body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>The goal is to transpose the excel file that comes in the following form</p> <p><a href="https://i.stack.imgur.com/Svd49.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Svd49.png" alt="enter image description here" /></a></p> <p>into this</p> <p><a href="https://i.stack.imgur.com/PlbRB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PlbRB.png" alt="enter image description here" /></a></p> <p>The code I created works properly, but I think it can be improved.</p> <p>I would also like to avoid using <code>reduce</code> to avoid importing <code>functools</code>.</p> <pre><code>#importing the libraries import pandas as pd from functools import reduce #defining the mapping list descriptions_pizzeria = [ &quot;Pizzeria Da Michele - Napoli&quot;, &quot;Pizzeria Da Michele - Roma&quot;, &quot;Pizzeria Da Michele - Bologna&quot;, &quot;Pizzeria Da Michele - Londra&quot;, ] pizzeria_code = [ 1, 2, 3 ] #path where the data are stored url_path = &quot;https://github.com/uomodellamansarda/AC_StackQuestions/blob/main/Pizzerie.xlsx? raw=true&quot; #reading the data df = pd.read_excel(url_path, index_col=0, header=3) #printing to have an idea print(df) #from an inspection we now that #the first column is where the Pizzeria code is stored #but we need to rename it #we need to rename the first column df = df.rename(columns={&quot;Unnamed: 1&quot;:&quot;Pizzeria code&quot;}) print(df.info()) #Grouping based on the pizzeria code G = df.groupby('Pizzeria code') pizzeria_df_list = [] for i, code in enumerate(pizzeria_code): #selecting the related Pizzeria commercial name description = descriptions_pizzeria[i] df_temp = G.get_group(code) #Dropping and trasposing the Pizzeria Code column df_temp = df_temp.drop(columns=&quot;Pizzeria code&quot;).transpose() #Based on what we know about the columns we can create the suffix col_suffix = ['Average Values', '# of customers ', 'Servings'] #and rename the columns df_temp.columns = [description + &quot;_&quot; + x for x in col_suffix] pizzeria_df_list.append(df_temp) pizzeria_df = reduce(lambda x, y: pd.merge(x, y,right_index=True, left_index=True), pizzeria_df_list) pizzeria_df.to_excel(&quot;Pizzeria_trasposed.xlsx&quot;) </code></pre>
[]
[ { "body": "<h2>TL;DR</h2>\n<p>Instead of looping through each pizzeria and merging temporary subframes, it's more idiomatic to manipulate/map the columns at once.</p>\n<p>The bulk of the work is just changing the original columns (left) to be filled/dropped/sorted/renamed (right):</p>\n<pre class=\"lang-none prettyprint-override\"><code> FROM THESE TO THESE \n|----------------------|-------------------------------------------------|\n| Category Pizzeria | Category Pizzeria |\n| Sales NaN | |\n| NaN 1.0 | Average Values Pizzeria Da Michele - Napoli |\n| NaN 2.0 | # of Customers Pizzeria Da Michele - Napoli |\n| NaN 3.0 | Servings Pizzeria Da Michele - Napoli |\n| People NaN | |\n| NaN 1.0 | Average Values Pizzeria Da Michele - Roma |\n| NaN 2.0 | # of Customers Pizzeria Da Michele - Roma |\n| NaN 3.0 | Servings Pizzeria Da Michele - Roma |\n| Dishes NaN | |\n| NaN 1.0 | Average Values Pizzeria Da Michele - Bologna |\n| NaN 2.0 | # of Customers Pizzeria Da Michele - Bologna |\n| NaN 3.0 | Servings Pizzeria Da Michele - Bologna |\n|----------------------|-------------------------------------------------|\n</code></pre>\n<pre><code>df = pd.read_excel(url_path, header=3)\ndf = df.rename(columns={'Unnamed: 0': 'Category', 'Unnamed: 1': 'Pizzeria'})\n\n# fill the null categories\ndf['Category'] = df['Category'].ffill()\n\n# group up the pizzerias\ndf = df.dropna().sort_values('Pizzeria')\n\n# map to the preferred pizzeria names\ndf['Pizzeria'] = df['Pizzeria'].map({\n 1: 'Pizzeria Da Michele - Napoli',\n 2: 'Pizzeria Da Michele - Roma',\n 3: 'Pizzeria Da Michele - Bologna',\n 4: 'Pizzeria Da Michele - Londra',\n})\n\n# map to the preferred category names\ndf['Category'] = df['Category'].map({\n 'Dishes': 'Servings',\n 'People': '# of Customers',\n 'Sales': 'Average Values',\n})\n\n# set the combined pizzeria_category as the index\ndf = df.set_index(['Pizzeria', 'Category'])\ndf.index = [f'{p}_{c}' for p, c in df.index] # or ['_'.join(i) for i in df.index]\n\n# transpose and output\ndf.T.to_excel('Pizzeria_transposed.xlsx')\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code> Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele -\n Napoli_Average Values Napoli_# of Customers Napoli_Servings Roma_Average Values Roma_# of Customers Roma_Servings Bologna_Average Values Bologna_# of Customers Bologna_Servings\n2021-11-01 00:00:00 100.0 70.0 10.0 300.0 200.0 30.0 50.0 20.0 5.0 \n2021-11-08 00:00:00 250.0 160.0 25.0 350.0 150.0 35.0 100.0 70.0 10.0 \n2021-11-15 00:00:00 100.0 70.0 10.0 500.0 300.0 50.0 250.0 160.0 25.0 \n2021-11-22 00:00:00 300.0 200.0 30.0 2000.0 1000.0 200.0 10.0 20.0 1.0 \n2021-11-29 00:00:00 400.0 250.0 40.0 1000.0 500.0 100.0 300.0 200.0 30.0 \n</code></pre>\n<hr />\n<h2>Detailed breakdown</h2>\n<ol>\n<li><p>Load the excel sheet without setting <code>index_col</code> because it will be easier to manipulate the <code>Category</code> as a column rather than index:</p>\n<pre><code>df = pd.read_excel(url_path, header=3)\ndf = df.rename(columns={'Unnamed: 0': 'Category', 'Unnamed: 1': 'Pizzeria'})\n\n# Category Pizzeria 2021-11-01 00:00:00 2021-11-08 00:00:00 2021-11-15 00:00:00 2021-11-22 00:00:00 2021-11-29 00:00:00\n# 0 Sales NaN NaN NaN NaN NaN NaN\n# 1 NaN 1.0 100.0 250.0 100.0 300.0 400.0\n# 2 NaN 2.0 300.0 350.0 500.0 2000.0 1000.0\n# 3 NaN 3.0 50.0 100.0 250.0 10.0 300.0\n# 4 People NaN NaN NaN NaN NaN NaN\n# 5 NaN 1.0 70.0 160.0 70.0 200.0 250.0\n# 6 NaN 2.0 200.0 150.0 300.0 1000.0 500.0\n# 7 NaN 3.0 20.0 70.0 160.0 20.0 200.0\n# 8 Dishes NaN NaN NaN NaN NaN NaN\n# 9 NaN 1.0 10.0 25.0 10.0 30.0 40.0\n# 10 NaN 2.0 30.0 35.0 50.0 200.0 100.0\n# 11 NaN 3.0 5.0 10.0 25.0 1.0 30.0\n</code></pre>\n</li>\n<li><p><a href=\"https://pandas.pydata.org/docs/reference/api/pandas.Series.ffill.html\" rel=\"nofollow noreferrer\"><code>ffill</code></a> (forward-fill) the null <code>Category</code> values and then sort by <code>Pizzeria</code> so that the pizzerias are grouped up:</p>\n<pre><code>df['Category'] = df['Category'].ffill()\ndf = df.dropna().sort_values('Pizzeria')\n\n# Category Pizzeria 2021-11-01 00:00:00 2021-11-08 00:00:00 2021-11-15 00:00:00 2021-11-22 00:00:00 2021-11-29 00:00:00\n# 1 Sales 1.0 100.0 250.0 100.0 300.0 400.0\n# 5 People 1.0 70.0 160.0 70.0 200.0 250.0\n# 9 Dishes 1.0 10.0 25.0 10.0 30.0 40.0\n# 2 Sales 2.0 300.0 350.0 500.0 2000.0 1000.0\n# 6 People 2.0 200.0 150.0 300.0 1000.0 500.0\n# 10 Dishes 2.0 30.0 35.0 50.0 200.0 100.0\n# 3 Sales 3.0 50.0 100.0 250.0 10.0 300.0\n# 7 People 3.0 20.0 70.0 160.0 20.0 200.0\n# 11 Dishes 3.0 5.0 10.0 25.0 1.0 30.0\n</code></pre>\n</li>\n<li><p><a href=\"https://pandas.pydata.org/docs/reference/api/pandas.Series.map.html\" rel=\"nofollow noreferrer\"><code>map</code></a> <code>Pizzeria</code> and <code>Category</code> to your preferred strings:</p>\n<pre><code>df['Pizzeria'] = df['Pizzeria'].map({\n 1: 'Pizzeria Da Michele - Napoli',\n 2: 'Pizzeria Da Michele - Roma',\n 3: 'Pizzeria Da Michele - Bologna',\n 4: 'Pizzeria Da Michele - Londra',\n})\ndf['Category'] = df['Category'].map({\n 'Dishes': 'Servings',\n 'People': '# of Customers',\n 'Sales': 'Average Values',\n})\n\n# Category Pizzeria 2021-11-01 00:00:00 2021-11-08 00:00:00 2021-11-15 00:00:00 2021-11-22 00:00:00 2021-11-29 00:00:00\n# 1 Average Values Pizzeria Da Michele - Napoli 100.0 250.0 100.0 300.0 400.0\n# 5 # of Customers Pizzeria Da Michele - Napoli 70.0 160.0 70.0 200.0 250.0\n# 9 Servings Pizzeria Da Michele - Napoli 10.0 25.0 10.0 30.0 40.0\n# 2 Average Values Pizzeria Da Michele - Roma 300.0 350.0 500.0 2000.0 1000.0\n# 6 # of Customers Pizzeria Da Michele - Roma 200.0 150.0 300.0 1000.0 500.0\n# 10 Servings Pizzeria Da Michele - Roma 30.0 35.0 50.0 200.0 100.0\n# 3 Average Values Pizzeria Da Michele - Bologna 50.0 100.0 250.0 10.0 300.0\n# 7 # of Customers Pizzeria Da Michele - Bologna 20.0 70.0 160.0 20.0 200.0\n# 11 Servings Pizzeria Da Michele - Bologna 5.0 10.0 25.0 1.0 30.0\n</code></pre>\n</li>\n<li><p>Join <code>Pizzeria</code> and <code>Category</code> inside the index (either explicitly unpack+concat the tuples or <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>join</code></a> them):</p>\n<pre><code>df = df.set_index(['Pizzeria', 'Category'])\ndf.index = [f'{p}_{c}' for p, c in df.index] # or ['_'.join(i) for i in df.index]\n\n# 2021-11-01 00:00:00 2021-11-08 00:00:00 2021-11-15 00:00:00 2021-11-22 00:00:00 2021-11-29 00:00:00\n# Pizzeria Da Michele - Napoli_Average Values 100.0 250.0 100.0 300.0 400.0\n# Pizzeria Da Michele - Napoli_# of Customers 70.0 160.0 70.0 200.0 250.0\n# Pizzeria Da Michele - Napoli_Servings 10.0 25.0 10.0 30.0 40.0\n# Pizzeria Da Michele - Roma_Average Values 300.0 350.0 500.0 2000.0 1000.0\n# Pizzeria Da Michele - Roma_# of Customers 200.0 150.0 300.0 1000.0 500.0\n# Pizzeria Da Michele - Roma_Servings 30.0 35.0 50.0 200.0 100.0\n# Pizzeria Da Michele - Bologna_Average Values 50.0 100.0 250.0 10.0 300.0\n# Pizzeria Da Michele - Bologna_# of Customers 20.0 70.0 160.0 20.0 200.0\n# Pizzeria Da Michele - Bologna_Servings 5.0 10.0 25.0 1.0 30.0\n</code></pre>\n</li>\n<li><p>Finally transpose and save:</p>\n<pre><code>df.T.to_excel('Pizzeria_transposed.xlsx')\n\n# Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele - Pizzeria Da Michele -\n# Napoli_Average Values Napoli_# of Customers Napoli_Servings Roma_Average Values Roma_# of Customers Roma_Servings Bologna_Average Values Bologna_# of Customers Bologna_Servings\n# 2021-11-01 00:00:00 100.0 70.0 10.0 300.0 200.0 30.0 50.0 20.0 5.0 \n# 2021-11-08 00:00:00 250.0 160.0 25.0 350.0 150.0 35.0 100.0 70.0 10.0 \n# 2021-11-15 00:00:00 100.0 70.0 10.0 500.0 300.0 50.0 250.0 160.0 25.0 \n# 2021-11-22 00:00:00 300.0 200.0 30.0 2000.0 1000.0 200.0 10.0 20.0 1.0 \n# 2021-11-29 00:00:00 400.0 250.0 40.0 1000.0 500.0 100.0 300.0 200.0 30.0 \n</code></pre>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T17:32:15.713", "Id": "533436", "Score": "2", "body": "Nice explanation and definitely more pandas-idiomatic. I would suggest in step 3, `dict(enumerate(descriptions_pizzeria, 1))` is maybe a bit too clever, and instead `descriptions_pizzeria` should be merged with `pizzeria_code` and become a simple dictionary or intenum, mapping location codes to strings. This way the correspondence is explicit so you don't end up accidentally adding a name to the wrong index in the list and making the auto mapping invalid, if that makes sense. Also more efficient at runtime to predefine this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T17:39:45.627", "Id": "533438", "Score": "2", "body": "Also in section 4 `df.index = ['_'.join(i) for i in df.index]` maybe do a tuple unpacking to make it more explicit, e.g. `df.index = [f\"{pizzeria}_{sales_category}\" for pizzeria, sales_category in df.index]` - it's less performant than your approach but a lot clearer I think and this is not a performance bottleneck in the code so I'd take that trade-off :). Subjective though..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T17:46:30.380", "Id": "533439", "Score": "0", "body": "@Greedo Thanks for the feedback! Great points -- will update." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T09:03:15.297", "Id": "270190", "ParentId": "270174", "Score": "3" } } ]
{ "AcceptedAnswerId": "270190", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T18:44:21.350", "Id": "270174", "Score": "3", "Tags": [ "python", "excel", "pandas" ], "Title": "Transposing an Excel sheet with pandas adding additional information for a different readability - Using Fake Pizzeria Data" }
270174
<p>I have (for example) the following license plate image: <a href="https://i.stack.imgur.com/ibnL8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ibnL8.png" alt="enter image description here" /></a></p> <p>And I want to segment the characters. The code I have so far consists of me using <code>cv2.MSER</code> to detect regions in the image. Afterwards I create bounding rectangles for each of the contours and create a dictionary according to height of the bounding boxes (characters). Then I get a dictionary key with the biggest number of items, this is an assumption, as there should not be anything else in the image other than the characters that are clearly visible and of the same height (relatively). The values of the key are x,y coordinates and width and height parameters of the bounding box. Afterwards, I sort the items of this dict key according to the x value, so that they are ordered as in the license plate image from left to right. Then I loop through the list in reverse order to remove duplicates (based on Euclidean distance I believe). What I want to know if there is any step of this process that could be improved upon, or if there is a defect in the thinking process. Code for show:</p> <pre><code>import cv2 import numpy as np img = cv2.imread('path_to_img', 0) mser = cv2.MSER_create() regions = mser.detectRegions(img)[0] h_dict = {} # group contours according to height for cnt in regions: x,y,w,h = cv2.boundingRect(cnt) if h in h_dict: if (x,y,w,h) not in h_dict[h]: h_dict[h].append((x,y,w,h)) else: continue else: h_dict[h] = [(x,y,w,h)] longest_key = max(h_dict, key=lambda x: len(h_dict[x])) sorted_longest = sorted(h_dict[longest_key], key=lambda x: [x][0]) # order according to x coordinate # remove duplicates for i, val in reversed(list(enumerate(sorted_longest))): for j, val2 in reversed(list(enumerate(sorted_longest))): if j &gt; i: result_dist = np.linalg.norm(np.asarray(val) - np.asarray(val2)) if result_dist &lt; 2: del sorted_longest[j] </code></pre> <p>Resulting image horizontally stacked: <a href="https://i.stack.imgur.com/26qLJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/26qLJ.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T21:30:44.077", "Id": "533549", "Score": "1", "body": "I'm not sure I understand the logic of using the height as a key... Are you saying that all letters and numbers to be extracted are exactly the same height in pixels? That cannot always be true, can it? Even the slightest bit of noise or geometric distortion will make one character a pixel taller than its neighbor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T00:30:15.623", "Id": "533556", "Score": "0", "body": "I have thought about pooling contours of \"roughly\" the same height together, e.g. of height 39-43 as height 41." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T20:26:33.657", "Id": "270175", "Score": "3", "Tags": [ "python", "opencv" ], "Title": "Segment characters from license plate image according to regions with same height" }
270175
<p>I have this calculator. The user is asked to provide three numbers as well as the numeric operation they wish to perform. Based on this input, a certain case will be executed. The calculator is supposed to cover the basic arithmetic options such as + - * / as well as that &quot;dividing or multiplying numbers are stronger actions than adding or subtracting numbers&quot;, if that makes sense (sorry, I am not a native speaker).</p> <p>I think it works, but the code is clumsy and way too long. I feel like there must be a better way, but I don't really know how to improve the code as I am new to this.</p> <p>This is the code:</p> <pre class="lang-cs prettyprint-override"><code>using System; namespace Program { class Taschenrechner2 { public static void Main() { double eingabe1, eingabe2, eingabe3; string rechenoperator1, rechenoperator2; Console.WriteLine(&quot;Geben Sie die erste Zahl ein.&quot;); eingabe1 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine(&quot;Geben Sie die erste Rechenoperation ein.&quot;); rechenoperator1 = Console.ReadLine(); Console.WriteLine(&quot;Geben Sie die zweite Zahl ein.&quot;); eingabe2 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine(&quot;Geben Sie die zweite Rechenoperation ein.&quot;); rechenoperator2 = Console.ReadLine(); Console.WriteLine(&quot;Geben Sie die dritte Zahl ein.&quot;); eingabe3 = Convert.ToDouble(Console.ReadLine()); if (rechenoperator1 == &quot;-&quot; &amp;&amp; rechenoperator2 == &quot;-&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + (eingabe1 - eingabe2 - eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;+&quot; &amp;&amp; rechenoperator2 == &quot;+&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + (eingabe1 + eingabe2 + eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;+&quot; &amp;&amp; rechenoperator2 == &quot;-&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + (eingabe1 + eingabe2 - eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;-&quot; &amp;&amp; rechenoperator2 == &quot;+&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + (eingabe1 - eingabe2 + eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;*&quot; &amp;&amp; rechenoperator2 == &quot;+&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + ((eingabe1 * eingabe2) + eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;+&quot; &amp;&amp; rechenoperator2 == &quot;*&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + ((eingabe1 + eingabe2) * eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;-&quot; &amp;&amp; rechenoperator2 == &quot;*&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + ((eingabe1 - eingabe2) * eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;*&quot; &amp;&amp; rechenoperator2 == &quot;-&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + ((eingabe1 * eingabe2) - eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;*&quot; &amp;&amp; rechenoperator2 == &quot;*&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + (eingabe1 * eingabe2 * eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;*&quot; &amp;&amp; rechenoperator2 == &quot;/&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + ((eingabe1 * eingabe2) / eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;/&quot; &amp;&amp; rechenoperator2 == &quot;*&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + ((eingabe1 / eingabe2) * eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;-&quot; &amp;&amp; rechenoperator2 == &quot;/&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + (eingabe1 - (eingabe2 / eingabe3))); Console.ReadKey(); } if (rechenoperator1 == &quot;/&quot; &amp;&amp; rechenoperator2 == &quot;-&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + ((eingabe1 / eingabe2) - eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;+&quot; &amp;&amp; rechenoperator2 == &quot;/&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + (eingabe1 + (eingabe2 / eingabe3))); Console.ReadKey(); } if (rechenoperator1 == &quot;/&quot; &amp;&amp; rechenoperator2 == &quot;+&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + ((eingabe1 / eingabe2) + eingabe3)); Console.ReadKey(); } if (rechenoperator1 == &quot;/&quot; &amp;&amp; rechenoperator2 == &quot;/&quot;) { Console.WriteLine(&quot;Das Ergebnis ist: &quot; + ((eingabe1 / eingabe2) / eingabe3)); Console.ReadKey(); } } } } </code></pre> <p>I have tried to teach myself how to program multiple times, but every time I didn't manage to get further than the basics... This time I hope to get further, so any help would be appreciated!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T00:50:00.257", "Id": "533384", "Score": "0", "body": "*dividing or multiplying numbers are stronger actions than adding or subtracting numbers* \"precedence\" is word you want. It means \"priority of action\" As in: \"multiplication takes precedence over addition\"" } ]
[ { "body": "<p>Welcome to the site! The best way to learn is to experiment and have fun!</p>\n<p>The key to simplifying code is to find patterns. This will be easier to find if we sort all the <code>if</code> statements by operation like the following:</p>\n<pre><code>if (rechenoperator1 == &quot;+&quot; &amp;&amp; rechenoperator2 == &quot;+&quot;) { ... }\nif (rechenoperator1 == &quot;+&quot; &amp;&amp; rechenoperator2 == &quot;-&quot;) { ... }\nif (rechenoperator1 == &quot;+&quot; &amp;&amp; rechenoperator2 == &quot;*&quot;) { ... }\nif (rechenoperator1 == &quot;+&quot; &amp;&amp; rechenoperator2 == &quot;/&quot;) { ... }\nif (rechenoperator1 == &quot;-&quot; &amp;&amp; rechenoperator2 == &quot;+&quot;) { ... }\nif (rechenoperator1 == &quot;-&quot; &amp;&amp; rechenoperator2 == &quot;-&quot;) { ... }\nif (rechenoperator1 == &quot;-&quot; &amp;&amp; rechenoperator2 == &quot;*&quot;) { ... }\nif (rechenoperator1 == &quot;-&quot; &amp;&amp; rechenoperator2 == &quot;/&quot;) { ... }\nif (rechenoperator1 == &quot;*&quot; &amp;&amp; rechenoperator2 == &quot;+&quot;) { ... }\nif (rechenoperator1 == &quot;*&quot; &amp;&amp; rechenoperator2 == &quot;-&quot;) { ... }\nif (rechenoperator1 == &quot;*&quot; &amp;&amp; rechenoperator2 == &quot;*&quot;) { ... }\nif (rechenoperator1 == &quot;*&quot; &amp;&amp; rechenoperator2 == &quot;/&quot;) { ... }\nif (rechenoperator1 == &quot;/&quot; &amp;&amp; rechenoperator2 == &quot;+&quot;) { ... }\nif (rechenoperator1 == &quot;/&quot; &amp;&amp; rechenoperator2 == &quot;-&quot;) { ... }\nif (rechenoperator1 == &quot;/&quot; &amp;&amp; rechenoperator2 == &quot;*&quot;) { ... }\nif (rechenoperator1 == &quot;/&quot; &amp;&amp; rechenoperator2 == &quot;/&quot;) { ... }\n</code></pre>\n<p>See the pattern? I hope so :-)</p>\n<p>What can we do with this? First, we can create a function like the following to take care of the first operation:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static double Berechnungsteil(double eingabe1, double eingabe2, string operation)\n{\n switch (operation)\n {\n case &quot;+&quot;:\n return eingabe1 + eingabe2;\n case &quot;-&quot;:\n return eingabe1 - eingabe2;\n case &quot;*&quot;:\n return eingabe1 * eingabe2;\n case &quot;/&quot;:\n return eingabe1 / eingabe2;\n default:\n return 0;\n }\n}\n</code></pre>\n<p>This can then be used to calculate the first part like so:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>double resultFirstPart = Berechnungsteil(eingabe1, eingabe2, rechenoperator1);\n</code></pre>\n<p>To calculate the final result we can take <code>resultFirstPart</code> and call `Berechnungsteil' again:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>double result = Berechnungsteil(resultFirstPart, eingabe3, rechenoperator2);\n</code></pre>\n<p>To get the correct order of operations, we can simply check if the first operation is <code>*</code> or <code>/</code>.</p>\n<p>Putting it all together:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\n\nnamespace Program\n{\n class Taschenrechner2\n {\n public static double Berechnungsteil(double eingabe1, double eingabe2, string operation)\n {\n switch (operation)\n {\n case &quot;+&quot;:\n return eingabe1 + eingabe2;\n case &quot;-&quot;:\n return eingabe1 - eingabe2;\n case &quot;*&quot;:\n return eingabe1 * eingabe2;\n case &quot;/&quot;:\n return eingabe1 / eingabe2;\n default:\n return 0;\n }\n }\n\n public static void Main()\n {\n Console.WriteLine(&quot;Geben Sie die erste Zahl ein.&quot;);\n double eingabe1 = Convert.ToDouble(Console.ReadLine());\n\n Console.WriteLine(&quot;Geben Sie die erste Rechenoperation ein.&quot;);\n string rechenoperator1 = Console.ReadLine();\n\n Console.WriteLine(&quot;Geben Sie die zweite Zahl ein.&quot;);\n double eingabe2 = double.Parse(Console.ReadLine());\n\n Console.WriteLine(&quot;Geben Sie die zweite Rechenoperation ein.&quot;);\n string rechenoperator2 = Console.ReadLine();\n\n Console.WriteLine(&quot;Geben Sie die dritte Zahl ein.&quot;);\n double eingabe3 = double.Parse(Console.ReadLine());\n\n if (rechenoperator1 == &quot;*&quot; || rechenoperator1 == &quot;/&quot;)\n {\n double resultFirstPart = Berechnungsteil(eingabe1, eingabe2, rechenoperator1);\n Console.WriteLine(&quot;Das Ergebnis ist: &quot; + Berechnungsteil(resultFirstPart, eingabe3, rechenoperator2));\n }\n else\n {\n double resultFirstPart = Berechnungsteil(eingabe2, eingabe3, rechenoperator2);\n Console.WriteLine(&quot;Das Ergebnis ist: &quot; + Berechnungsteil(resultFirstPart, eingabe1, rechenoperator1));\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T08:31:42.320", "Id": "533397", "Score": "0", "body": "Thank you, I wouldn't have thought of that myself. How can I improve my way of thinking in that regard? Any project ideas maybe or tips?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T13:02:14.707", "Id": "533419", "Score": "0", "body": "@morloq, It's all about breaking down problems into manageable parts. Get out the whiteboard and ask yourself: what are the logical steps that I need to do to make this work. Implementing PEMDAS math in code is supprising difficult and I know a couple of decent programmers that would not have gotten as far as you did :-). Project ideas: simple games like tick tack toe, checkers, card games, etc. If you are feeling brave create your own calculator that can work on strings like the following `(3 * 3 + 4 * 4) ^ .5`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T13:04:49.153", "Id": "533420", "Score": "0", "body": "Thanks, I think Ill go with tack tack toe. Is it bad for the learning process to google if you are stuck or do not know how to implement something? For instance, I know what tick tack toe is and how it should work but I have no idea where to start and how to even generate the graphic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T13:06:23.447", "Id": "533421", "Score": "0", "body": "@morloq, not at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T16:52:51.517", "Id": "533582", "Score": "0", "body": "@morloq, here is something to get you started [TIO](https://tio.run/##vVJda8IwFH3Pr7j4YourWvcp3V621w1kFjaQPoR4p4GaSBInw/W3dzHVrpmKb7uQ5nJz7jm9H0xHTLOyXGkuZjD@0gYXCSGCLlAvKUNI05RsCFhjOdUaRkrOFF24SBXfmjbUcAafkk8tggvzKKmaBmxO1SQDhnmuwxr8m7a1Jym0zLH7prjBZy4waMGmX8A3bGL3HRSti4pi0s/2Xlx7gyxMzhFGUdTZndZ59En5y1r0qvau/0/@pha9rb27pnxBjg7khXIRnGp/rwdccFPReS/N4cEDCFxXoWHml/AhFQR25MAtqp/Y6x6G9up0Qg/n6zoFVwLPbF4b2j5ro5bdb87sTkIu5dJ7WM95jhAYtcJzcs3FdBuZkAPMkXmMMUdWNQhiiGD4d4Zbc/WL5crYWqzfHVGlMdizvSKdOrLwmOauDS47gti14/2gHb5XkKIsfwA)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T19:33:54.333", "Id": "533587", "Score": "0", "body": "Thanks, that's kind of you! I'm actually a bit further along with that (thanks to some tutorials). Currently I have the problem that a place can be marked more than once, not sure how to fix that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T19:59:31.850", "Id": "533589", "Score": "0", "body": "@morloq, Hint, you have to create a loop and keep on asking for an input until `input >= 0` and `input <= 9` and cells[input - 1] == ' '" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T12:44:35.347", "Id": "533680", "Score": "0", "body": "@morloq, Congratulations, I see you did it! Do not get discouraged by any answers you get, remember that there are many ways to skin a cat ;-)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T22:10:25.877", "Id": "270181", "ParentId": "270177", "Score": "1" } } ]
{ "AcceptedAnswerId": "270181", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T20:44:41.090", "Id": "270177", "Score": "1", "Tags": [ "c#", "calculator" ], "Title": "How can I implement this calculator in a better way?" }
270177
<p>My assignment was to write a function that computes the value of an expression written in infix notation. We assume that we are using the four classical arithmetic operations +, -, * and / and that each binary operation is enclosed in parentheses.</p> <p>My stack:</p> <pre><code>class Stack: def __init__(self): self._arr = list() def push(self, item): self._arr.append(item) #return self def pop(self): assert not self.is_empty(), &quot;pop() on empty stack&quot; return self._arr.pop() def is_empty(self): return not bool(self._arr) def peek(self): assert not self.is_empty(), &quot;peek() on empty stack&quot; return self._arr[-1] def all_items(self): return self._arr def value_at_index(self, value): try: return self.items[value] except: return False def __len__(self): return len(self._arr) </code></pre> <p>The code:</p> <pre><code>def infix_brackets_eval(data): Stack = Stack() i = 0 ret = 0 while i &lt; len(data): if data[i] != ' ': if data[i] not in '+-*/()': temp = 0 while data[i] != ' ' and data[i]!= ')': temp = temp * 10 + int(data[i]) i+=1 i-=1 elif data[i] == ')': B = Stack.peek() Stack.pop() x = Stack.peek() Stack.pop() A = Stack.peek() Stack.pop() if Stack.peek() == '(': Stack.pop() if x == '-': temp = A - B elif x == '+': temp = A + B elif x == '*': temp = A * B elif x == '/': temp = A / B else: temp = data[i] #print(temp) Stack.push(temp) i += 1 return Stack.peek() infix_brackets_eval(&quot;((12 * 3) + (2 + 3) * (1 * 3))&quot;) </code></pre> <p>Output:</p> <pre><code>15 </code></pre> <p>Apart from the code comments of course, could any of you point me to an example use of a tokenizer or parser? I am very curious about the application and mechanics of how to use it, in the case when the tokens are operands, tokenize also need multi-digit numbers. Unfortunately I do not know where to look. I tried to rely on various documentation but I can not translate it to this example.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T22:24:20.600", "Id": "533377", "Score": "3", "body": "Are you [KermitTheFrog](https://codereview.stackexchange.com/users/241883/kermitthefrog)? Because your `Stack` is almost exactly the same as in [Kermit's question](https://codereview.stackexchange.com/q/270063)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T22:59:52.723", "Id": "533379", "Score": "0", "body": "well... we are classmates" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T23:00:25.250", "Id": "533380", "Score": "0", "body": "And now we r both struggling with your comment about parsing/tokenizer @Peilonrayz :D" } ]
[ { "body": "<ul>\n<li><p>Python <code>list</code>s are stacks. I'd recommend removing the <code>Stack</code> class.</p>\n</li>\n<li><p>You should split tokenization away from evaluation.\nWhilst the tokenization you need is quite simple, tokenization can get quite complicated.\nNot only will you shoot yourself in the foot, but the code is harder to read with tokenization and evaluation in the same function.</p>\n</li>\n<li><p>Your variable names are not great.</p>\n</li>\n</ul>\n<p>Lets use TDD to build the tokenizer:</p>\n<ol>\n<li><p>We'll handle only numbers.<br />\nHowever only one character, and we'll convert to an int.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def tokenize(text):\n for char in text:\n if char in &quot;0123456789&quot;:\n yield int(char)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; list(tokenize(&quot;123&quot;))\n[1, 2, 3]\n</code></pre>\n</li>\n<li><p>We'll handle one number of any size.<br />\nWe'll build up a 'token' stack.\nWe'll use a list to ensure <span class=\"math-container\">\\$O(1)\\$</span> time when adding new characters.\nThis is because Python's strings guaranteed a minimum <span class=\"math-container\">\\$O(n)\\$</span> time when adding.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def tokenize(text):\n token = []\n for char in text:\n if char in &quot;0123456789&quot;:\n token.append(char)\n if token:\n yield int(&quot;&quot;.join(token))\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; list(tokenize(&quot;1 2 3&quot;))\n[123]\n&gt;&gt;&gt; list(tokenize(&quot;&quot;))\n[]\n</code></pre>\n</li>\n<li><p>We'll handle spaces.<br />\nWe just need to copy the <code>if token</code> code.\nAnd reset <code>token</code> after yielding one.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def tokenize(text):\n token = []\n for char in text:\n if char in &quot;0123456789&quot;:\n token.append(char)\n elif char in &quot; &quot;:\n if token:\n yield int(&quot;&quot;.join(token))\n token = []\n if token:\n yield int(&quot;&quot;.join(token))\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; list(tokenize(&quot;1 2 3&quot;))\n[1, 2, 3]\n</code></pre>\n</li>\n<li><p>We'll handle operators.<br />\nBasically the same as spaces but we also yield the operator.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def tokenize(text):\n token = []\n for char in text:\n if char in &quot;0123456789&quot;:\n token.append(char)\n elif char in &quot; +-*/()&quot;:\n if token:\n yield int(&quot;&quot;.join(token))\n token = []\n if char != &quot; &quot;:\n yield char\n if token:\n yield int(&quot;&quot;.join(token))\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; list(tokenize(&quot;1+ 2+3&quot;))\n[1, &quot;+&quot;, 2, &quot;+&quot;, 3]\n</code></pre>\n</li>\n<li><p>Error on unknown values.<br />\nYou should error on malformed input.\nThe hard part of programming is handling user input.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def tokenize(text):\n token = []\n for char in text:\n if char in &quot;0123456789&quot;:\n token.append(char)\n elif char in &quot; +-*/()&quot;:\n if token:\n yield int(&quot;&quot;.join(token))\n token = []\n if char != &quot; &quot;:\n yield char\n else:\n raise ValueError(f&quot;unknown character {char!r}&quot;)\n if token:\n yield int(&quot;&quot;.join(token))\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; list(tokenize(&quot;~&quot;))\nValueError: unknown character '~'\n</code></pre>\n</li>\n</ol>\n<p>Since we've handled the tokenization, all we need to do is use your <code>if data[i] == ')'</code> code.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def evaluate_infix(tokens):\n stack = []\n for token in tokens:\n if token == &quot;)&quot;:\n lhs, op, rhs = stack[-3:]\n del stack[-3:]\n if stack[-1] == &quot;(&quot;:\n del stack[-1]\n if op == '-':\n token = lhs - rhs\n elif op == '+':\n token = lhs + rhs\n elif op == '*':\n token = lhs * rhs\n elif op == '/':\n token = lhs / rhs\n stack.append(token)\n return stack[-1]\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; evaluate_infix(tokenize(&quot;((12 * 3) + (2 + 3) * (1 * 3))&quot;))\n15\n</code></pre>\n<blockquote>\n<p>The hard part of programming is handling user input.</p>\n</blockquote>\n<p>You have a bug:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; ((12 * 3) + (2 + 3) * (1 * 3))\n51\n</code></pre>\n<p>The <code>if stack[-1] == &quot;(&quot;:</code> check shouldn't be optional.\nA &quot;(&quot; should always be required. As such, your input is invalid but you've not noticed.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def evaluate_infix(tokens):\n stack = []\n for token in tokens:\n if token == &quot;)&quot;:\n lb, lhs, op, rhs = stack[-4:]\n del stack[-4:]\n if lb != &quot;(&quot;:\n raise ValueError(&quot;three tokens must be between parens&quot;)\n if op == '-':\n token = lhs - rhs\n elif op == '+':\n token = lhs + rhs\n elif op == '*':\n token = lhs * rhs\n elif op == '/':\n token = lhs / rhs\n stack.append(token)\n return stack[-1]\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; evaluate_infix(tokenize(&quot;((12 * 3) + ((2 + 3) * (1 * 3)))&quot;))\n51\n&gt;&gt;&gt; evaluate_infix(tokenize(&quot;((12 * 3) + (2 + 3) * (1 * 3))&quot;))\nValueError: three tokens must be between parens\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T09:44:48.700", "Id": "533406", "Score": "0", "body": "What variables names i should use in this case? What would be more \"proffesional\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T18:22:26.500", "Id": "533444", "Score": "0", "body": "@TheUselessProgrammer4 I've renamed a number of your variables. `A`-> `lhs`, `B` -> `rhs`, `x` -> `op`, `temp` -> `token`. Your names can mean anything, where the names I've picked say what the variables contain." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T23:58:47.523", "Id": "270184", "ParentId": "270180", "Score": "2" } } ]
{ "AcceptedAnswerId": "270184", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T21:50:17.993", "Id": "270180", "Score": "1", "Tags": [ "python", "python-3.x", "homework", "math-expression-eval" ], "Title": "Evaluating infix expression with brackets" }
270180
<p>I'm a Python novice. The system I'm using is called IBM <a href="http://ibm.com/docs/en/mam/7.6.1.2" rel="nofollow noreferrer">Maximo Asset Management</a>. In Maximo, we can write Python scripts that utilize Maximo's Java API/methods. So the script is technically a <a href="https://www.jython.org/" rel="nofollow noreferrer">Jython</a> script (Python + Java methods).</p> <hr /> <p>I've written a <a href="https://www.ibm.com/docs/en/mam/7.6.1.2?topic=product-automating-routine-tasks" rel="nofollow noreferrer">scheduled Jython 2.7 script</a> for checking an external system's <a href="https://enterprise.arcgis.com/en/server/10.7/publish-services/windows/what-is-a-map-service.htm" rel="nofollow noreferrer">web service</a> for issues.</p> <p>The idea is that this script would be run on a nightly schedule -- just after a scheduled integration has completed. I don't have control over the scheduled integration (I can't build this script right into the integration), but at least I can run a separate job to check for possible issues afterwards. And make it email me if it finds any issues.</p> <ol> <li>Did the web service produce an error?</li> <li>Are there any records that haven't been synced? (this is the <strong>main reason</strong> for the script)</li> <li>Did the web service time out? (the web service didn't have an error, it just didn't respond)</li> </ol> <hr /> <pre><code>from psdi.mbo import MboConstants from java.util import HashMap from com.ibm.json.java import JSONObject #The web service's vendor provides a public sample server that can be used for testing purposes: url = &quot;https://sampleserver6.arcgisonline.com/arcgis/rest/services/ServiceRequest/MapServer/1/query?where=SUBMITDT%3CDATE%272018-05-11%27&amp;f=pjson&amp;returnCountOnly=true&quot; def fetch_row_count(url): #Get the JSON text from the web service. ctx = HashMap() ctx.put(&quot;url&quot;, url) service.invokeScript(&quot;LIBHTTPCLIENT&quot;, ctx) json_text = str(ctx.get(&quot;response&quot;)) #Parse the row count from the JSON text` obj = JSONObject.parse(json_text) parsed_val = obj.get(&quot;count&quot;) return parsed_val try: result = fetch_row_count(url) if result == 0: print &quot;All records are synced. No need to do anything.&quot; #Check 1: elif result is None: #Email Template &quot;ERROR&quot;: &quot;The web service had an error when pinged.&quot; # &quot;Check for records that have not been synced.&quot; ctMboSet = mbo.getMboSet(&quot;$commtemp&quot;, &quot;COMMTEMPLATE&quot;, &quot;TEMPLATEID ='ERROR'&quot;) ctMbo = ctMboSet.getMbo(0) ctMbo.sendMessage(mbo, mbo) #Check 2: elif result &gt; 0: #Email Template &quot;NOSYNC&quot;: &quot;There are records that have not been synced.&quot; ctMboSet = mbo.getMboSet(&quot;$commtemp&quot;, &quot;COMMTEMPLATE&quot;, &quot;TEMPLATEID ='NOSYNC'&quot;) ctMbo = ctMboSet.getMbo(0) ctMbo.sendMessage(mbo, mbo) except: #Check 3 #Email Template &quot;TIMEOUT&quot;: &quot;The web service timed-out when pinged.&quot; # &quot;Check for records that have not been synced.&quot;&quot; ctMboSet = mbo.getMboSet(&quot;$commtemp&quot;, &quot;COMMTEMPLATE&quot;, &quot;TEMPLATEID ='TIMEOUT'&quot;) ctMbo = ctMboSet.getMbo(0) ctMbo.sendMessage(mbo, mbo) </code></pre> <p>You'll notice that I'm not passing information about errors to the emails that I'm sending (the emails are called &quot;Communication Templates&quot;). I'm not aware of an easy way to pass information, like &quot;Error 500&quot;, to the email communication templates. I think I'm stuck with sending generic emails -- the recipient will need to refer to the timestamp of the email and investigate the logs.</p> <hr /> <p>This is what's called a &quot;<a href="https://www.ibm.com/docs/en/maximo-for-utilities/7.6.0?topic=SSLLAM_7.6.0/com.ibm.mbs.doc/autoscript/c_example_reuse.html" rel="nofollow noreferrer">library script</a>&quot; in Maximo:</p> <p>LIBHTTPCLIENT (referenced in line #11 above)</p> <pre><code>from psdi.iface.router import HTTPHandler from java.util import HashMap from java.lang import String handler = HTTPHandler() map = HashMap() map.put(&quot;URL&quot;, url) map.put(&quot;HTTPMETHOD&quot;, &quot;GET&quot;) responseBytes = handler.invoke(map, None) response = String(responseBytes, &quot;utf-8&quot;) </code></pre> <hr /> <p>As a novice, I'm wondering if the script can be improved. Cheers.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T22:43:14.220", "Id": "270182", "Score": "1", "Tags": [ "python", "python-2.x", "status-monitoring", "jython" ], "Title": "Script to check a web service" }
270182
<p>this is my first ansible playbook.</p> <p>it installs docker in swarm mode and automatically joins the cluster.</p> <p>could you guys please review my code and show me where it can be improved?</p> <pre><code>- hosts: all tasks: - name: Add apt key apt_key: url: https://download.docker.com/linux/raspbian/gpg state: present - name: Remove some packages apt: autoclean: yes autoremove: yes state: absent pkg: [python2, python-configparser, python-is-python2] - name: Install a list of packages apt: update_cache: yes pkg: - apt-transport-https - aptitude - ca-certificates - curl - libffi-dev - libssl-dev - python3 - python-is-python3 - software-properties-common - name: Get docker convenience script shell: curl -fsSL https://get.docker.com -o get-docker.sh args: creates: ~/get-docker.sh - name: Install docker shell: sh ~/get-docker.sh args: creates: /usr/bin/docker - name: Config user permissions user: name=&quot;{{ ansible_user_id }}&quot; groups=docker append=yes generate_ssh_key=yes #shell: usermod -aG docker $(whoami) - name: Install docker-compose pip: name=docker-compose state=latest #shell: pip3 -v install -U docker-compose #args: # creates: /usr/local/bin/docker-compose - name: Start service service: name=docker enabled=yes state=started - name: Get docker info shell: docker info register: docker_info changed_when: False - hosts: docker_swarm_manager tasks: - name: Create primary swarm manager shell: docker swarm init --advertise-addr {{ ansible_default_ipv4.address }} when: &quot;docker_info.stdout.find('Swarm: inactive') &gt; 0&quot; - name: Get docker swarm manager ip copy: content: '{{ ansible_default_ipv4.address }}' dest: '/tmp/dsm_ip' - name: Get docker swarm manager token shell: docker swarm join-token -q manager register: swarm_manager_token - copy: content: '{{ swarm_manager_token.stdout }}' dest: '/tmp/dsm_mt' - name: Get docker swarm worker token shell: docker swarm join-token -q worker register: swarm_worker_token - copy: content: '{{ swarm_worker_token.stdout }}' dest: '/tmp/dsm_wt' - hosts: all tasks: - name: Join the swarm shell: &quot;docker swarm join --token {{ lookup('file', '/tmp/dsm_mt') }} {{ lookup('file', '/tmp/dsm_ip') }}:2377&quot; when: &quot;docker_info.stdout.find('Swarm: inactive') &gt; 0&quot; retries: 5 delay: 5 </code></pre> <hr /> <blockquote> <p>A couple queries: 1. What version of ansible are you using? 2. Why are you not using the docker_swarm module? – 0xSheepdog</p> </blockquote> <ol> <li>ansible [core 2.11.6]</li> </ol> <pre><code>root@minipc:~# ansible --version ansible [core 2.11.6] config file = None configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/local/lib/python3.8/dist-packages/ansible ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections executable location = /usr/local/bin/ansible python version = 3.8.10 (default, Sep 28 2021, 16:10:42) [GCC 9.3.0] jinja version = 3.0.3 libyaml = True </code></pre> <ol start="2"> <li>i didnt even know there was a docker_swarm module. maybe you could post an answer showing how you would write the playbook using this module? my playbook was pretty simple to write, if using the module can save time, i dont mind changing.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T02:48:32.430", "Id": "534260", "Score": "0", "body": "A couple queries: 1. What version of ansible are you using? 2. Why are you not using the docker_swarm module?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T12:41:29.177", "Id": "534300", "Score": "0", "body": "@0xSheepdog i updated my post to answer your questions" } ]
[ { "body": "<p>I have done some Ansible tasks 5 years ago, so I looked at your code just out of interest, and I didn't read any documentation. Here are some things I noted by just looking at the code:</p>\n<p>The task <code>apt_key</code> looks strange to me. The basic idea of a GPG key is that it provides a trust anchor. You currently trust the URL of that task to always provide the correct GPG key. Instead, I would download this key and verify offline that it comes from the person it says. Then I'd compute a hash of the file and use that to verify the download. Since the hash by itself does not tell a story, I'd write a comment along it, summarizing the information from the GPG key, something like:</p>\n<pre class=\"lang-yaml prettyprint-override\"><code># 2021-11-30: 9DC858229FC7DD38854AE2D88D81803C0EBFCD88\n# Docker Release (CE deb) &lt;docker@docker.com&gt;\nhash: sha256:abcdef12345678\n</code></pre>\n<p>Verifying the download is something that the <code>apt_key</code> module should provide out-of-the-box, or its documentation must warn about the practice of downloading an untrusted key, otherwise its authors have no clue of IT security.</p>\n<p>The task <code>apt</code> looks strange as well. You are basing the system on a Linux distribution that still has Python 2 installed as default. That seems old to me. Isn't there some newer release of that distribution?</p>\n<p>Talking of the distribution: From reading the Ansible file, I have no idea what base system I should install before applying Ansible to it. Is it a Debian, Ubuntu, Alpine, Arch, Red Hat (probably not)? This should be documented somewhere. In case the hosts die all of a sudden, it should be possible to set up the exact same setup as before.</p>\n<p>Speaking of which, you don't specify which versions of the packages you want to have installed. This also provides possible variance.</p>\n<p>Over to <code>get-docker.sh</code>. You trust get.docker.com to always serve you the file you expect. You should verify this download as well, just as you do with the Debian packages above. Also, downloading the now-current file prevents the setup from being reproducible.</p>\n<p>Same for <code>pip3</code>, Python packages also have versions, and if you want a reproducible setup, you must use fixed version numbers instead of always taking the latest versions.</p>\n<p>I found the filenames in <code>/tmp</code> a bit short. When you wrote the code, it was immediately clear to you what they are supposed to mean, but will that still be the case in 2 years? I'd choose longer, more expressive names.</p>\n<p>All the rest looks good, and it serves as a nice and brief instruction how to set up a Docker Swarm cluster.</p>\n<p>I wonder how many hosts <code>all</code> means. But that probably depends on how you use this Ansible file. It should definitely not mean &quot;all 2000 reachable hosts that are accidentally reachable&quot;. :)</p>\n<p>Further reading:</p>\n<ul>\n<li><a href=\"https://reproducible-builds.org/\" rel=\"nofollow noreferrer\">Reproducible builds</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T22:07:01.457", "Id": "270554", "ParentId": "270183", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T23:49:09.983", "Id": "270183", "Score": "3", "Tags": [ "beginner", "installer", "yaml", "docker", "ansible" ], "Title": "Ansible playbook to install Docker Swarm" }
270183
<p>This code is Cholesky decomposition in numerical linear algebra.</p> <pre><code>function LLT = Cholesky(A) if is_pos_def(A) == 1 disp('Cholesky Decomposition is used only for positive definite matrixes') else n = rank(A); L = zeros(rank(A)); L(1,1) = sqrt(A(1,1)); for i=2:n L(i,1)=A(i,1)/L(1,1); end for i = 2:n L(i,i)= sqrt(A(i,i)- sum(power(L(i,1:i-1),2))); for j = i+1:n L(j,i) = (A(i,j)-(dot(L(j,1:i-1), L(i,1:i-1))))/L(i,i); end end end LLT = L; end </code></pre> <p>I'd prefer to use vectorized code instead of the second <code>for</code> loop.</p> <p>Is it possible to replace the inner (<code>j</code>) loop?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T09:01:35.880", "Id": "533400", "Score": "2", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T09:23:48.767", "Id": "533404", "Score": "1", "body": "Doesn't MATLAB have a built-in function for the Cholesky decomposition?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T10:38:07.680", "Id": "533410", "Score": "0", "body": "@MartinR how can I access the source code of the \"Chol\" function in MatLab?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T12:03:42.477", "Id": "533414", "Score": "2", "body": "What @MartinR is asking is, is there a reason why you wrote this `Cholesky` function rather than just calling [`chol`](https://www.mathworks.com/help/matlab/ref/chol.html)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T13:19:18.537", "Id": "533423", "Score": "0", "body": "@MartinR This is part of my academic project, and I just want to do it efficiently on MatLab by myself" } ]
[ { "body": "<p>First I'll point out some general code improvements, then we'll get into vectorization.</p>\n<p>There is a bug in your code, in case the first condition is true:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>function LLT = Cholesky(A)\n if is_pos_def(A) == 1\n disp('Cholesky Decomposition is used only for positive definite matrixes')\n else\n % ...computations...\n end\n LLT = L; % &lt;--- L is not defined!\nend\n</code></pre>\n<p>Since this is supposed to be an error condition, use <code>error</code> to print your error message and exit the function abnormally. You then also don't need <code>else</code>:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>function LLT = Cholesky(A)\n if is_pos_def(A) == 1\n error('Cholesky Decomposition is used only for positive definite matrixes')\n end\n % ...computations...\n LLT = L;\nend\n</code></pre>\n<p>Note we don't have the definition of <code>is_pos_def()</code>, so we can't discuss it. However, I'd expect it to return <code>true</code> if the matrix is positive definite, in which case you do want to run your computations, so I'd expect a test</p>\n<pre class=\"lang-matlab prettyprint-override\"><code> if ~is_pos_def(A)\n error('Cholesky Decomposition is used only for positive definite matrixes')\n end\n</code></pre>\n<p>This reads more meaningfully: &quot;if not is positive definite...&quot;</p>\n<p>The spacing around operators is inconsistent, as is the use of empty lines. In particular, I see <code>L(i,1)=A(i,1)...</code>, <code>L(i,i)= sqrt(...</code> and <code>L(j,i) = (A(i,j)...</code> (no spaces around the assignment operator, a space after but not before, and a space on either side). Pick one style and stick to it. I personally prefer spaces around assignment operator, as it helps me read the code.</p>\n<p>The assignment at the end, <code>LLT = L</code>, is necessary for the function to produce an output value. But I find it really ugly because the only purpose of this assignment is to change the name of a variable. I would suggest one of two alternatives:</p>\n<ol>\n<li>declare your function as <code>function L = Cholesky(A)</code>, then the variable <code>L</code> is the output variable; or</li>\n<li>use <code>LLT</code> directly instead of <code>L</code> everywhere in your code.\nBoth solutions yield the same result: the ugly assignment is no longer needed.</li>\n</ol>\n<p>The code</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>n = rank(A);\nL = zeros(rank(A));\n</code></pre>\n<p>is awkward as well. Why compute the rank of <code>A</code> twice? The second line should read <code>L = zeros(n);</code>.</p>\n<p>The loop</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>for i=2:n\n L(i,1)=A(i,1)/L(1,1);\nend\n</code></pre>\n<p>can be trivially vectorized. Here you apply a division with the same number to a series of values, which can be written as</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>L(2:n,1) = A(2:n,1)/L(1,1);\n</code></pre>\n<p>Vectorizing the loop above makes the code more compact and easier to read (IMO), which is the main reason to vectorize code. It will also be a bit faster, but the difference has shrunk a lot in recent years. MATLAB first included a JIT (Just In Time) compiler in 2006 I think, and it has been steadily improving over the years. In MATLAB R2015b, they introduced a completely new JIT, and since then the difference between trivial loops and vectorized code is no longer important, and a more complex loop is oftentimes faster than the vectorized version (usually the case when large intermediate arrays are necessary to vectorize).</p>\n<p>Finally, vectorizing the main inner loop,</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>for j = i+1:n\n L(j,i) = (A(i,j)-(dot(L(j,1:i-1), L(i,1:i-1))))/L(i,i);\nend\n</code></pre>\n<p>is a bit more complex. Let's do this step by step.\n<code>dot(L(j,1:i-1), L(i,1:i-1))</code> is the same as <code>L(j,1:i-1) * L(i,1:i-1).'</code>, except the latter is a matrix product and so will generalize to be applied to many vectors at once (i.e. a range of <code>j</code> values). If we fill in <code>j = i+1:n</code> in that matrix multiplication expression, the result is a column vector. <code>A(i,j)</code> for that range of <code>j</code> values is a row vector, we will have to transpose it to make it match the other result.\nFinally, we arrive at:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>L(i+1:n,i) = (A(i,i+1:n).' - (L(i+1:n,1:i-1) * L(i,1:i-1).')) / L(i,i);\n</code></pre>\n<p>I do think that this expression is harder to read than the loop version, and I might prefer to keep the loop version at least in a comment to aid understanding. The vectorized code here likely is a bit faster, at least for smaller arrays.</p>\n<p>The final function is:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>function L = Cholesky(A)\nn = rank(A);\nL = zeros(n);\nL(1,1) = sqrt(A(1,1));\nL(2:n,1) = A(2:n,1)/L(1,1);\nfor i = 2:n\n L(i,i) = sqrt(A(i,i)- sum(power(L(i,1:i-1),2)));\n L(i+1:n,i) = (A(i,i+1:n).' - (L(i+1:n,1:i-1) * L(i,1:i-1).')) / L(i,i);\nend\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T09:21:58.067", "Id": "533575", "Score": "0", "body": "I appreciate your thorough review and accurate answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T21:24:22.330", "Id": "270234", "ParentId": "270188", "Score": "2" } } ]
{ "AcceptedAnswerId": "270234", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T08:25:10.217", "Id": "270188", "Score": "2", "Tags": [ "mathematics", "matlab" ], "Title": "Cholesky decomposition" }
270188
<p>This code converts a 3-letter English month abbreviation to its numeric equivalent (as a string).</p> <pre class="lang-java prettyprint-override"><code>public static String numericMonth(String monthInFull) { monthInFull = monthInFull.toUpperCase(); if (monthInFull.equals(&quot;JAN&quot;)) { return &quot;01&quot;; } if (monthInFull.equals(&quot;FEB&quot;)) { return &quot;02&quot;; } if (monthInFull.equals(&quot;MAR&quot;)) { return &quot;03&quot;; } if (monthInFull.equals(&quot;APR&quot;)) { return &quot;04&quot;; } if (monthInFull.equals(&quot;MAY&quot;)) { return &quot;05&quot;; } if (monthInFull.equals(&quot;JUN&quot;)) { return &quot;06&quot;; } if (monthInFull.equals(&quot;JUL&quot;)) { return &quot;07&quot;; } if (monthInFull.equals(&quot;AUG&quot;)) { return &quot;08&quot;; } if (monthInFull.equals(&quot;SEP&quot;)) { return &quot;09&quot;; } if (monthInFull.equals(&quot;OCT&quot;)) { return &quot;10&quot;; } if (monthInFull.equals(&quot;NOV&quot;)) { return &quot;11&quot;; } if (monthInFull.equals(&quot;DEC&quot;)) { return &quot;12&quot;; } return &quot;&quot;; } </code></pre> <p>Is it possible to create an array (or Enum?) listing the month names and their respective index (or index + 1) and avoid this excess of <code>if</code>?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T22:06:00.927", "Id": "533463", "Score": "0", "body": "Using a `switch` statement would remove much of the repetition in your code. Whether or not using an `enum` here is beneficial or appropriate would require more context for how/where this code is being used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T08:08:57.150", "Id": "533486", "Score": "0", "body": "(`monthInFull` for three-letter abbrev.s is kind of odd. That's not a *static String*, but a *static `String` **method***.) Please mention that run time is absolutely no concern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T17:15:44.713", "Id": "533535", "Score": "1", "body": "The new _switch expression_: `return switch (monthFull.toUpperCase()) { case \"JAN\" => \"01\"; case \"FEB\" => \"02\"; ... };}`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T19:48:51.827", "Id": "533544", "Score": "1", "body": "https://docs.oracle.com/javase/tutorial/datetime/iso/enum.html is a possible startup point." } ]
[ { "body": "<p>Some improvement ideas:</p>\n<ol>\n<li>You could consider using <code>java.time</code> api, however to use <code>DateTimeFormatter</code> you'd have to use builder, quite heavily configure it (as it would require defaults for year and day, not to mention its case sensitive) and <code>Month</code> class does not seem to offer anything to help here - the benefit of this approach would be that you don't have to maintain localized list of months (but would end up with a date from which month would have to be extracted - additional step, unless there is some other way that I don't see)</li>\n<li>For current solution you can use map (like <code>Map.of(&quot;JAN&quot;, 1, &quot;FEB&quot;, 2...</code>) and instead of repeating <code>if</code> have one <code>get</code> (or <code>getOrDefault</code> if you want to return default value, but...)</li>\n<li>I'd propose to throw exception instead of returning empty string for month out of bounds - I am not sure of exact use case but I'd prefer to know when something unexpected is happening in my code rather than continue execution (fail fast)</li>\n<li>Consider using <code>String.format(&quot;%02d&quot;, parsedMonthNumber)</code> instead manually prepending zeros to numbers - not that it is important in any way (can be even considered unnecessary complication) but this way you separate a little your &quot;app logic&quot; (parsing month number) from &quot;display logic&quot; (or are better of if such separation was ever needed - benefit of such separation is that you can use integer for number instead of string)</li>\n</ol>\n<p>Edit: ad. 1 you <em>could</em> also use <code>Month.values()</code> check if name contains your raw month string and <code>getValue</code> - limiting yourself to english representations of months... but it kinda feels a little off</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T09:38:17.463", "Id": "270216", "ParentId": "270196", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T15:01:43.110", "Id": "270196", "Score": "0", "Tags": [ "java" ], "Title": "Convert month name to numeric string" }
270196
<p>After having a good experience with virtualenvwrapper built on top of the venv, I thought maybe it could be benefitial to have similar shortcuts for standard activities with git which could be time saving as opposite to typing many commands.</p> <p>I've given it a try like the following:</p> <p>Start session (sync current repository with origin, create a session branch for the to-be merge request):</p> <pre><code>#!/bin/bash set -ex DATE=$(date +%F) git fetch --all --prune git pull git branch &quot;$USER-$DATE&quot; git checkout &quot;$USER-$DATE&quot; </code></pre> <p>Close session and integrate results to origin:</p> <pre><code>#!/bin/bash set -ex DATE=$(date +%F) DEFAULT_BRANCH = &quot;main&quot; git add . --all git commit -m &quot;$1&quot; git push -o merge_request.create -o merge_request.target=$DEFAULT_BRANCH origin &quot;$USER-$DATE&quot; git checkout $DEFAULT_BRANCH git branch -d &quot;$USER-$DATE&quot; </code></pre> <p>This works.. more or less, but it would be great to sort out some concerns I have got, general and specific.</p> <ul> <li>In general, maybe there is something I am missing therefore fixing details is waste of time because then I will discover some fundamental blocker, or maybe it's a common problem already solved (maybe in this, or other way)</li> <li>Specifically, there is some bash scripting yet to do which I could though sort out in separately, but maybe this is not all, therefore I try to review these details myself first.</li> </ul> <p>So the issues with the code are, from what I see:</p> <ul> <li>It's random whether the default branch is called &quot;main&quot; either &quot;master&quot;. So the script needs to detect/decide that somehow.</li> <li>The merge request branch name could be derived from repository name</li> <li>Not sure what could be a proper error handling to enable for defined states</li> <li>Is it matter of taste, or reasonable decision to put these scripts as separate files under <code>~/bin</code>, either integrate as functions to something bigger, and call through command line parameters? Then I will have possibly to look on Bash tabbing as well.</li> </ul> <p>Thanks for reading and looking forward to your feedback!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T17:35:43.410", "Id": "533437", "Score": "0", "body": "Regarding the main vs. master branch, you could (A) see which branch exists in the repo but you might have to choose one if both are there or (B) use a config file in the repo to say which main branch is /the/ main branch." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T15:02:54.760", "Id": "270197", "Score": "2", "Tags": [ "bash", "git", "macros" ], "Title": "Fast git change sets with git wrapping scripts" }
270197
<p>This is original Code</p> <pre><code>if($(&quot;#dcl#dynamicID#&quot;).length &gt; 0){ var dcl = document.getElementById(&quot;dcl#dynamicID#&quot;); if(dcl.addEventListener){ dcl.addEventListener(&quot;click&quot;,function(e){ showDelete(this); (e.preventDefault) ? e.preventDefault() : e.returnValue = false; }); }else if(dcl.attachEvent){ dcl.attachEvent(&quot;onclick&quot;,function(e){ showDelete(dcl); (e.preventDefault) ? e.preventDefault() : e.returnValue = false; }); } } </code></pre> <p>and this is what i wrote</p> <pre><code>$(document).on('click','#dcl',function(e) { var eContactLink = $(this).attr('data-delete-pid'); showDelete(this); (e.preventDefault) ? e.preventDefault() : e.returnValue = false; }); </code></pre> <p>please note the <code>dynamicID</code> is the a dynamicvalue coming from <strong>coldfusion</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T19:07:23.573", "Id": "533450", "Score": "0", "body": "Welcome to Code Review! It would benefit reviewers to have a bit more information about the code in the description. From [the help center page _How to ask_](https://codereview.stackexchange.com/help/how-to-ask): \"_You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better._\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T07:24:19.590", "Id": "533479", "Score": "1", "body": "The second line in your code does nothing. `var eContactLink = $(this).attr('data-delete-pid');` The variable `eContactLink` is assigned a value and never used making the whole line superfluous." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T17:45:30.380", "Id": "270198", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "jquery function updated from javascript" }
270198
<p>Hello I'm relatively new to VBA and I have this macro to VLookup information into corresponding cells in the sheet that works, the issue is that it depends on a For Loop to iterate through 10s of thousands of rows. This is taking a significant amount of time to iterate and I know I'm asking a good amount of it but I feel like there's a faster way than how I have it currently. Any help would be appreciated!</p> <pre><code>Sub Test() Application.ScreenUpdating = False Dim Calc_Setting As Long Calc_Setting = Application.Calculation Application.Calculation = xlCalculationManual On Error Resume Next If ActiveSheet.AutoFilterMode Then ActiveSheet.ShowAllData On Error GoTo 0 Dim wb As Workbook Set wb = ActiveWorkbook Dim MARCws As Worksheet, FTws As Worksheet Dim MARCLastRow As Long, FTLastRow As Long, x As Long Dim dataRng As Range Set MARCws = wb.Sheets(&quot;MARC-MARA Pivot Values&quot;) Set FTws = wb.Sheets(&quot;Forecasting Template&quot;) MARCLastRow = MARCws.Range(&quot;A&quot; &amp; Rows.Count).End(xlUp).Row FTLastRow = FTws.Range(&quot;A&quot; &amp; Rows.Count).End(xlUp).Row Set dataRng = MARCws.Range(&quot;A4:Q&quot; &amp; MARCLastRow) For x = 4 To MARCLastRow On Error Resume Next FTws.Range(&quot;C&quot; &amp; x) = Application.WorksheetFunction.VLookup(FTws.Range(&quot;A&quot; &amp; x).Value, dataRng, 2, False) FTws.Range(&quot;E&quot; &amp; x) = Application.WorksheetFunction.VLookup(FTws.Range(&quot;A&quot; &amp; x).Value, dataRng, 3, False) FTws.Range(&quot;F&quot; &amp; x) = Application.WorksheetFunction.VLookup(FTws.Range(&quot;A&quot; &amp; x).Value, dataRng, 4, False) FTws.Range(&quot;G&quot; &amp; x) = Application.WorksheetFunction.VLookup(FTws.Range(&quot;A&quot; &amp; x).Value, dataRng, 5, False) FTws.Range(&quot;H&quot; &amp; x) = Application.WorksheetFunction.VLookup(FTws.Range(&quot;A&quot; &amp; x).Value, dataRng, 6, False) FTws.Range(&quot;I&quot; &amp; x) = Application.WorksheetFunction.VLookup(FTws.Range(&quot;A&quot; &amp; x).Value, dataRng, 7, False) FTws.Range(&quot;J&quot; &amp; x) = Application.WorksheetFunction.VLookup(FTws.Range(&quot;A&quot; &amp; x).Value, dataRng, 8, False) FTws.Range(&quot;K&quot; &amp; x) = Application.WorksheetFunction.VLookup(FTws.Range(&quot;A&quot; &amp; x).Value, dataRng, 9, False) FTws.Range(&quot;L&quot; &amp; x) = Application.WorksheetFunction.VLookup(FTws.Range(&quot;A&quot; &amp; x).Value, dataRng, 10, False) FTws.Range(&quot;M&quot; &amp; x) = Application.WorksheetFunction.VLookup(FTws.Range(&quot;A&quot; &amp; x).Value, dataRng, 12, False) FTws.Range(&quot;AZ&quot; &amp; x) = Application.WorksheetFunction.VLookup(FTws.Range(&quot;A&quot; &amp; x).Value, dataRng, 17, False) FTws.Range(&quot;BA&quot; &amp; x) = (FTws.Range(&quot;AZ&quot; &amp; x).Value / 30) Next x Application.ScreenUpdating = True Application.Calculation = Calc_Setting End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T20:59:47.687", "Id": "533454", "Score": "0", "body": "Wouldn't it be faster to have the formulas built in to the sheet? I don't see anything here that requires the use of VBA. You should use tables that automatically fill in formulas as the tables expand. It might help to describe *what* you are trying to do and not just *how* you are doing it. This will help people help you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T21:26:35.137", "Id": "533457", "Score": "0", "body": "Using the formulas in the sheet would be faster, but I'm designing this such that the formulas are inaccessible and thus unbreakable for the user, since building the formulas into the sheet has proved unreliable due to human error. One idea that I had that perhaps might work that would be if I could have macro run the vlookup formula into the first row's relevant cells and could then have another statement copy and paste to the last row, what do you think about that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T23:25:01.947", "Id": "533465", "Score": "0", "body": "That's what a table does. The table will automatically copy the formulas down the row. Select your data and Press **CTRL+T** to make a table." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T01:40:00.493", "Id": "533467", "Score": "0", "body": "Are you using FTLastRow anywhere?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T06:42:49.620", "Id": "533474", "Score": "1", "body": "As a further frame challenge: Excel can protect/hide formulas to prevent accidental edits. Format Cells -> Protection -> Locked,Hidden; and then menu Review -> Protect -> Protect Sheet to prevent displaying or editing the formulas. Similar feature in Libreoffice/Openoffice." } ]
[ { "body": "<p><strong>Code Style</strong></p>\n<p>Avoid multiple variable declarations in a single line, like <code>Dim MARCLastRow As Long, FTLastRow As Long, x As Long</code>.</p>\n<p>It is generally not recommended to include the variable type in the variable name (e.g. <code>ws</code> in <code>MARCws</code>), as variable names should be self-explanatory / self-documenting. Although I know this and don't do this in any other language, I still find myself doing this in VBA. For some reason I find it to increase readability in VBA (while I find it harmful in other languages). Just something to consider.</p>\n<hr />\n<p><strong>Functionality</strong></p>\n<p>If you run into an error (<code>On Error GoTo 0</code>), <code>Application.Calculation = Calc_Setting</code> will not be executed, therefore the original calculation setting will not be restored.</p>\n<p>It seems to me that this <code>Sub</code>'s functionality could be more easily replicated without VBA, using formulas inside the worksheet. I'd expect this to improve performance as well. I'm assuming there's a specific reason to do this in VBA, so I'll take a look at the performance next.</p>\n<hr />\n<p><strong>Performance</strong></p>\n<p>You're doing too much work. Instead of calling <code>Vlookup</code> 10 times with different column values you should only look for the desired row once. Once you have the address / range object you can easily replicate your current functionality by stepping through the row with the <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.range.offset\" rel=\"nofollow noreferrer\"><code>Range.Offset</code></a> property.</p>\n<p>For getting and setting cell values I would recommend using <code>Range.Value2</code> instead of <code>Range</code> (withough <code>Value</code>) or <code>Range.Value</code>. <code>Range.Value2</code> refers to the range's underlying &quot;real&quot; value, withough any formatting applied to it. More detailed discussion <a href=\"https://fastexcel.wordpress.com/2011/11/30/text-vs-value-vs-value2-slow-text-and-how-to-avoid-it/\" rel=\"nofollow noreferrer\">here</a>. <code>Range.Value2</code> is slightly faster than <code>Range.Value</code> and is generally preferable for most use cases, as you probably don't want to deal with cell formatting if you don't have to.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T21:16:45.980", "Id": "533455", "Score": "0", "body": "Thank you. Though using the formulas in the worksheet would be faster, I'm designing a process that is designed to have no end thought for the user and also no possibility for an end user to somehow break it because there will be 100s of end users using the tool independently and any one error could be critical. One idea that I had that perhaps might work that would be somewhat \"having the formulas in the sheet\" and would only iterate once would be if I could have the first rows containing either the vlookup formula or range.offset, I could then have another statement copy and paste to lastrow" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T21:21:19.180", "Id": "533456", "Score": "0", "body": "What do you think about that? and would you have any ideas on how to achieve that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T21:45:59.003", "Id": "533458", "Score": "0", "body": "I'm not entirely sure what you're suggesting. I'd recommend starting out with the suggestions I made regarding the performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T21:48:23.853", "Id": "533459", "Score": "0", "body": "My point was that if I use the Range.Offset property that improves performance but then the loop still iterates 50k times. Is there a way to have the loop iterate once but then instead of it pasting values it pastes the formulas such that I can then do a copy paste with my range being row n+1 to the last row? Wouldn't that improve runtime quite significantly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T22:02:43.280", "Id": "533462", "Score": "0", "body": "Well if you're just copying formulas, you probably don't need VBA for this use case. If you want to do it in VBA, I don't see a way around iterating over every row. Unless of course there's some patterns in your data I don't know of." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T21:11:28.327", "Id": "270203", "ParentId": "270202", "Score": "6" } }, { "body": "<p>Each line within the <code>for</code> loop executes a <code>VLOOKUP</code> even though failure by the first <code>VLOOKUP</code> statement guarantees that each subsequent statement will also fail. It would be more efficient to check for 'success' only once per loop and then grab the remaining data after that.</p>\n<p>So, below is an option that uses the <code>MATCH</code> function within a helper function. The function returns <code>True</code> and the <code>Range</code> row offset if a match is found. Even for scenarios where a match is found every time, the approach below will save time. <code>VLookup</code> is not called upon to evaluate a very large lookup range 11 X '10s of thousands rows' <em>times</em> more than necessary.</p>\n<pre><code>Sub Test()\n\nApplication.ScreenUpdating = False\nDim Calc_Setting As Long\nCalc_Setting = Application.Calculation\nApplication.Calculation = xlCalculationManual\n\nOn Error Resume Next\nIf ActiveSheet.AutoFilterMode Then ActiveSheet.ShowAllData\nOn Error GoTo 0\n\n\n\nDim wb As Workbook\nSet wb = ActiveWorkbook\nDim MARCws As Worksheet, FTws As Worksheet\nDim MARCLastRow As Long, FTLastRow As Long, x As Long\nDim dataRng As Range\nDim dLookupRange As Range\n\nSet MARCws = wb.Sheets(&quot;MARC-MARA Pivot Values&quot;)\nSet FTws = wb.Sheets(&quot;Forecasting Template&quot;)\n\nMARCLastRow = MARCws.Range(&quot;A&quot; &amp; Rows.Count).End(xlUp).Row\nFTLastRow = FTws.Range(&quot;A&quot; &amp; Rows.Count).End(xlUp).Row\n\nSet dataRng = MARCws.Range(&quot;A4:Q&quot; &amp; MARCLastRow)\n\n'Setup a Range to use specifically by the MATCH function\nSet dLookupRange = MARCws.Range(&quot;A4:A&quot; &amp; MARCLastRow)\n\nDim dMatchingRowOffset As Long\n\nFor x = 4 To MARCLastRow\n \n 'Find the row of interest once...then grab all the data using Range.Cells\n 'rather than VLookup. Otherwise, move onto the next row\n If TryFindRowOfInterest(FTws.Range(&quot;A&quot; &amp; x).Value2, dLookupRange, dMatchingRowOffset) Then\n \n FTws.Range(&quot;C&quot; &amp; x).Value = dataRng.Cells(dMatchingRowOffset, 2).Value2\n FTws.Range(&quot;E&quot; &amp; x).Value = dataRng.Cells(dMatchingRowOffset, 3).Value2\n FTws.Range(&quot;F&quot; &amp; x).Value = dataRng.Cells(dMatchingRowOffset, 4).Value2\n FTws.Range(&quot;G&quot; &amp; x).Value = dataRng.Cells(dMatchingRowOffset, 5).Value2\n FTws.Range(&quot;H&quot; &amp; x).Value = dataRng.Cells(dMatchingRowOffset, 6).Value2\n FTws.Range(&quot;I&quot; &amp; x).Value = dataRng.Cells(dMatchingRowOffset, 7).Value2\n FTws.Range(&quot;J&quot; &amp; x).Value = dataRng.Cells(dMatchingRowOffset, 8).Value2\n FTws.Range(&quot;K&quot; &amp; x).Value = dataRng.Cells(dMatchingRowOffset, 9).Value2\n FTws.Range(&quot;L&quot; &amp; x).Value = dataRng.Cells(dMatchingRowOffset, 10).Value2\n FTws.Range(&quot;M&quot; &amp; x).Value = dataRng.Cells(dMatchingRowOffset, 12).Value2\n FTws.Range(&quot;AZ&quot; &amp; x).Value = dataRng.Cells(dMatchingRowOffset, 17).Value2\n FTws.Range(&quot;BA&quot; &amp; x).Value = (FTws.Range(&quot;AZ&quot; &amp; x).Value2 / 30)\n \n End If\nNext x\n\nApplication.ScreenUpdating = True\nApplication.Calculation = Calc_Setting\n\nEnd Sub\n\nPrivate Function TryFindRowOfInterest(ByVal pLookupValue As Variant, ByVal pDataRange As Range, ByRef pOutRangeRowOffset As Long) As Boolean\n \n pOutRangeRowOffset = -1\n \nOn Error Resume Next\n pOutRangeRowOffset = Application.WorksheetFunction.Match(pLookupValue, pDataRange, 0)\n \n TryFindRowOfInterest = pOutRangeRowOffset &gt; -1\nEnd Function\n\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T15:15:21.577", "Id": "533525", "Score": "0", "body": "I think, something in relation to the screen updating or xl calculation settings is causing this code to have no output at all, would you have any idea what the fix may be?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T15:28:40.273", "Id": "533527", "Score": "0", "body": "A couple things: 1) Put a breakpoint at a point inside the loop and see if it is ever 'hit'. 2) comment out all the Application settings and see if it changes the results. FWIW, I ran this code against some fake data that I thought would be _like_ your dataset, and it generated the results I thought I should expect. Note: if you pass `dataRng` rather than `dLookupRange` into the `TryXXX` predicate function...it would always return `False`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T18:26:10.150", "Id": "533541", "Score": "0", "body": "That entire IF statement can be made smaller (don't repeat yourself) - just use a Loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T21:07:32.680", "Id": "533546", "Score": "0", "body": "I put the breakpoint within the loop and it wasn't hit. A breakpoint just outside the loop hits but for some reason the if statement is returning false" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T21:13:00.933", "Id": "533547", "Score": "0", "body": "So, the next step would be to sort out why the `Match` function is not returning `True` when you would expect it to. Probably best to create a single statement that you can execute in isolation, and experiment with the parameters until you find the issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T21:45:41.483", "Id": "533551", "Score": "0", "body": "It can really only be one of two things: The `pDataRange` parameter should be a single column Range (e.g., \"A4:A20000\") of the `MARCws` worksheet. The `pLookupValue` parameter should be a valid value and be located somewhere in `MARCws` worksheet's A column. If both of those conditions are met, the `Match` function will return a value - and the helper function will return `True`. Hope that helps you find the issue." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T23:41:04.317", "Id": "270206", "ParentId": "270202", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T20:29:13.743", "Id": "270202", "Score": "4", "Tags": [ "performance", "vba", "excel" ], "Title": "VLOOKUP Macro to reformat data between sheets preserving the connection to the source" }
270202
<p>I have put together <a href="https://github.com/lancejpollard/normalize-ast.js/blob/make/index.js" rel="nofollow noreferrer">this complete runnable source code</a> with an example set of <a href="https://github.com/lancejpollard/normalize-ast.js/blob/make/test.js" rel="nofollow noreferrer">test expressions</a> which it parses and prints. The code requires <code>acorn</code>, which is a JS AST generator from a string, so it can't easily run in StackOverflow I don't think. But here is the main <a href="https://github.com/lancejpollard/normalize-ast.js/blob/1a44a0be767015fafebccd4e0ef7efc9aba85785/index.js" rel="nofollow noreferrer">index.js</a> which I would like to refactor:</p> <pre><code>const acorn = require('acorn') const print = require('./print') const { createMemberExpression, createConditionalExpression, createBinaryExpression, createLogicalExpression, createIdentifier, createLiteral, createExpressionStatement, createVariableDeclaration, createVariableDeclarator, createAssignmentExpression, createCallExpression, createFunctionDeclaration, createFunctionExpression, createArrowFunctionExpression, createAssignmentPattern, createReturnStatement, createIfStatement, createBlockStatement, createObjectExpression, createProperty, createArrayExpression, createForInStatement, createForOfStatement, createWhileStatement, createLabeledStatement } = require('./create') module.exports = { parse, print, normalize } function parse(string) { return acorn.parse(string, { ecmaVersion: 2021, sourceType: 'module' }) } function normalize(input) { const output = { type: 'Program', body: [] } const scope = { index: 0, } input.body.forEach(node =&gt; { output.body.push(...normalizeBodyNode(node, scope)) }) return output } function normalizeBodyNode(node, scope) { const output = [] const normalizers = { VariableDeclaration() { const declarations = normalizeVariableDeclaration(node, scope) output.push(...declarations) }, ExpressionStatement() { const expressions = normalizeExpressionStatement(node.expression, scope) output.push(...expressions) }, FunctionDeclaration() { output.push(...normalizeFunctionDeclaration(node, scope)) }, ReturnStatement() { output.push(...normalizeReturnStatement(node, scope)) }, IfStatement() { const [ifStatement, expressions] = normalizeIfStatement(node, scope) output.push(...expressions) output.push(ifStatement) }, SwitchStatement() { const [swtch, expressions] = normalizeSwitchStatement(node, scope) }, ForInStatement() { const [forInStatement, expressions] = normalizeForInStatement(node, scope) output.push(...expressions) output.push(forInStatement) }, ForOfStatement() { const [forOfStatement, expressions] = normalizeForOfStatement(node, scope) output.push(...expressions) output.push(forOfStatement) }, WhileStatement() { const [whileStatement, expressions] = normalizeWhileStatement(node, scope) output.push(...expressions) output.push(whileStatement) }, ClassDeclaration() { const [clss, expressions] = normalizeClassDeclaration(node, scope) output.push(...expressions) output.push(clss) }, BreakStatement() { output.push(node) }, LabeledStatement() { const [body] = normalizeBodyNode(node.body, scope) const [label] = normalizeExpression(node.label, scope) output.push(createLabeledStatement(label, body)) }, ForStatement() { const blockStatement = normalizeForStatement(node, scope) output.push(blockStatement) }, BlockStatement() { output.push(normalizeBlockStatement(node, scope)) }, AssignmentExpression() { const [assign, expressions] = normalizeAssignmentExpression(node, scope) output.push(...expressions) output.push(assign) }, ExportNamedDeclaration() { const [exp, expressions] = normalizeExportNamedDeclaration(node, scope) output.push(...expressions) output.push(exp) } } call(normalizers, node.type) return output } function normalizeExportNamedDeclaration(node, scope) { const declaration = normalizeBodyNode(node.declaration, scope) const specifiers = [] } function normalizeAssignmentExpression(node, scope) { const [left, leftExps] = normalizeExpression(node.left, scope) const [right, rightExps] = normalizeExpression(node.right, scope) return [ createAssignmentExpression(left, right, node.operator), [...leftExps, ...rightExps] ] } function normalizeBlockStatement(node, scope) { const childScope = { ...scope } const body = [] node.body.forEach(bd =&gt; { body.push(...normalizeBodyNode(bd, childScope)) }) return createBlockStatement(body) } function normalizeForStatement(node, scope) { const childScope = { ...scope } let initExps if (node.init) { initExps = normalizeBodyNode(node.init, childScope) } else { initExps = [] } let test, testExps = [] if (node.test) { [test, testExps] = normalizeExpression(node.test, childScope, true) } const [update, updateExps] = normalizeExpression(node.update, childScope) const body = [] const normalizers = { BlockStatement() { node.body.body.forEach(bd =&gt; { body.push(...normalizeBodyNode(bd, childScope)) }) }, ExpressionStatement() { body.push(...normalizeBodyNode(node.body, childScope)) } } call(normalizers, node.body.type) const block = createBlockStatement([ ...initExps, createWhileStatement( createLiteral(true), [ ...testExps, createIfStatement(test, createBlockStatement([ ...body, ...updateExps, update ]), createBlockStatement([ createBreakStatement() ]) ) ] ) ]) return block } function normalizeClassDeclaration(node, scope) { const [id, idExps] = normalizeExpression(node.id, scope) const output = [...idExps] const superClass = null const [body, bodyExps] = normalizeClassBody(node.body, scope) output.push(...bodyExps) return [createClassDeclaration(id, superClass, body), output] } function createClassDeclaration(id, superClass, body) { return { type: 'ClassDeclaration', id, superClass, body } } function normalizeClassBody(node, scope) { const body = [] const output = [] node.body.forEach(bd =&gt; { const [method, methodExps] = normalizeMethodDefinition(bd, scope) output.push(...methodExps) body.push(method) }) return [createClassBody(body), output] } function createClassBody(body) { return { type: 'ClassBody', body } } function normalizeMethodDefinition(node, scope) { const [key, keyExps] = normalizeExpression(node.key, scope) const value = normalizeFunctionExpression(node.value, scope) return [createMethodDefinition(key, value.pop()), keyExps] } function createMethodDefinition(key, value) { return { type: 'MethodDefinition', key, value } } function normalizeForInStatement(node, scope) { const output = [] const [left, leftExps] = normalizeExpression(node.left, scope) const [right, rightExps] = normalizeExpression(node.right, scope) output.push(...leftExps) output.push(...rightExps) const body = [] if (node.body.type === 'BlockStatement') { node.body.body.forEach(bd =&gt; { body.push(...normalizeBodyNode(bd, { ...scope })) }) } else { body.push(...normalizeBodyNode(node.body, { ...scope })) } const forInStatement = createForInStatement(left, right, body) return [forInStatement, output] } function normalizeForOfStatement(node, scope) { const output = [] const [left, leftExps] = normalizeExpression(node.left, scope) const [right, rightExps] = normalizeExpression(node.right, scope) output.push(...leftExps) output.push(...rightExps) const body = [] node.body.body.forEach(bd =&gt; { body.push(...normalizeBodyNode(bd, { ...scope })) }) const forOfStatement = createForOfStatement(left, right, body) return [forOfStatement, output] } function createBreakStatement(label) { return { type: 'BreakStatement', label } } function normalizeWhileStatement(node, scope) { const [test, testExps] = normalizeExpression(node.test, scope, true) const body = [] node.body.body.forEach(bd =&gt; { body.push(...normalizeBodyNode(bd, { ...scope })) }) const newBody = [...testExps, createIfStatement(test, createBlockStatement(body), createBlockStatement([createBreakStatement()]))] const whileStatement = createWhileStatement(createLiteral(true), newBody) return [whileStatement, []] } function normalizeSwitchStatement(node, scope) { const discriminant = normalizeExpression(node.discriminant) return [] } function normalizeIfStatement(node, scope) { const top = [] const [test, testExpressionStatements] = normalizeExpression(node.test, scope, true) top.push(...testExpressionStatements) let consequent = [] if (node.consequent.type === 'BlockStatement') { node.consequent.body.forEach(statement =&gt; { const cons = normalizeBodyNode(statement, { ...scope }) consequent.push(...cons) }) } else { consequent.push(...normalizeExpressionStatement(node.consequent, { ...scope })) } consequent = createBlockStatement(consequent) let alternate = null if (node.alternate) { if (node.alternate.type === 'BlockStatement') { alternate = [] node.alternate.body.forEach(statement =&gt; { const alts = normalizeBodyNode(statement, { ...scope }) alternate.push(...alts) }) alternate = createBlockStatement(alternate) } else { [alternate, altExpressionStatements] = normalizeIfStatement(node.alternate, scope) top.push(...altExpressionStatements) } } const ifStatement = createIfStatement(test, consequent, alternate) return [ifStatement, top] } function normalizeReturnStatement(node, scope) { const output = [] const [arg, expressionStatements] = normalizeExpression(node.argument, scope, true) output.push(...expressionStatements) output.push(createReturnStatement(arg)) return output } function normalizeArrowFunctionExpression(node, scope) { const output = [] const params = [] node.params.forEach(param =&gt; { const [p, pExpressionStatements] = normalizeFunctionParam(param, scope) output.push(...pExpressionStatements) params.push(p) }) const normalizers = { CallExpression() { [body, expressions] = normalizeExpression(node.body, { ...scope }, true); body = createBlockStatement([ ...expressions, body ]) }, ArrayExpression() { [body, expressions] = normalizeExpression(node.body, { ...scope }); body = createBlockStatement([ ...expressions, createReturnStatement(body), ]) }, ObjectExpression() { [body, expressions] = normalizeExpression(node.body, { ...scope }); body = createBlockStatement([ ...expressions, createReturnStatement(body), ]) }, BlockStatement() { body = [] const childScope = { ...scope } node.body.body.forEach(bd =&gt; { body.push(...normalizeBodyNode(bd, childScope)) }) body = createBlockStatement(body) }, BinaryExpression() { [body, expressions] = normalizeExpression(node.body, { ...scope }); body = createBlockStatement([ ...expressions, createReturnStatement(body), ]) } } let body call(normalizers, node.body.type) return [ createArrowFunctionExpression(node.id, params, body), output ] } function normalizeFunctionExpression(node, scope) { const childScope = { ...scope } const output = [] const params = [] node.params.forEach(param =&gt; { const [p, pExpressionStatements] = normalizeFunctionParam(param, childScope) output.push(...pExpressionStatements) params.push(p) }) const body = [] node.body.body.forEach(bd =&gt; { body.push(...normalizeBodyNode(bd, childScope)) }) output.push(createFunctionExpression(node.id, params, body)) return output } function normalizeFunctionDeclaration(node, scope) { const output = [] const params = [] node.params.forEach(param =&gt; { const [p, pExpressionStatements] = normalizeFunctionParam(param, scope) output.push(...pExpressionStatements) params.push(p) }) const body = [] node.body.body.forEach(bd =&gt; { body.push(...normalizeBodyNode(bd, scope)) }) output.push(createFunctionDeclaration(node.id, params, body)) return output } function normalizeFunctionParam(node, scope) { const output = [] const expressionStatements = [] const normalizers = { Identifier() { output.push(node) }, AssignmentPattern() { const [left] = normalizeExpression(node.left, scope) const [right, rightExpressionStatements] = normalizeExpression(node.right, scope) expressionStatements.push(...rightExpressionStatements) // TODO: do inside the function. output.push( createAssignmentPattern(left, right) ) }, RestElement() { const [rest, restExps] = normalizeRestElement(node, scope) expressionStatements.push(...restExps) output.push(rest) } } call(normalizers, node.type) output.push(expressionStatements) return output } function normalizeRestElement(node, scope) { const [arg, argExps] = normalizeExpression(node.argument, scope) return [ createRestElement(arg), argExps ] } function createRestElement(argument) { return { type: 'RestElement', argument } } function normalizeVariableDeclaration(node, scope) { const output = [] node.declarations.forEach(dec =&gt; { const declarations = normalizeVariableDeclarator(node, dec, scope) output.push(...declarations) }) return output } function normalizeVariableDeclarator(parent, node, scope) { const output = [] const normalizeId = { Identifier() { const normalizeInit = { Identifier() { output.push( createVariableDeclaration(parent.kind, [ createVariableDeclarator(node.id, node.init) ]) ) }, Literal() { output.push( createVariableDeclaration(parent.kind, [ createVariableDeclarator(node.id, node.init) ]) ) }, ObjectExpression() { const props = [] node.init.properties.forEach(prop =&gt; { const [p, pExpressionStatements] = normalizeProperty(prop, scope) props.push(p) output.push(...pExpressionStatements) }) output.push(createVariableDeclaration(parent.kind, [ createVariableDeclarator(node.id, createObjectExpression(props) ) ])) }, ArrayExpression() { const els = [] node.init.elements.forEach(element =&gt; { const [p, pExpressionStatements] = normalizeExpression(element, scope) els.push(p) output.push(...pExpressionStatements) }) output.push(createVariableDeclaration(parent.kind, [ createVariableDeclarator(node.id, createArrayExpression(els) ) ])) }, ConditionalExpression() { const [test, testExpressionStatements] = normalizeExpression(node.init.test, scope) const [consequent, consequentExpressionStatements] = normalizeExpression(node.init.consequent, scope) const [alternate, alternateExpressionStatements] = normalizeExpression(node.init.alternate, scope) output.push(...testExpressionStatements) output.push(...consequentExpressionStatements) output.push(...alternateExpressionStatements) output.push(createVariableDeclaration(parent.kind, [ createVariableDeclarator(node.id, createConditionalExpression( test, consequent, alternate ) ) ])) }, FunctionExpression() { // output.push(...normalizeFunctionExpression(node.init, { ...scope })) }, MemberExpression() { const [object, objectStatements] = normalizeExpression(node.init.object, scope) const [property, propertyStatements] = normalizeExpression(node.init.property, scope) output.push(...objectStatements) output.push(...propertyStatements) output.push(createVariableDeclaration(parent.kind, [ createVariableDeclarator(node.id, createMemberExpression( object, property, node.init.computed ) ) ])) }, BinaryExpression() { const [left, leftExpressionStatements] = normalizeExpression(node.init.left, scope, true) const [right, rightExpressionStatements] = normalizeExpression(node.init.right, scope, true) output.push(...leftExpressionStatements) output.push(...rightExpressionStatements) output.push(createVariable(parent.kind, node.id, createBinaryExpression( left, node.init.operator, right ))) }, ArrowFunctionExpression() { const [func, expressions] = normalizeArrowFunctionExpression(node.init, scope) output.push(...expressions) output.push(createVariable(parent.kind, node.id, func)) }, NewExpression() { const [ctor, expressions] = normalizeNewExpression(node.init, scope) output.push(...expressions) output.push(createVariable(parent.kind, node.id, ctor)) }, CallExpression() { const [_callee, calleeStatements] = normalizeExpression(node.init.callee, scope) const args = [] node.init.arguments.forEach(arg =&gt; { const [argument, argumentStatements] = normalizeExpression(arg, scope, true) output.push(...argumentStatements) args.push(argument) }) output.push(...calleeStatements) output.push(createVariable(parent.kind, node.id, createCallExpression(_callee, args) )) }, TemplateLiteral() { const [template, expressions] = normalizeTemplateLiteral(node.init, scope) output.push(...expressions) output.push(createVariable(parent.kind, node.id, template)) }, TaggedTemplateExpression() { const [template, expressions] = normalizeTaggedTemplateExpression(node.init, scope) output.push(...expressions) output.push(createVariable(parent.kind, node.id, template)) }, UnaryExpression() { const [update, updateExps] = normalizeUnaryExpression(node.init, scope, true) output.push(...updateExps) // if (isolate) { // const name = `tmp${scope.index++}` // output.push( // createVariable('const', // createIdentifier(name), // update // ) // ) // output.push(createVariable(parent.kind, node.id, createIdentifier(name))) // } else { output.push(createVariable(parent.kind, node.id, update)) // } } } if (node.init) { call(normalizeInit, node.init.type) } else { output.push(createVariableDeclaration(parent.kind, [ createVariableDeclarator(node.id) ])) } }, ObjectPattern() { throw new Error('todo') }, ArrayPattern() { const normalizeInit = { Identifier() { node.id.elements.forEach(el =&gt; { output.push( createVariableDeclaration(parent.kind, [ createVariableDeclarator(el, createMemberExpression(node.init, el)) ]) ) }) }, MemberExpression() { node.id.elements.forEach(el =&gt; { output.push( createVariableDeclaration(parent.kind, [ createVariableDeclarator(el, createMemberExpression(node.init, el)) ]) ) }) }, // CallExpression() { // const [_callee, calleeStatements] = normalizeExpression(node.init.callee, scope) // const args = [] // node.init.arguments.forEach(arg =&gt; { // const [argument, argumentStatements] = normalizeExpression(arg, scope) // output.push(...argumentStatements) // args.push(argument) // }) // output.push(...calleeStatements) // output.push(createVariable(parent.kind, // createCallExpression(_callee, args) // )) // }, } call(normalizeInit, node.init.type) } } call(normalizeId, node.id.type) return output } function normalizeTaggedTemplateExpression(node, scope) { const [tag, tagExps] = normalizeExpression(node.tag, scope) const [template, templateExps] = normalizeTemplateLiteral(node.quasi, scope) return [ createTaggedTemplateExpression(tag, template), [...templateExps, ...tagExps] ] } function createTaggedTemplateExpression(tag, quasi) { return { type: 'TaggedTemplateExpression', tag, quasi } } function normalizeTemplateLiteral(node, scope) { const quasis = [] const expressions = [] const exps = [] node.expressions.forEach(expression =&gt; { const [exp, expExps] = normalizeExpression(expression, scope) expressions.push(exp) exps.push(...expExps) }) node.quasis.forEach(q =&gt; { quasis.push(normalizeTemplateElement(q, scope)) }) return [ createTemplateLiteral(expressions, quasis), exps ] } function normalizeTemplateElement(node, scope) { return node } function createTemplateLiteral(expressions, quasis) { return { type: 'TemplateLiteral', expressions, quasis } } function createVariable(kind, id, init) { return createVariableDeclaration(kind, [ createVariableDeclarator(id, init) ]) } function normalizeNewExpression(node, scope) { const [ctor, ctorExps] = normalizeExpression(node.callee, scope) const argExps = [] const args = [] node.arguments.forEach(arg =&gt; { const [argument, argumentExps] = normalizeExpression(arg, { ...scope }, true) args.push(argument) argExps.push(...argumentExps) }) return [createNewExpression(ctor, args), ctorExps.concat(argExps)] } function createNewExpression(ctor, args) { return { type: 'NewExpression', callee: ctor, arguments: args } } function normalizeSpreadElement(node, scope) { const [arg, argExps] = normalizeExpression(node.argument, scope) return [ createSpreadElement(arg), argExps ] } function createSpreadElement(argument) { return { type: 'SpreadElement', argument } } function normalizeProperty(node, scope) { if (node.type === 'SpreadElement') { return normalizeSpreadElement(node, scope) } const output = [] const [key, keyExpressionStatements] = normalizeExpression(node.key, scope) const [value, valueExpressionStatements] = normalizeExpression(node.value, scope) output.push(...keyExpressionStatements) output.push(...valueExpressionStatements) return [createProperty(key, value), output] } function normalizeExpressionStatement(node, scope) { const output = [] const normalizers = { AssignmentExpression() { // if node.left.type === 'ArrayPattern' const [left, leftExpressionStatements] = normalizeExpression(node.left, scope) const [right, rightExpressionStatements] = normalizeExpression(node.right, scope) output.push(...leftExpressionStatements) output.push(...rightExpressionStatements) if (Array.isArray(left)) { const name = `tmp${scope.index++}` output.push(createExpressionStatement( createAssignmentExpression( createIdentifier(name), right ) )) left.forEach(l =&gt; { output.push(createExpressionStatement( createAssignmentExpression(l, createMemberExpression( createIdentifier(name), l)) )) }) } else { output.push(createExpressionStatement( createAssignmentExpression(left, right) )) } }, Identifier() { output.push(createExpressionStatement(node)) }, MemberExpression() { const [object, objectStatements] = normalizeExpression(node.object, scope) const [property, propertyStatements] = normalizeExpression(node.property, scope) output.push(...objectStatements) output.push(...propertyStatements) output.push(createExpressionStatement( createMemberExpression( object, property, node.computed )) ) }, CallExpression() { const [_callee, calleeStatements] = normalizeExpression(node.callee, scope) const args = [] node.arguments.forEach(arg =&gt; { const [argument, argumentStatements] = normalizeExpression(arg, scope, true) output.push(...argumentStatements) args.push(argument) }) output.push(...calleeStatements) output.push(createExpressionStatement( createCallExpression(_callee, args) )) }, FunctionExpression() { output.push(...normalizeFunctionExpression(node, { ...scope })) }, NewExpression() { const [ctor, expressions] = normalizeNewExpression(node, scope) output.push(...expressions) output.push(createExpressionStatement(ctor)) }, TaggedTemplateExpression() { const [template, expressions] = normalizeTaggedTemplateExpression(node, scope) output.push(...expressions) output.push(createExpressionStatement(template)) }, SequenceExpression() { const expressions = normalizeSequenceExpression(node, scope) output.push(...expressions) }, ReturnStatement() { output.push(...normalizeReturnStatement(node, scope)) }, Literal() { output.push(node) }, ThrowStatement() { const [thrw, expressions] = normalizeThrowStatement(node, scope) output.push(...expressions) output.push(createExpressionStatement(thrw)) } } call(normalizers, node.type) return output } function normalizeThrowStatement(node, scope) { const [argument, argumentExps] = normalizeExpression(node.argument, scope) return [ createThrowStatement(argument), argumentExps ] } function createThrowStatement(argument) { return { type: 'ThrowStatement', argument } } function normalizeSequenceExpression(node, scope) { const expressions = [] // this just flattens the list and gets rid of the node type // in the normalized output node.expressions.forEach(exp =&gt; { expressions.push(...normalizeExpressionStatement(exp, scope)) }) return expressions } function normalizeExpression(node, scope, isolate = false) { const expressionStatements = [] const output = [] const normalizers = { Identifier() { output.push(node) }, MemberExpression() { const [object, objectStatements] = normalizeExpression(node.object, scope, isolate) const [property, propertyStatements] = normalizeExpression(node.property, scope, isolate) expressionStatements.push(...objectStatements) expressionStatements.push(...propertyStatements) output.push(createMemberExpression( object, property, node.computed )) }, CallExpression() { const [_callee, calleeStatements] = normalizeExpression(node.callee, scope, isolate) const args = [] node.arguments.forEach(arg =&gt; { const [argument, argumentStatements] = normalizeExpression(arg, scope, true) expressionStatements.push(...argumentStatements) args.push(argument) }) expressionStatements.push(...calleeStatements) const name = `tmp${scope.index++}` output.push(createIdentifier(name)) expressionStatements.push( createVariableDeclaration('const', [ createVariableDeclarator( createIdentifier(name), createCallExpression(_callee, args) ) ]) ) }, LogicalExpression() { const [left, leftExpressionStatements] = normalizeExpression(node.left, scope, true) const [right, rightExpressionStatements] = normalizeExpression(node.right, scope, true) expressionStatements.push(...leftExpressionStatements) expressionStatements.push(...rightExpressionStatements) const logicalExp = createLogicalExpression( left, node.operator, right ) if (isolate) { const name = `tmp${scope.index++}` expressionStatements.push( createVariable('const', createIdentifier(name), logicalExp ) ) output.push(createIdentifier(name)) } else { output.push(logicalExp) } }, BinaryExpression() { const [left, leftExpressionStatements] = normalizeExpression(node.left, scope, true) const [right, rightExpressionStatements] = normalizeExpression(node.right, scope, true) expressionStatements.push(...leftExpressionStatements) expressionStatements.push(...rightExpressionStatements) const binary = createBinaryExpression( left, node.operator, right ) if (isolate) { const name = `tmp${scope.index++}` expressionStatements.push( createVariable('const', createIdentifier(name), binary ) ) output.push(createIdentifier(name)) } else { output.push(binary) } }, ConditionalExpression() { const [test, testExpressionStatements] = normalizeExpression(node.test, scope, true) const [consequent, consequentExpressionStatements] = normalizeExpression(node.consequent, scope, true) const [alternate, alternateExpressionStatements] = normalizeExpression(node.alternate, scope, true) expressionStatements.push(...testExpressionStatements) expressionStatements.push(...consequentExpressionStatements) expressionStatements.push(...alternateExpressionStatements) const conditional = createConditionalExpression( test, consequent, alternate ) if (isolate) { const name = `tmp${scope.index++}` expressionStatements.push( createVariable('const', createIdentifier(name), conditional ) ) output.push(createIdentifier(name)) } else { output.push(conditional) } }, AssignmentExpression() { const [assign, expressions] = normalizeAssignmentExpression(node, scope) expressionStatements.push(...expressions) output.push(assign) }, ArrayPattern() { const array = [] node.elements.forEach(element =&gt; { const [el, elExpressionStatements] = normalizeExpression(element, scope) array.push(el) expressionStatements.push(...elExpressionStatements) }) output.push(array) }, Literal() { output.push(node) }, ObjectExpression() { const array = [] node.properties.forEach(prop =&gt; { const [el, elExpressionStatements] = normalizeExpression(prop, scope) array.push(el) expressionStatements.push(...elExpressionStatements) }) const objectExp = createObjectExpression(array) if (isolate) { const name = `tmp${scope.index++}` expressionStatements.push( createVariable('const', createIdentifier(name), objectExp ) ) output.push(createIdentifier(name)) } else { output.push(objectExp) } }, Property() { const [key, keyExps] = normalizeExpression(node.key, scope) const [value, valueExps] = normalizeExpression(node.value, scope) expressionStatements.push(...keyExps) expressionStatements.push(...valueExps) output.push(createProperty(key, value)) }, ArrayExpression() { const array = [] node.elements.forEach(element =&gt; { const [el, elExpressionStatements] = normalizeExpression(element, scope) array.push(el) expressionStatements.push(...elExpressionStatements) }) output.push(createArrayExpression(array)) }, FunctionExpression() { output.push(...normalizeFunctionExpression(node, scope)) }, VariableDeclaration() { output.push(...normalizeVariableDeclaration(node, scope)) }, ThisExpression() { output.push(node) }, SpreadElement() { const [spread, expressions] = normalizeSpreadElement(node, scope) expressionStatements.push(...expressions) output.push(spread) }, ArrowFunctionExpression() { const [arrow, arrowExps] = normalizeArrowFunctionExpression(node, scope) expressionStatements.push(...arrowExps) output.push(arrow) }, UpdateExpression() { const [update, updateExps] = normalizeUpdateExpression(node, scope) expressionStatements.push(...updateExps) output.push(update) }, UnaryExpression() { const [update, updateExps] = normalizeUnaryExpression(node, scope, isolate) expressionStatements.push(...updateExps) if (isolate) { const name = `tmp${scope.index++}` expressionStatements.push( createVariable('const', createIdentifier(name), update ) ) output.push(createIdentifier(name)) } else { output.push(update) } }, NewExpression() { const [ctor, expressions] = normalizeNewExpression(node, scope) expressionStatements.push(...expressions) output.push(ctor) } } call(normalizers, node.type) output.push(expressionStatements) return output } function normalizeUnaryExpression(node, scope, isolate) { const [argument, argumentExps] = normalizeExpression(node.argument, scope, isolate) return [ createUnaryExpression(argument, node.operator, node.prefix), argumentExps ] } function createUnaryExpression(argument, operator, prefix) { return { type: 'UnaryExpression', argument, operator, prefix } } function normalizeUpdateExpression(node, scope) { const [argument, argumentExps] = normalizeExpression(node.argument, scope) return [ createUpdateExpression(argument, node.operator, node.prefix), argumentExps ] } function createUpdateExpression(argument, operator, prefix) { return { type: 'UpdateExpression', argument, operator, prefix } } function call(obj, method, ...args) { if (!obj.hasOwnProperty(method)) { throw new Error(`Missing method ${method}`) } return obj[method](...args) } </code></pre> <p>So what this does is take a JavaScript source string, parse it into an AST, the traverse the AST and &quot;normalize&quot; it in a certain way, essentially hoisting variables and putting everything on a single line, so there are no nested expressions really. I am doing this for a side project, to transpile JS into a custom programming language, which only has rudimentary structures. So I simplify/normalize the JS so it can be easily converted into the target language.</p> <p>The way the code above works is, it is at a certain node. Then within that node you have a context of property expressions you can parse, so based on the context of the parent node, you have a few options for parsing the child property nodes. For example, the VariableDeclaration has an <code>id</code> prop, and an <code>init</code> prop. The <code>id</code> prop can be a simple name, or it can be an array expression (or an object expression, but I haven't handled that case just yet, only the array expression case). So we might have these examples:</p> <pre><code>const a1 = 123 const a2 = b const [a3, a4] = c const { a5, a6 } = d </code></pre> <p>For the array expression, it converts it into two different variable declarations, so it would be:</p> <pre><code>const a3 = c[0] const a4 = c[1] const a5 = d.a5 const a6 = d.a6 </code></pre> <p>Stuff like that. So that handling is based on the context. Likewise, in the ExpressionStatement context, we assume we have a whole line to ourselves. While in the plain Expression context, we could be nested inside something else. So you might have a ternary/conditional expression as an ExpressionStatement (on a line), or nested in an argument to a CallExpression. That sort of stuff. Or as the result of a variable. Etc.</p> <p>So what I ended up doing to &quot;solve&quot; these cases is to just duplicate a lot of the logic in multiple different contexts as you'll notice. They have slightly different final result handling, but the bulk of it is the same.</p> <p>How could I accomplish the following?</p> <ol> <li><strong>Reduce the duplication.</strong> So that there is only ideally one normalizer per node type, or at least the bulk of it is abstracted away somehow.</li> <li><strong>We can remove the <code>normalizers</code> objects</strong>. This is a dynamically constructed object with function handlers for each node type <em>depending on the context of the parent</em>. It uses a <code>node</code> property for the most part, coming from the parent function scope. Ideally we wouldn't be constructing functions like this on the fly. Instead, there would be a flat list of normalizer functions, independent of context potentially? I dunno if that is possible. But something to remove the scope-dependent implementation like I have.</li> </ol> <p><em>Do you even need the <code>normalizers</code> objects? Do you need to keep track of the parent context, and have a normalize function for each parent/child context pair? I'm not sure.</em></p> <p>You don't have to rewrite the entire file as it's over 1,000 lines currently and it is probably too much work. But if you could paint the picture on how to specifically refactor it to address these 2 points, that would be wonderful. Thank you.</p> <p><em>Note: what I'm finding is that I haven't handled every combination of contexts (parent/child relationships), so I keep having to add more normalizers to the normalizer map as I encounter them. But I have handled almost every type of expression at least once, so in theory I should not have to extend the code any further. That's sort of what I'm thinking.</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:04:52.457", "Id": "533516", "Score": "0", "body": "How is [this branch](https://github.com/lancejpollard/normalize-ast.js/blob/de18f76499a60aabfffab563bb9dd99e7986ae21/index.js) in terms of refactoring (and making more robust)?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T01:34:59.800", "Id": "270208", "Score": "3", "Tags": [ "javascript", "algorithm" ], "Title": "How to remove a lot of the duplication in this JavaScript AST transformer?" }
270208
<p>Consider the following piece of code I wrote (a templated Linked List):</p> <pre class="lang-java prettyprint-override"><code>package com.data_structures; public class LinkedList&lt;NodeDataType&gt; { public LinkedList() { super(); } class LinkedListNode&lt;DataType&gt; { private DataType data; LinkedListNode&lt;DataType&gt; nextNode; public LinkedListNode(DataType data) { this.data = data; this.nextNode = null; } public DataType getData() { return data; } public void setData(DataType data) { this.data = data; } @Override public String toString() { return String.valueOf(data).toString(); } } private LinkedListNode&lt;NodeDataType&gt; rootNode = null; private int nodeCount = 0; private void addTail(LinkedList&lt;NodeDataType&gt;.LinkedListNode&lt;NodeDataType&gt; node) { LinkedList&lt;NodeDataType&gt;.LinkedListNode&lt;NodeDataType&gt; temp = rootNode; while (temp.nextNode != null) { temp = temp.nextNode; } temp.nextNode = node; } private void changeRoot(LinkedList&lt;NodeDataType&gt;.LinkedListNode&lt;NodeDataType&gt; node) { node.nextNode = this.rootNode; this.rootNode = node; } private void addNodeAt(LinkedList&lt;NodeDataType&gt;.LinkedListNode&lt;NodeDataType&gt; node, int position) { LinkedListNode&lt;NodeDataType&gt; temp = this.rootNode; for (int i = 0; i &lt; position - 1; i++) { temp = temp.nextNode; } node.nextNode = temp.nextNode; temp.nextNode = node; } public LinkedList(NodeDataType data) { this.rootNode = new LinkedListNode&lt;&gt;(data); this.nodeCount++; } public int getNodeCount() { return nodeCount; } public void addNode(NodeDataType data, int position) { LinkedListNode&lt;NodeDataType&gt; node = new LinkedListNode&lt;&gt;(data); if (position &lt;= 1 || this.rootNode == null) { changeRoot(node); } else if (position &gt;= this.nodeCount) { addTail(node); } else { addNodeAt(node, position); } this.nodeCount++; } private void eraseRoot() { this.rootNode = this.rootNode.nextNode; } private void eraseTail() { LinkedList&lt;NodeDataType&gt;.LinkedListNode&lt;NodeDataType&gt; temp = this.rootNode; LinkedList&lt;NodeDataType&gt;.LinkedListNode&lt;NodeDataType&gt; temp2 = temp; while (temp.nextNode != null) { temp2 = temp; temp = temp.nextNode; } temp2.nextNode = null; } private void eraseNodeAt(int position) { LinkedList&lt;NodeDataType&gt;.LinkedListNode&lt;NodeDataType&gt; temp = this.rootNode; LinkedList&lt;NodeDataType&gt;.LinkedListNode&lt;NodeDataType&gt; temp2 = temp; for (int i = 0; i &lt; position - 1; i++) { temp2 = temp; temp = temp.nextNode; } temp2.nextNode = temp.nextNode; } public void deleteNode(int position) { if (position &lt;= 1) { eraseRoot(); } else if (position &gt;= this.nodeCount) { eraseTail(); } else { eraseNodeAt(position); } this.nodeCount--; } public NodeDataType getNode(int position) { if (position &lt;= 1) { return this.rootNode.data; } else { LinkedList&lt;NodeDataType&gt;.LinkedListNode&lt;NodeDataType&gt; node = this.rootNode; for (int i = 0; i &lt; position - 1 &amp;&amp; node.nextNode != null; i++) { node = node.nextNode; } return node.data; } } } </code></pre> <p>If we take a careful look at <code>addNode</code> and <code>deleteNode</code> functions, we see that I essentially had to write separate logic for &quot;ends&quot; and &quot;in-betweeners&quot;. I don't usually code in Java, and am not very good at Java. Is there a better logic for these 2 functions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T06:00:18.160", "Id": "533471", "Score": "0", "body": "With the language you are most comfortable with, do you know the way to avoid the _separate logic_?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T06:10:54.033", "Id": "533472", "Score": "0", "body": "@vnp *do you know the way to avoid the separate logic?* frankly, that's part of the question " } ]
[ { "body": "<h1>Template Type Parameter</h1>\n<p>You've used <code>NodeDataType</code> for your <code>LinkedList</code> template type parameter, and <code>DataType</code> for your <code>LinkedListNode</code> template type parameter. Why are these different?</p>\n<p>Considering your code is littered with <code>LinkedList&lt;NodeDataType&gt;.LinkedListNode&lt;NodeDataType&gt;</code> types, it seems you want the same type used for both classes.</p>\n<p>But if you want the same type, why are you specifying it twice?</p>\n<h1>Nested Types</h1>\n<p>What is the type name for the list's internal nodes? It is not <code>LinkedListNode</code>; it is <code>LinkedList::LinkedListNode</code>. Somewhat verbose? A little too redundant? Perhaps <code>Node</code> is sufficient.</p>\n<h1>Organization</h1>\n<p>Put like thing together. Inside <code>LinkedList</code>, you have a constructor, then a type definition, then data members, then methods, then another constructor, then more methods.</p>\n<p>Better would be a type definition, data members, constructors, and methods.</p>\n<h1>Access restriction</h1>\n<p>Why is <code>data</code> private, but <code>nextNode</code> isn't?</p>\n<p>Does anything external to <code>LinkedList</code> need access to the internal node structure at all? Internal nodes are never returned by a <code>public</code> method, so the entire class could be <code>private</code>.</p>\n<h1>super</h1>\n<p>Why is does the <code>LinkedList()</code> constructor calling <code>super()</code> when there is no parent class defined?</p>\n<p>Why doesn't the <code>LinkedList(NodeDataType data)</code> constructor call <code>super()</code>?</p>\n<h1>First Rework</h1>\n<p>Applying the above points, you're code can look more like:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class LinkedList&lt;DataType&gt; {\n\n private class Node { // No need for an additional template parameter type!\n private DataType data;\n Node next;\n\n /* constructors &amp; methods */\n }\n \n private Node rootNode = null;\n private int nodeCount = 0;\n \n public LinkedList() {\n }\n \n public LinkedList(DataType data) {\n addNode(data, 1);\n }\n \n /* methods */\n}\n</code></pre>\n<p>Notice the second constructor isn't creating a node, setting it to root, and incrementing the node count; it is just using a routine which will already do this for you.</p>\n<h1>Redundant code</h1>\n<p>You've written the following code a few times:</p>\n<pre><code> for (int i = 0; i &lt; position - 1; i++) {\n temp = temp.nextNode;\n }\n</code></pre>\n<p>It is in <code>addNodeAt</code>, <code>getNode</code>. Very similar code is in <code>eraseNodeAt</code>. Even <code>addTail</code>, and <code>eraseTail</code>, are close to this code, if you consider the tail is at position <code>nodeCount</code>.</p>\n<p>Let's write the code once:</p>\n<pre><code> private Node findNode(int position) {\n if (position &lt; 1 || position &gt; nodeCount)\n raise IndexOutOfBoundsException(&quot;Position is not within linked list&quot;);\n\n Node node = rootNode;\n for(int i = 1; i &lt; position; i++) {\n node = node.nextNode;\n }\n\n return node;\n }\n</code></pre>\n<p>Note: I've made indexes outside the range <code>1 &lt;= position &lt;= nodeCount</code> an error, as opposed to silently treating those as the head or tail nodes.</p>\n<p>Now we can easily use this helper function in other functions:</p>\n<pre><code> public DataType getNode(int position) {\n Node node = findNode(position);\n return node.getData();\n }\n</code></pre>\n<p>Adding and removing nodes can use this too. But we need to be a little careful. To add or remove a node at <code>position</code>, we need to access the node at <code>position - 1</code> and manipulate that node's <code>nextNode</code>. To add/remove the node at the root, there is no node before it, so that will remain a special case. Eg)</p>\n<pre><code> public void addNode(DataType data, int position) {\n Node new_node = new Node(data);\n if (position == 1) {\n new_node.nextNode = rootNode;\n rootNode = new_node;\n } else {\n Node prev_node = findNode(position - 1);\n new_node.nextNode = prev_node.nextNode;\n prev_node.nextNode = new_node;\n }\n nodeCount++;\n }\n</code></pre>\n<p>Note that adding at the tail is not a special case, since <code>prev.nextNode</code> will contain <code>null</code> before the addition, and that <code>null</code> value is simply copied to the new node's <code>nextNode</code>.</p>\n<p>Similar code for <code>deleteNode</code> left to student.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T05:30:30.753", "Id": "533560", "Score": "0", "body": "*You've used NodeDataType for your LinkedList template type parameter, and DataType for your LinkedListNode template type parameter. Why are these different?* When I used DataType as the type parameter for both the outer class and the inner class, Visual Studio Code gave me a \"mask\" warning. That is why I'd to do it like that, but I think the way you've suggested is better because it'll reduce the redundancy in the code, for the use case where NodeDataType and DataType have different values is practically and logically impossible :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T05:33:03.213", "Id": "533561", "Score": "0", "body": "*Considering your code is littered with LinkedList<NodeDataType>.LinkedListNode<NodeDataType> types, it seems you want the same type used for both classes.* Um... I didn't quite understand this. Please you please explain this part? Do you mean, I can do *LinkedList.LinkedListNode<NodeDataType>* and it will still logically be the same?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T05:34:01.597", "Id": "533562", "Score": "0", "body": "*I've made indexes outside the range 1 <= position <= nodeCount an error, as opposed to silently treating those as the head or tail nodes* That is what I would have done normally, but that was a part of the assignment. That is why I had to do it like that :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T05:35:25.537", "Id": "533563", "Score": "0", "body": "*Why is does the LinkedList() constructor calling super() when there is no parent class defined?* Isn't the parent class `Object` by default?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T23:58:59.253", "Id": "270239", "ParentId": "270210", "Score": "3" } } ]
{ "AcceptedAnswerId": "270239", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T04:49:34.930", "Id": "270210", "Score": "2", "Tags": [ "java", "performance", "linked-list" ], "Title": "Finding better logic for addition and removal of Nodes in a Linked List" }
270210
<h1>Front Matter</h1> <p>I'm learning Scala and have not gotten used to functional programming and the language. I'm hoping a review of my naively implemented code can help me bridge my object-oriented ways to something more functional and Scala-prescribed.</p> <p>I've uploaded all of my code here: <a href="https://gitlab.com/-/snippets/2209023/" rel="nofollow noreferrer">https://gitlab.com/-/snippets/2209023/</a></p> <h1>Problem</h1> <p>I have to merge 2 data sets and product a XML output.</p> <ul> <li>one dataset is entity data, e.g. <code>entity.csv</code></li> </ul> <pre><code>name, ip, name1,, name1,1.2.3.4, name3,1.2.3.4, name4,1.2.3.4, </code></pre> <ul> <li>another data set is streaming data, e.g. <code>streaming.csv</code></li> </ul> <pre><code>name, event, name1, event1, name1, event2, name2, event3, name3, event4, </code></pre> <h1>Concerns</h1> <p>I was not sure how to merge the 2 datasets without storing the data in a list of model objects. Is there a functional programming pattern to do this type of joining/merging?</p> <p>I thought that if I get a list of objects then I can feed it to a templating engine to produce the XML output. Is there a functional programming pattern to render the merged data as XML?</p> <h1>Approach</h1> <p>My naive approach is to:</p> <ol> <li>get a list of all the device names</li> <li>iterate through this list and fill out all of the relevant data needed for the XML output</li> <li>feed the list to a templating engine to product the XML file <ul> <li>This part has not been completed yet</li> </ul> </li> </ol> <h1>Implementation</h1> <h2>Step 1: Get List of Devices</h2> <p>In <code>Main.scala</code>, get a list of all the devices, e.g. <code>devices_list</code>:</p> <pre><code> val streaming = spark.read ... .load(&quot;src/main/resources/streaming.csv&quot;) // using steaming data because we want devices that has events ... val devices_df = streaming .select( &quot;name&quot;, ) .distinct val devices_list = new Devices(devices_df).devices() </code></pre> <p>In <code>Devices.scala</code>:</p> <pre><code>import org.apache.spark.sql.{Dataset, Row} import scala.collection.mutable.ListBuffer class Devices( val devices_df: Dataset[Row], ){ private var _devices = List[Device]() def devices(): List[Device] = { _get_devices() } private[this] def _get_devices(): List[Device] = { if (_devices.isEmpty) { _devices = _initialize_list_of_devices() } _devices } private[this] def _initialize_list_of_devices(): List[Device] = { val devices_list = ListBuffer[Device]() for (device &lt;- devices_df.collect()) { devices_list += new Device( device.getAs[String](&quot;name&quot;), ) } devices_list.toList } } </code></pre> <p>In <code>Device.scala</code>:</p> <pre><code>class Device( val name: String, ){ private var _events = List[String]() private var _ip = &quot;&quot; def getName(): String = { name } def getEvents(): List[String] = { _events } def setEvents(events: List[String]): Unit = { _events = events } def getIp(): String = { _ip } def setIp(ip: String): Unit = { _ip = ip } } </code></pre> <h2>Step 2: Fill Out Data for Each Device</h2> <p>In <code>Main.scala</code>, iterate through the list of devices and use <code>DataFiller</code> class:</p> <pre><code> for (device &lt;- devices_list) { new DataFiller( device, streaming, entity, ).fill() } </code></pre> <p>In <code>DataFiller</code>:</p> <pre><code>import org.apache.spark.sql.{Dataset, SparkSession, Row} import org.apache.spark.sql.functions.col class DataFiller( var device: Device, val streaming: Dataset[Row], val entity: Dataset[Row], ){ def fill() = { _fillEvents() _fillIp() } private[this] def _fillEvents(): Unit = { device.setEvents( streaming .filter(col(&quot;name&quot;) === device.getName()) .select(&quot;event&quot;) .rdd.map(event =&gt; { event.getAs[String](&quot;event&quot;) }) .collect.toList ) } private[this] def _fillIp(): Unit = { val ip_column = device_network_info .filter(col(&quot;name&quot;) === device.getName()) .filter(row =&gt; { !row.getAs[String](&quot;ip&quot;).isEmpty }) .select(&quot;ip&quot;) var ip:Any = &quot;&quot; if(!ip_column.rdd.isEmpty) { ip = ip_column.first().get(0) device.setIp(ip.toString) } } } </code></pre> <h2>Step 3: Output to XML</h2> <p>I have not implemented this part yet. I was thinking to use a templating engine and render the <code>devices_list</code>. I was not sure how to do this functionally without having a list with all of the data in model classes.</p> <p>Thank you for your time </p> <p>Here's the entire <code>Main.scala</code>:</p> <pre><code>import org.apache.spark.sql.SparkSession object Main extends App { val spark = SparkSession .builder() .master(&quot;local&quot;) .getOrCreate() val streaming = spark.read ... .load(&quot;src/main/resources/streaming.csv&quot;) val entity = spark.read ... .load(&quot;src/main/resources/entity.csv&quot;) val devices_df = streaming .select( &quot;name&quot;, ) .distinct val devices_list = new Devices(devices_df).devices() for (device &lt;- devices_list) { new DataFiller( device, streaming, entity, ).fill() } // output devices_list to XML spark.stop() } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T07:08:25.673", "Id": "533477", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T08:05:53.830", "Id": "533485", "Score": "2", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T08:18:53.380", "Id": "533487", "Score": "0", "body": "@TobySpeight thank you for your help. I think that’s a better description than anything I can think." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T06:47:31.883", "Id": "270213", "Score": "0", "Tags": [ "beginner", "functional-programming", "scala", "data-mining", "etl" ], "Title": "Relational join of two datasets" }
270213
<p>I'm testing to use a fluent builder pattern for generating a pdf file using AbcPDF. I've looked at several methods of accomplishing this and I'd be very glad to get some input on what I've written so far to see if I'm going in the right direction or if there's some criticism.</p> <p>The idea is that I have a builder for each component in the pdf:</p> <ul> <li>Footer builder</li> <li>Page numbers builder</li> <li>Index builder</li> <li>Project information builder</li> <li>Customer information builder</li> <li>Document content (the main text) builder</li> </ul> <p>So for example I have an &quot;umbrella&quot; builder for generating a customer document that can contain some or all parts in that list. And then another &quot;umbrella&quot; builder for generating another type of document but contains some parts of the list.</p> <p>The main idea is to use the builders in the list for generating different types of documents. For example a sales report may contain some main content, footer and page numbers, whilst a customer document also needs customer information and maybe project information.</p> <p>I've looked at some that use inheritance with recursive generics, and fatected builders but in those examples my &quot;component builders&quot; (ref list above) would be coupled to the sales report builder or customer document builder. At least in those examples I've read(?).</p> <p>But yeah, the general idea is to have small builders not coupled with anything that can be reused by bigger builders that expose a set of the small builders that are appropriate to have in that context. Or is there a pattern better suited for this goal? Thanks :) And yeah, I don't know if the interfaces are neccessary, but I guess I kept them there to hear about what you guys thought about it.</p> <p>And the Doc variable is from the ABC pdf nuget package. It's the variable I write everything to. <a href="https://www.websupergoo.com/helppdfnet/default.htm" rel="nofollow noreferrer">Documentation</a></p> <pre><code>public class Main { public void Run() { CustomerDocumentBuilder.Create() .AddCustomerInformation(new CustomerInformation { Name = &quot;customer&quot; }) .AddProjectInformation(new ProjectInformation { Name = &quot;Project&quot; }) .AddDocument(new DocumentInformation { Name = &quot;Document text&quot; }) .AddPageNumbers() .AddFooter(&quot;Footer text&quot;) .Build(); } } public class CustomerDocumentBuilder { private readonly Doc _document; private CustomerDocumentBuilder() { _document = new(); } public static CustomerDocumentBuilder Create() =&gt; new(); public void Build() { _document.Save(&quot;C:\\pdf\\textflow.pdf&quot;); } public CustomerDocumentBuilder AddDocument( DocumentInformation documentInfo) { new DocumentBuilder(_document).AddDocument(documentInfo); return this; } public CustomerDocumentBuilder AddCustomerInformation( CustomerInformation customerInfo) { new CustomerBuilder(_document).AddCustomerInformation(customerInfo); return this; } public CustomerDocumentBuilder AddProjectInformation( ProjectInformation projectInfo) { new ProjectInfoBuilder(_document).AddProjectInformation(projectInfo); return this; } public CustomerDocumentBuilder AddFooter( string footerText) { new FooterBuilder(_document).AddFooter(footerText); return this; } public CustomerDocumentBuilder AddPageNumbers() { new PageNumbersBuilder(_document).AddPageNumbers(); return this; } } public class SalesReportBuilder { private readonly Doc _document; private SalesReportBuilder() { _document = new(); } public static SalesReportBuilder Create() =&gt; new(); public void Build() { _document.Save(&quot;C:\\pdf\\textflow.pdf&quot;); } public SalesReportBuilder AddDocument( DocumentInformation documentInfo) { new DocumentBuilder(_document).AddDocument(documentInfo); return this; } public SalesReportBuilder AddFooter( string footerText) { new FooterBuilder(_document).AddFooter(footerText); return this; } public SalesReportBuilder AddPageNumbers( DocumentInformation documentInfo) { new PageNumbersBuilder(_document).AddPageNumbers(); return this; } } public class CustomerBuilder : ICustomerBuilder { private readonly Doc _document; public CustomerBuilder( Doc document) { _document = document; } public ICustomerBuilder AddCustomerInformation( CustomerInformation customerInfo) { _document.AddTextStyled(customerInfo.Name); // etc... return this; } } public class DocumentBuilder : IDocumentBuilder { private readonly Doc _document; public DocumentBuilder( Doc document) { _document = document; } public IDocumentBuilder AddDocument( DocumentInformation documentInfo) { _document.AddTextStyled(documentInfo.Name); // etc... return this; } } public class ProjectInfoBuilder : IProjectInfoBuilder { private readonly Doc _document; public ProjectInfoBuilder( Doc document) { _document = document; } public IProjectInfoBuilder AddProjectInformation( ProjectInformation projectInfo) { _document.AddTextStyled(projectInfo.Name); // etc... return this; } } public class FooterBuilder : IFooterBuilder { private readonly Doc _document; public FooterBuilder( Doc document) { _document = document; } public IFooterBuilder AddFooter( string footerText) { _document.AddTextStyled(footerText); // etc... return this; } } public class PageNumbersBuilder : IPageNumbersBuilder { private readonly Doc _document; public PageNumbersBuilder( Doc document) { _document = document; } public IPageNumbersBuilder AddPageNumbers() { //calculcate pages and insert // page number to each pages return this; } } public interface IDocumentBuilder { IDocumentBuilder AddDocument(DocumentInformation documentInfo); } public interface ICustomerBuilder { ICustomerBuilder AddCustomerInformation(CustomerInformation customerInfo); } public interface IProjectInfoBuilder { IProjectInfoBuilder AddProjectInformation(ProjectInformation projectInfo); } public interface IFooterBuilder { IFooterBuilder AddFooter(string footerText); } public interface IPageNumbersBuilder { IPageNumbersBuilder AddPageNumbers(); } public class CustomerInformation { public string Name { get; set; } } public class ProjectInformation { public string Name { get; set; } } public class DocumentInformation { public string Name { get; set; } } </code></pre> <p><strong>Updated example:</strong></p> <pre><code> public interface ICustomerTextDocumentBuilder { Doc Build(); CustomerTextDocumentBuilder WithTextDocument( DocumentInformation documentInfo); CustomerTextDocumentBuilder WithCustomerInformation( CustomerInformation customerInfo); CustomerTextDocumentBuilder WithProjectInformation( ProjectInformation projectInfo); CustomerTextDocumentBuilder WithFooter( FooterInformation footerInfo); CustomerTextDocumentBuilder WithPageNumbers(); } public class CustomerTextDocumentBuilder : ICustomerTextDocumentBuilder { private readonly Doc _document; private CustomerTextDocumentBuilder() { _document = new(); } // private footerBuilder; public static CustomerTextDocumentBuilder Create() =&gt; new(); public Doc Build() { return _document; } public CustomerTextDocumentBuilder WithTextDocument( DocumentInformation documentInfo) { new TextDocumentPdfWriter(_document).AddDocument(documentInfo); return this; } public CustomerTextDocumentBuilder WithCustomerInformation( CustomerInformation customerInfo) { new CustomerInfoPdfWriter(_document).AddCustomerInformation(customerInfo); return this; } public CustomerTextDocumentBuilder WithProjectInformation( ProjectInformation projectInfo) { new ProjectInfoPdfWriter(_document).AddProjectInformation(projectInfo); return this; } public CustomerTextDocumentBuilder WithFooter( FooterInformation footerInfo) { new FooterPdfWriter(_document).AddFooter(footerInfo); return this; } public CustomerTextDocumentBuilder WithPageNumbers() { new PageNumbersPdfWriter(_document).AddPageNumbers(); return this; } } public class CustomerInfoPdfWriter : PdfWriter { private readonly Doc _document; public CustomerInfoPdfWriter( Doc document) { _document = document; } public void AddCustomerInformation( CustomerInformation customerInfo) { // write to doc... } } public class TextDocumentPdfWriter : PdfWriter { private readonly Doc _document; public TextDocumentPdfWriter( Doc document) { _document = document; } public void AddDocument( DocumentInformation documentInfo) { _document.Width = 4; _document.FontSize = 32; _document.TextStyle.Justification = 1; _document.Rect.String = &quot;100 200 500 600&quot;; _document.FrameRect(); var theId = _document.AddTextStyled(documentInfo.Name); while (_document.Chainable(theId)) { _document.Page = _document.AddPage(); _document.FrameRect(); theId = _document.AddTextStyled(&quot;&quot;, theId); } } } public class ProjectInfoPdfWriter : PdfWriter { private readonly Doc _document; public ProjectInfoPdfWriter( Doc document) { _document = document; } public void AddProjectInformation( ProjectInformation projectInfo) { _document.Width = 2; _document.FontSize = 20; _document.TextStyle.Justification = 5; _document.Rect.String = &quot;100 650 500 750&quot;; _document.FrameRect(); _document.AddText(projectInfo.Name); } } public class FooterPdfWriter : PdfWriter { private readonly Doc _document; public FooterPdfWriter( Doc document) { _document = document; } private void AddFooterOnPage(FooterInformation footerInfo) { var top = PDF_Document_page_footer_top; _document.TextStyle.HPos = PDF_Text_Align_Left; _document.Color.String = &quot;0 0 0&quot;; _document.FontSize = 7; _document.TextStyle.Font = _document.AddFont(PDF_Fonts_Regular); const int topMargin = 4; SetRect(_document, top - topMargin, 10, 28 + 12, PDF_Document_width - 28); _document.AddText(footerInfo.OrganizationName); _document.Rect.Top = top - topMargin - 10; _document.AddText(&quot;Organization number&quot; + &quot; &quot; + footerInfo.OrganizationNumber); SetRect(_document, top - 4, top - 11, PDF_Document_Margin, PDF_Document_width - PDF_Document_Margin); _document.Color.String = PDF_Color_Grey; _document.TextStyle.HPos = PDF_Text_Align_Center; _document.AddText($&quot;Document generated at {DateTime.UtcNow:dd.MM.yyyy}&quot;); } // Adds footer on all pages public void AddFooter( FooterInformation footerInfo) { var theCount = _document.PageCount; for (int i = 1; i &lt;= theCount; i++) { _document.PageNumber = i; AddFooterOnPage(footerInfo); } } } public class PageNumbersPdfWriter : PdfWriter { private readonly Doc _document; public PageNumbersPdfWriter( Doc document) { _document = document; } public void AddPageNumbers() { //calculcate pages and insert // page number to each pages } } public abstract class PdfWriter { protected const string PDF_Fonts_Regular = &quot;Helvetica&quot;; protected const int PDF_Document_width = 595; protected const int PDF_Document_page_footer_top = 42; protected const int PDF_Document_Margin = 28; protected const string PDF_Color_Grey = &quot;120 144 156&quot;; protected const double PDF_Text_Align_Left = 0; protected const double PDF_Text_Align_Center = 0.5; protected static void SetRect(Doc theDoc, double top, double bottom, double left, double right) { theDoc.Rect.Top = top; theDoc.Rect.Bottom = bottom; theDoc.Rect.Left = left; theDoc.Rect.Right = right; } } public class FooterInformation { public string OrganizationNumber { get; set; } public string OrganizationName { get; set; } } public class CustomerInformation { public string Name { get; set; } } public class ProjectInformation { public string Name { get; set; } } public class DocumentInformation { public string Name { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T07:54:14.133", "Id": "533482", "Score": "1", "body": "Welcome to Code Review! Could you please share with the following class definitions as well: `DocumentInformation`, `CustomerInformation`, `ProjectInformation` and `Doc`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T10:04:23.277", "Id": "533492", "Score": "1", "body": "Of course! I added them now. They're just very simple dto's currently. But the Doc variable is something that is found the ABCPdf nuget package. I added a reference to the documentation for AbcPDF. But I could have used any other pdf library, since it's the pattern around I'm more concerned about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T12:04:32.647", "Id": "533501", "Score": "0", "body": "Its not fluent enough. You should replace the class instanceiation like new CustomerInformation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:35:07.530", "Id": "533511", "Score": "0", "body": "@Anders I get your point. In production they wouldn't be instantianted in the function call, but passed in as a parameter for the class containing the builder. All the data would be dto's generated mapped and retrieved from the database. Thoughts on that?" } ]
[ { "body": "<p>Maybe I misunderstand your intent but I can see lots of boilerplate code.</p>\n<h3>Builder vs Fluent</h3>\n<p>There is a common misunderstanding that these concepts are the same. Let's see what wikipedia says about them</p>\n<blockquote>\n<p>The builder pattern is a design pattern designed to provide a <strong>flexible solution to various object creation problems</strong> in object-oriented programming. The intent of the Builder design pattern is to <strong>separate the construction of a complex object from its representation</strong>.</p>\n</blockquote>\n<p><a href=\"https://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">Source</a></p>\n<blockquote>\n<p>In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to <strong>increase code legibility by creating a domain-specific language</strong> (DSL).</p>\n</blockquote>\n<p><a href=\"https://en.wikipedia.org/wiki/Fluent_interface\" rel=\"nofollow noreferrer\">Source</a></p>\n<p>Further readings: <a href=\"http://www.javabyexamples.com/builder-vs-fluent-interface/\" rel=\"nofollow noreferrer\">1</a>, <a href=\"https://stackoverflow.com/questions/45322321/difference-between-method-chaining-and-fluent-interface\">2</a>, <a href=\"https://stackoverflow.com/questions/17937755/what-is-the-difference-between-a-fluent-interface-and-the-builder-pattern/17937946\">3</a>, <a href=\"https://medium.com/@martinstm/fluent-builder-pattern-c-4ac39fafcb0b\" rel=\"nofollow noreferrer\">4</a></p>\n<hr />\n<h3>Builder</h3>\n<p>As its name suggests it construct something. In your case it persist something to the disk.</p>\n<p>So, from a consumer perspective it should look more like this:</p>\n<pre><code>var docBuilder = new CustomerDocumentBuilder();\nvar doc = docBuilder\n .WithCustomerInformation(&quot;customer&quot;)\n .WithProjectInformation(&quot;Project&quot;)\n .WithDocument(&quot;Document text&quot;)\n .WithPageNumbers()\n .WithFooter(&quot;Footer text&quot;)\n .Build();\n\ndoc.Save(&quot;C:\\\\pdf\\\\textflow.pdf&quot;);\n</code></pre>\n<p>If the usage looks like this, then the implementation requires only two classes</p>\n<h3><code>CustomerDocument</code></h3>\n<pre><code>public class CustomerDocument\n{\n private readonly Doc _doc;\n\n public CustomerDocument(Doc doc) =&gt; _doc = doc;\n \n public void Save(string path) =&gt; _doc.Save(path);\n}\n</code></pre>\n<h3><code>CustomerDocumentBuilder</code></h3>\n<pre><code>public class CustomerDocumentBuilder\n{\n private readonly Doc _document = new ();\n\n public CustomerDocument Build() =&gt; new (_document);\n\n public CustomerDocumentBuilder WithDocument(string documentInfo)\n {\n _document.AddTextStyled(documentInfo);\n return this;\n }\n\n public CustomerDocumentBuilder WithCustomerInformation(string customerInfo)\n {\n _document.AddTextStyled(customerInfo);\n return this;\n }\n\n public CustomerDocumentBuilder WithProjectInformation(string projectInfo)\n {\n _document.AddTextStyled(projectInfo);\n return this;\n }\n\n public CustomerDocumentBuilder WithFooter(string footerText)\n {\n _document.AddTextStyled(footerText);\n return this;\n }\n\n public CustomerDocumentBuilder WithPageNumbers()\n {\n //calculcate pages and insert\n // page number to each pages\n return this;\n }\n}\n</code></pre>\n<hr />\n<p><strong>UPDATE #1</strong>: review of the updated code</p>\n<h3><code>ICustomerTextDocumentBuilder</code></h3>\n<p>This interface is tightly coupled to the implementation</p>\n<ul>\n<li>Either change the return type from <code>CustomerTextDocumentBuilder</code> to <code>ICustomerTextDocumentBuilder</code></li>\n<li>Or get rid of the whole interface</li>\n</ul>\n<h3><code>CustomerDocumentBuilder</code></h3>\n<ul>\n<li>If you really want to have this &quot;facade&quot;/wrapper class then you do NOT need to create a new <code>XYZPdfWriter</code> every time when a <code>WithXYZ</code> is called</li>\n<li>You can pass it as a method argument rather than a constructor parameter</li>\n</ul>\n<pre><code>public class CustomerTextDocumentBuilder\n{\n private readonly Doc _document = new();\n private readonly TextDocumentPdfWriter _textDocumentWriter = new();\n private readonly CustomerInfoPdfWriter _customerInfoWriter = new();\n private readonly ProjectInfoPdfWriter _projectInfoWriter = new();\n private readonly FooterPdfWriter _footerWriter = new();\n private readonly PageNumbersPdfWriter _pageNumbersWriter = new();\n\n public Doc Build() =&gt; _document;\n\n public CustomerTextDocumentBuilder WithTextDocument(\n DocumentInformation documentInfo)\n {\n _textDocumentWriter.AddDocument(_document, documentInfo);\n return this;\n }\n\n public CustomerTextDocumentBuilder WithCustomerInformation(\n CustomerInformation customerInfo)\n {\n _customerInfoWriter.AddCustomerInformation(_document, customerInfo);\n return this;\n }\n ...\n}\n</code></pre>\n<pre><code>internal class TextDocumentPdfWriter\n{\n public void AddDocument(Doc document, DocumentInformation documentInfo)\n {\n document.Width = 4;\n document.FontSize = 32;\n document.TextStyle.Justification = 1;\n document.Rect.String = &quot;100 200 500 600&quot;;\n\n document.FrameRect();\n var theId = document.AddTextStyled(documentInfo.Name);\n\n while (document.Chainable(theId))\n {\n document.Page = document.AddPage();\n document.FrameRect();\n theId = document.AddTextStyled(&quot;&quot;, theId);\n }\n }\n}\n...\n</code></pre>\n<ul>\n<li>I've changed each <code>XYZPdfWriter</code> class visibility from <code>public</code> to <code>internal</code>, since you have a facade in a front of them, so you don't need to expose them direclty</li>\n</ul>\n<h3><code>PdfWriter</code></h3>\n<ul>\n<li>This is not really a base class rather a constant class\n<ul>\n<li>So treat it like that</li>\n</ul>\n</li>\n</ul>\n<pre><code>internal static class PdfWriterConstants\n{\n public const string PDF_Fonts_Regular = &quot;Helvetica&quot;;\n public const int PDF_Document_width = 595;\n public const int PDF_Document_page_footer_top = 42;\n public const int PDF_Document_Margin = 28;\n \n public const string PDF_Color_Grey = &quot;120 144 156&quot;;\n\n public const double PDF_Text_Align_Left = 0;\n public const double PDF_Text_Align_Center = 0.5;\n\n public static void SetRect(Doc theDoc, double top, double bottom, double left, double right)\n {\n theDoc.Rect.Top = top;\n theDoc.Rect.Bottom = bottom;\n theDoc.Rect.Left = left;\n theDoc.Rect.Right = right;\n }\n}\n</code></pre>\n<ul>\n<li>I've changed class's access modifier from <code>public abstract</code> to an <code>internal static</code></li>\n<li>I've also changed <code>protected</code> keywords to <code>public</code></li>\n<li>If you use <code>using static</code> like this:</li>\n</ul>\n<pre><code>using static YourNamespace.PdfWriterConstants;\n</code></pre>\n<ul>\n<li>then you don't have to prefix each and every member access with the <code>PdfWriterConstants.</code> prefix</li>\n<li>Also none of the <code>XYZPdfWriter</code> has to be inherited from anything</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T12:47:44.913", "Id": "533504", "Score": "0", "body": "I updated my example with a more extensive example. I get some of the points you are making. I think that the function AddTextStyled was a bit misleading, since the write functions for each component will in reality be much larger and complex than just calling that one function. I wrote the footer function to exemplify that, and added some more to some of the other functions. What do you think of the updated version?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:52:42.370", "Id": "533513", "Score": "1", "body": "@user1784297 I've updated my answer please check it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T16:48:10.713", "Id": "533534", "Score": "1", "body": "This looks just perfect. Really appreciate you taking the time to help me revise it. Cheers!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T11:45:00.520", "Id": "270219", "ParentId": "270215", "Score": "3" } } ]
{ "AcceptedAnswerId": "270219", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T07:32:25.500", "Id": "270215", "Score": "2", "Tags": [ "c#", "design-patterns", "pdf" ], "Title": "Using fluent builder pattern for generating pdf" }
270215
<p>I have to write a program in python that will take a number and print a right triangle attempting to use all numbers from 1 to that number. For example:</p> <pre><code>Enter number: 10 Output: 7 8 9 10 4 5 6 2 3 1 Enter number: 6 Output: 4 5 6 2 3 1 Enter number: 20 Output: 11 12 13 14 15 7 8 9 10 4 5 6 2 3 1 </code></pre> <p>For which I have written the following function</p> <pre><code>def print_right_triangle(num): c = 1 k = 0 l = [] while(k &lt; num-1): v = [] for i in range(c): v.append(k+1) k += 1 c += 1 if k &gt; num: break l.append(v) p = len(l) for i in range(p): for j in l[p-(i+1)]: print(j, end=' ') print() return None print_right_triangle(10) </code></pre> <p>It's giving the same output and solved my problem. <strong>I was wondering is there any more pythonic way to do this</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T11:43:43.367", "Id": "533499", "Score": "2", "body": "One liner with a bit of maths to find x(x+1)/2 = n: lambda x: [print(\\*range(1+i*~-i//2, 1+i*-~i//2)) for i in range(int(((1+8*x)**.5-1)/2), 0, -1)]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:27:37.203", "Id": "533509", "Score": "0", "body": "@rak1507 Thank you so much!!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:14:34.953", "Id": "533518", "Score": "0", "body": "@rak1507 could you please explain 1+i*~-i//2 this, its so tricky to understand this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:38:39.513", "Id": "533522", "Score": "1", "body": "~-i is magic for (i-1) so it's 1 + i * (i-1) // 2 (sorry: code golfing habits die hard)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T18:54:55.980", "Id": "533542", "Score": "0", "body": "@rak1507 ohhokay....got it..thank you so much for responding!" } ]
[ { "body": "<h3>Optimized != pythonic</h3>\n<p>Optimized means &quot;spending less resources&quot;. &quot;Pythonic&quot; means &quot;using idiomatic Python features&quot;. Sometimes they come together, sometimes don't. Pythonic code is clean and maintainable, while optimized can be very unclear and need many comments.</p>\n<p>Anyway, optimization should start with making the code readable, and pythonic code should be readable.</p>\n<h3>Make more use of Python features</h3>\n<p>List comprehensions, range arguments and unpacking can be very handy. This code</p>\n<pre><code> v = []\n for i in range(c):\n v.append(k+1)\n k += 1\n</code></pre>\n<p>is clearly just a</p>\n<pre><code> v = [k+1+i for i in range(c)]\n k += c\n</code></pre>\n<p>and, changing the range arguments,</p>\n<pre><code> v = list(range(k+1, k+c))\n k += c\n</code></pre>\n<p>And this code</p>\n<pre><code> for j in l[p-(i+1)]:\n print(j, end=' ')\n print()\n</code></pre>\n<p>can be written as</p>\n<pre><code> print(*l[p-(i+1)])\n</code></pre>\n<p>and</p>\n<pre><code>p = len(l)\nfor i in range(p):\n print(*l[p-(i+1)])\n</code></pre>\n<p>is walking the <code>l</code> list backwards, so it's</p>\n<pre><code>for line in reversed(l):\n print(*line)\n</code></pre>\n<p>This is pythonic.</p>\n<h3>Optimizations</h3>\n<p>Change the algorithm. Here you're gathering all the number in a list to output them. But the numbers are all in order, so you can easily avoid lists at all - just make loops with <code>print</code>s.</p>\n<p>First, read <a href=\"https://en.wikipedia.org/wiki/Triangular_number\" rel=\"nofollow noreferrer\">some theory</a>.</p>\n<p>Now you know that only numbers that equal <code>n*(n+1)/2</code> can be used to build such triangles. You can solve <code>n*(n+1)/2 = num</code> as a quadratic equation and round n down to get the number of lines without loops like <a href=\"https://codereview.stackexchange.com/users/251597/rak1507\">rak1507</a> did.</p>\n<p>Next, find formulas for starting and ending numbers in each line to put them into range arguments.</p>\n<p>And now you can code it in three lines.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:27:19.363", "Id": "533508", "Score": "0", "body": "Thank you so much!! for this wonderful explaination" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T12:38:30.200", "Id": "270221", "ParentId": "270218", "Score": "3" } } ]
{ "AcceptedAnswerId": "270221", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T11:13:24.437", "Id": "270218", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Printing reverse number triangle" }
270218
<p>JSFiddle: <a href="https://jsfiddle.net/EddTally/jsa69f7r/3/#&amp;togetherjs=zMFpAQcRTt" rel="nofollow noreferrer">https://jsfiddle.net/EddTally/jsa69f7r/3/#&amp;togetherjs=zMFpAQcRTt</a></p> <p>Those who cannot access JSFiddle:</p> <pre><code>/** * Utilizes recursion to search through an item of any type (currently accepted types are object, array and string) * to find if it contains such a value. * * @param item * @param value */ function filterItem(item, value){ // Isn't object if(typeof item == 'string'){ return filterString(item, value) } // Is Array else if(Array.isArray(item)){ return filterArray(item, value) } // Is Object else{ return filterObj(item, value) } } /** * Checks if an object contains the value by recursively calling the filterItem function to work it's way through the obj. * * @param obj * @param value */ const filterObj = (obj, value) =&gt; { let contains = false; for(let [key, val] of Object.entries(obj)){ if(key.toString().toLowerCase().includes(value)){ contains = true break; }else{ if(filterItem(val, value)){ contains = true break; } } } return contains } /** * Used in the recursive function above, goes all the way down until it reaches the base string, then would return * the result of the .includes() funtion. * * @param array * @param value */ const filterArray = (array, value) =&gt; { let contains = false; for(let x of array){ if(filterItem(x, value)){ contains = true break; } } return contains } /** * Checks if an string contains the value * @param string * @param value */ const filterString = (string, value) =&gt; { return string.toString().toLowerCase().includes(value) } let exampleObj = {&quot;hi&quot;: [&quot;five&quot;, &quot;twenty&quot;, {&quot;11&quot;: 44, &quot;eggs&quot;: [&quot;egge&quot;]}]} console.log(filterItem(exampleObj, &quot;egge&quot;)) //Should come back true </code></pre> <p>I am wondering if this search/filter function is good or not, any potential things I may have missed out on or things to make it better.</p>
[]
[ { "body": "<p>I think you are overcomplicating things. You do not need separate logic for <code>objects</code> and <code>arrays</code>. The following should do the job:</p>\n<pre><code>function filterItem(item, value) {\n if (typeof item == 'object' || Array.isArray(item)) {\n for (let i in item) {\n if (filterItem(i, value) || filterItem(item[i], value))\n return true;\n }\n return false;\n }\n if (typeof item == 'string')\n return item.toLowerCase().includes(value.toLowerCase());\n return false;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T15:24:06.890", "Id": "270229", "ParentId": "270220", "Score": "1" } }, { "body": "<p>From a short review;</p>\n<ul>\n<li><p>The function name is a bit misleading, it does not filter anything really. Could be named <code>hasValue</code>, or even <code>hasString</code></p>\n</li>\n<li><p>You could also just return the occurrence(s) of where the string is found, this could be more useful</p>\n</li>\n<li><p><code>typeof</code> returns more than you handle</p>\n</li>\n<li><p>Personally, I would make the <code>toLowerCase()</code> call only if requested by the caller</p>\n</li>\n<li><p><code>filterObj</code> should call <code>filterString</code> instead of <code>toString().toLowerCase().includes</code></p>\n</li>\n<li><p>Your ratio of comments vs. code is too high in places like this;</p>\n<pre><code> /**\n * Checks if an string contains the value\n * @param string\n * @param value\n **/\n const filterString = (string, value) =&gt; {\n return string.toString().toLowerCase().includes(value)\n }\n</code></pre>\n</li>\n</ul>\n<p>My rewrite would be something like this;\nThis one actually filters/returns all matches</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function filterString(haystack, needle){\n\n let type = typeof haystack; //\"undefined\", \"object\", \"boolean\", \"number\", \"bigint\", \"string\", \"symbol\", \"function\"\n //JS.. null is an object\n type = haystack===null?\"undefined\":type;\n \n if(Array.isArray(haystack)){\n return haystack.map(v =&gt; filterString(v, needle)).flat();\n }else if(type == \"object\"){\n return Object.keys(haystack).concat(Object.values(haystack)).map(v =&gt; filterString(v, needle)).flat();\n }else if(type == \"undefined\"){\n return (haystack+'').includes(needle)?[haystack]:[];\n }else{\n return haystack.toString().includes(needle)?[haystack]:[];\n }\n}\n \nlet example = {\"hi\": [console.log,{ thisIsNull:null, thisIsUndefined:undefined } ,4044, \"five\", \"twenty\", {\"11\": 44, \"eggs\": [\"egge\"]}]}\nconsole.log(filterString(example, \"egg\"));\nconsole.log(filterString(example, \"console\"));\nconsole.log(filterString(example, 44));\nconsole.log(filterString(example, null));\nconsole.log(filterString(example, undefined));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T18:06:53.523", "Id": "533537", "Score": "0", "body": "You need Node 11 or higher" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T22:19:40.613", "Id": "533554", "Score": "0", "body": "Warning your function will convert functions to strings including the source in the search, EG `filterString({test(){var B=0}}, \"B\"))` will return the function `test(){var B=0}`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T22:29:03.967", "Id": "533555", "Score": "0", "body": "Yep, I thought that was kind of cool" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T10:43:09.560", "Id": "533670", "Score": "0", "body": "Yes, the function name is misleading.\nToo much duplicated code, check.\nIn terms of ratio for comments vs code, I enjoy the practice of having the JSDoc popup when I hover over the function I'm using, but I should remove this if the code itself is too small?\nThank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T07:38:11.523", "Id": "533764", "Score": "0", "body": "@Tally I would, I seem to parse faster the code than the comment." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T15:42:01.950", "Id": "270230", "ParentId": "270220", "Score": "3" } }, { "body": "<h1>Bugs</h1>\n<p>Your code will throw errors if you include <code>null</code>, or <code>undefined</code> in the data.</p>\n<p>And your code does not check for cyclic data structures.</p>\n<p>First some review points.</p>\n<hr />\n<h1>Review</h1>\n<p>Some general review points regarding code style and language feature use.</p>\n<h2>Use <code>RegExp</code></h2>\n<p>Rather than use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String includes\">String.includes</a> convert the search term to a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. RegExp\">RegExp</a> with the case insensitive flag. You can then test without the need to convert to lower case. Eg <code>const match = new RegExp(value, &quot;gi&quot;);</code> See example for more.</p>\n<p>In this case <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. RegExp\">RegExp</a> has additional functionality that will help solve the bugs.</p>\n<h2>Use <code>===</code> not <code>==</code></h2>\n<p>Alwyas use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Strict equality\">=== (Strict equality)</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Strict inequality\">!== (Strict inequality)</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Equality\">== (Equality)</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Inequality\">!= (Inequality)</a></p>\n<h2><code>const</code></h2>\n<p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. const\">const</a> for variables that do not change. For example the line <code>for(let [key, val] of Object.entries(obj)){</code> should be <code>for(const [key, val] of Object.entries(obj)){</code></p>\n<h2>Reduce code noise</h2>\n<p>Don't add <code>else</code> / <code>else if</code> statements after you <code>return</code> in the previous statement block.</p>\n<p>Example</p>\n<pre><code>if (foo) {\n return 0;\n} else {\n return 1;\n}\n\n// should be\n\nif (foo) {\n return 0;\n}\nreturn 1;\n\n</code></pre>\n<h2>Use the language</h2>\n<p>Your code has not utilized appropriate language features.</p>\n<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array some\">Array.some</a> to check the content of an array of at least one match. That includes the array of entries from <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object entries\">Object.entries</a></p>\n<h2>Rewrite</h2>\n<p>Thus it could be rewritten as follows..</p>\n<pre><code>function filterItem(item, value){\n const match = new RegExp(value, &quot;gi&quot;); \n return (function filter(item){ \n if (item === null) { return false }\n if (typeof item !== 'object') { return match.test(item) }\n return Array.isArray(item) ? \n item.some(item =&gt; filter(item)) :\n Object.entries(item).some(([key, item]) =&gt; filter(key) || filter(item));\n })(item);\n}\n</code></pre>\n<p>The code checks for <code>null</code> assuming that you will not be searching for such. This is needed because <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. null\">null</a> is a type of <code>Object</code>.</p>\n<p>The code also does the string match for any item that is not an <code>Object</code> this is because the call <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. RegExp test\">RegExp.test</a> will automatically call the item's <code>toString</code> function for you.</p>\n<hr />\n<h1>Cyclic bug</h1>\n<p>However the above code and your code has a dangerous bug that can cause the page to hang, and chew up a lot of memory (depending on the object being searched)</p>\n<p>Take for example the following object..</p>\n<pre><code>const a = [];\na[0] = [a];\n</code></pre>\n<p>This will throw a call stack overflow because the data is cyclic.</p>\n<h2>Example of call stack overflow error</h2>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const a = [];\na[0] = [a];\nconsole.log(filterItem(a, \"c\")); // Will throw \n\n/****************************************************************/\n/* Cleaned up version of original code as example of cyclic bug */\n/****************************************************************/\nfunction filterItem(item, value) {\n if (typeof item == 'string') { return filterString(item, value) }\n if (Array.isArray(item)) { return filterArray(item, value) } \n return filterObj(item, value);\n}\nfunction filterObj(obj, value) {\n for (const [key, val] of Object.entries(obj)) {\n if (key.toLowerCase().includes(value)) { return true }\n if (filterItem(val, value)) { return true }\n }\n return false;\n}\nfunction filterArray(array, value) {\n for (const item of array) {\n if (filterItem(item, value)) { return true }\n }\n return false;\n}\nfunction filterString(string, value) {\n return string.toString().toLowerCase().includes(value);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Preventing call stack overflow</h2>\n<p>It is very important that you always protect against this situation. You can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set\">Set</a> to check if you have encountered an object before you search it. Each time you search an item you first add it to the set.</p>\n<h2>Example using <code>Set</code></h2>\n<p>const a = [];\na[0] = [a];\nconsole.log(filterItem1(a, &quot;c&quot;)); // Will throw</p>\n<p>The following is protected against cyclic data but be warned. Any time you call a function in JS you run the risk of running out of space on the call stack.</p>\n<pre><code>function filterItem(item, value){\n const match = new RegExp(value, &quot;gi&quot;); \n const tested = new Set();\n return (function filter(item){ \n if (!tested.has(item)) {\n tested.add(item); \n if (item === null) { return false }\n if (typeof item !== 'object') { return match.test(item) }\n return Array.isArray(item) ? \n item.some(item =&gt; filter(item)) :\n Object.entries(item).some(([key, item]) =&gt; filter(key) || filter(item));\n }\n })(item);\n}\n</code></pre>\n<p>You can improve the efficiency by using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. WeakSet\">WeakSet</a> but you will need to ensure that you don`t try and add strings, numbers and anything that is not an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object\">Object</a></p>\n<p>WeakSets do not store the object, only the reference to the hash and thus are quicker and use much less memory.</p>\n<h2>Example using <code>WeakSet</code></h2>\n<p>Note that only objects are added to the weak set.</p>\n<pre><code>function filterItem(item, value){\n const match = new RegExp(value, &quot;gi&quot;); \n const tested = new WeakSet();\n return (function filter(item){ \n if (!tested.has(item)) {\n if (item === null) { return false }\n if (typeof item !== 'object') { return match.test(item) }\n tested.add(item); \n return Array.isArray(item) ? \n item.some(item =&gt; filter(item)) :\n Object.entries(item).some(([key, item]) =&gt; filter(key) || filter(item));\n }\n })(item);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T08:03:50.157", "Id": "533666", "Score": "0", "body": "+1, forgot about cyclical in my answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T10:36:32.837", "Id": "533669", "Score": "0", "body": "Since there will be a vast amount of things in the search I will use the WeakSet version. I've always been scared of RegExp, today I will finally learn.\nThank you!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T21:55:18.807", "Id": "270235", "ParentId": "270220", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T11:54:35.603", "Id": "270220", "Score": "2", "Tags": [ "javascript" ], "Title": "Recursive Filter/Search function" }
270220
<p>I have a class <code>Scholar</code> which is basically a teacher in a university. I have to calculate the yearly salary of a scholar instance where the formula is <code>12-month salary + bonus</code><br/> the bonus is determined by the academic_position <br/> if the teacher is:</p> <ul> <li>a Professor --&gt; bonus = 70000</li> <li>an Associate Professor --&gt; bonus = 50000</li> <li>an Assistant Professor --&gt; bonus = 30000</li> </ul> <p>I want to keep the <code>bonus</code> in a separate variable so i implemented it in <code>__init__</code>, but it looks messy. not sure if it is the way to do or not. do you have any suggestion on my code? Is there a way to improve readibility? what normally a pythonista do with this kind of problem?</p> <pre><code>class Scholar: def __init__(self, name, salary, academic_position): self.name = name self.salary = salary self.academic_position = academic_position if self.academic_position == 'Professor': self.bonus = 70000 elif self.academic_position == 'Associate Professor': self.bonus = 50000 elif self.academic_position == 'Assistance Professor': self.bonus = 30000 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T17:28:04.707", "Id": "533583", "Score": "0", "body": "It's likely that it doesn't even make sense to set such an instance variable in the constructor. But we can't really advise you properly based on the tiny code excerpt you've shown here." } ]
[ { "body": "<p>If you have to stick to using this specific structure, I'd do it like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n _ACADEMIC_POSITIONS_BONUS_MAP = {\n 'Professor': 70000,\n 'Associate Professor': 50000,\n 'Assistance Professor': 30000,\n }\n\n def __init__(self, name, salary, academic_position):\n self.name = name\n self.salary = salary\n self.academic_position = academic_position\n\n @property\n def bonus(self):\n for academic_position, bonus in self._ACADEMIC_POSITIONS_BONUS_MAP.items():\n if self.academic_position == academic_position:\n return bonus\n\n raise ValueError(\n f&quot;Invalid academic position. Allowed: &quot;\n f&quot;{', '.join(self._ACADEMIC_POSITIONS_BONUS_MAP)}&quot;\n )\n</code></pre>\n<p>And as other have mentioned, instead of iterating through the dict itself you can just do this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n # ...\n\n @property\n def bonus(self):\n return self._ACADEMIC_POSITIONS_BONUS_MAP[self.academic_position]\n</code></pre>\n<p>We've created a map between each type of <code>academic_position</code> and its specific <code>bonus</code> and a <code>@property</code> where we return the bonus.</p>\n<p>And then you can use it like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>professor = Scholar(&quot;John Doe&quot;, 30000, &quot;Professor&quot;)\nassociate_professor = Scholar(&quot;Associate John Doe&quot;, 30000, &quot;Associate Professor&quot;)\nassistance_professor = Scholar(&quot;Assistance John Doe&quot;, 30000, &quot;Assistance Professor&quot;)\n\n\nprint(professor.bonus)\nprint(associate_professor.bonus)\nprint(assistance_professor.bonus)\n</code></pre>\n<p>Now, when you need to add another <code>academic_position</code>, you just have to modify <code>_ACADEMIC_POSITIONS_BONUS_MAP</code>.</p>\n<p>Next, in order to calculate the yearly salary, just create another method within your class:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n # ...\n\n def get_yearly_salary(self):\n # Note: multiply the salary with 12 if it's monthly-based\n return self.salary + self.bonus\n</code></pre>\n<p>Note: I'm not sure if <code>@property</code> is the best way of doing this. You could've just done something along the lines:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Scholar:\n _ACADEMIC_POSITIONS_BONUS_MAP = {\n 'Professor': 70000,\n 'Associate Professor': 50000,\n 'Assistance Professor': 30000,\n }\n\n def __init__(self, name, salary, academic_position):\n self.name = name\n self.salary = salary\n self.academic_position = academic_position\n\n self.bonus = self.get_bonus()\n\n def get_bonus(self):\n for academic_position, bonus in self._ACADEMIC_POSITIONS_BONUS_MAP.items():\n if self.academic_position == academic_position:\n return bonus\n\n raise ValueError(\n f&quot;Invalid academic position. Allowed: &quot;\n f&quot;{', '.join(self._ACADEMIC_POSITIONS_BONUS_MAP)}&quot;\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:53:30.337", "Id": "533514", "Score": "0", "body": "@ Grajdeano Alex thanks you so much for your answers. so basically @property is like an attribute which has immediate invoked call? we can access simply just like it is an instance variable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:56:17.247", "Id": "533515", "Score": "0", "body": "and you're suggesting that I should write get_bonus() instead of the @property bonus in order to protect the variable from changing outside the class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:10:17.973", "Id": "533517", "Score": "0", "body": "Basically yes. For a deeper read [have at this](https://www.programiz.com/python-programming/property)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:15:53.573", "Id": "533519", "Score": "0", "body": "thanks for the knowledges" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T18:18:48.310", "Id": "533540", "Score": "2", "body": "Iterating over a `dict` to check a value for equality against each key seems to defeat the purpose of using a `dict`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T19:00:19.603", "Id": "533543", "Score": "0", "body": "@GrajdeanuAlex I downvoted this answer because of the terrible use of the dict - it's not great to suggest answers to new people when you clearly haven't got a solid grasp of python yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T10:16:19.220", "Id": "533576", "Score": "1", "body": "@FMc yep, that's correct. It was pretty late when I wrote this. Added extra-comments for that part now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T10:18:33.570", "Id": "533577", "Score": "0", "body": "@rak1507 Fixed now. We're all learning here :) Next time if something is wrong, answer the question yourself and pinpoint what's wrong in other answers and why instead of just throwing out words. That't how OP and others can learn." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:25:46.207", "Id": "270224", "ParentId": "270222", "Score": "1" } }, { "body": "<p>You have a small class where the position must be one of three allowed values\nand where the bonus is derived purely from the position. Under typical\nconditions, this implies that you should validate the position and compute the\nbonus dynamically based on position (don't store the bonus, compute it). The\nway to achieve both of those things in via properties: a getter for bonus and\nboth a getter and setter for position. Here's an illustration with some\nadditional explanations in the comments.</p>\n<pre><code>class Scholar:\n\n # A data structure that links positions to bonuses and also\n # provides a mechanism to validate the position itself.\n\n BONUSES = {\n 'Professor': 70000,\n 'Associate Professor': 50000,\n 'Assistance Professor': 30000, # Shouldn't this be Assistant?\n }\n\n def __init__(self, name, salary, academic_position):\n self.name = name\n self.salary = salary\n self.academic_position = academic_position\n\n # Bonus is always computed dynamically, so position and bonus\n # are never out of sync. Since we do not want users of the Scholar\n # class to set the bonus, we only define the getter property.\n\n @property\n def bonus(self):\n return self.BONUSES[self.academic_position]\n\n # Position requires actual validation, so we need both a getter and a\n # setter. The setter raises an error if the position is invalid, and the\n # actual attribute is stored under the same name with an underscore prefix,\n # which conveys the idea to class users that the attribute is intended to\n # be managed by the class, not by users.\n\n @property\n def academic_position(self):\n return self._academic_position\n\n @academic_position.setter\n def academic_position(self, value):\n if value in self.BONUSES:\n self._academic_position = value\n else:\n # Adjust the error message as needed to explain the problem\n # in more detail or to provide allowed values.\n raise ValueError('Invalid academic_position')\n</code></pre>\n<p>That's the garden-variety way to handle stuff like this, in the sense that\nyou'll find many online tutorials covering approaches like it. One thing to\nnotice is that properties are a bit of a pain: they tend to spawn a lot of\nboilerplate code, and the whole things starts to feel too much like an\nunpleasant language that shall not be named.</p>\n<p>Before going to this trouble I would first ask a deeper question: <strong>should\nScholar instance be mutable</strong>? Based on what you've told us so far, the\nanswer could be no. In that case, <code>Scholar</code> could be a <code>namedtuple</code> or\n<code>dataclass</code>. For example:</p>\n<pre><code>from collections import namedtuple\n\nScholar = namedtuple('Scholar', 'name salary academic_position bonus')\n\nBONUSES = {\n 'Professor': 70000,\n 'Associate Professor': 50000,\n 'Assistant Professor': 30000,\n}\n\ndef make_scholar(name, salary, academic_position):\n # Here you get minimal error handling for free, as a KeyError.\n # If desired, wrap in a try-except structure to raise\n # a more informative ValueError.\n bonus = BONUSES[academic_position]\n return Scholar(name, salary, academic_position, bonus)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T03:25:14.600", "Id": "533558", "Score": "0", "body": "Thanks. For your question if it is mutable or not, well, I just started learning OOP in python. the exercise just tells me to create a class Scholar and compute the yearly income which include bonus. so the answer would be.. not concerned!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T23:54:25.287", "Id": "270238", "ParentId": "270222", "Score": "1" } } ]
{ "AcceptedAnswerId": "270224", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T12:41:45.070", "Id": "270222", "Score": "2", "Tags": [ "python", "object-oriented", "constructor" ], "Title": "Setting instance variable for salary bonus based on academic position" }
270222
<p>I decided to implement a solver for linear systems of equations based on the gaussian elimination and reduction to upper triangular form. The gaussian elimination is quite simple to implement but the function to go from a &quot;gauss-eliminated&quot; matrix (upper triangular form) to a solution is excessively complicated in my opinion (<code>solve_given_augmented_gauss_eliminated</code>), I am interested in both improving the readability of this function and in improving the performance that as of now is about 100x times slower than the <code>np.linalg</code> implementation. Probably trying to avoid pure python for loops and using vectorialized operations would improve performance but I am not sure how to proceed.</p> <pre><code>import numpy as np import doctest import time def gauss_elimination(matrix): &quot;&quot;&quot; Performs gaussian elimination. Example from: http://sites.science.oregonstate.edu/math/home/programs/undergrad/CalculusQuestStudyGuides/vcalc/gauss/gauss.html &gt;&gt;&gt; gauss_elimination(np.array([[1,-3,1,4],\ [2,-8,8,-2],\ [-6,3,-15,9]], dtype=float)) array([[ 1., -3., 1., 4.], [ 0., -2., 6., -10.], [ 0., 0., -54., 108.]]) &quot;&quot;&quot; for i in range(len(matrix)): for j in range(i): weight_j = matrix[i][j] / matrix[j][j] matrix[i] -= (matrix[j] * weight_j) return matrix def solve_given_augmented_gauss_eliminated(gauss_eliminated): &quot;&quot;&quot; The augmented matrix is the matrix of the coefficients of the system with the known terms vector added to the right, for example: 1x + 0y = 1 1x + 1y = 3 is represented by: &gt;&gt;&gt; m = np.array([[1, 0, 1],\ [1, 1, 3]], dtype=float) The gaussian eliminated form is upper triangular and is: 1x + 0y = 1 0x + 1y = 2 So &gt;&gt;&gt; m = np.array([[1, 0, 1],\ [0, 1, 2]], dtype=float) &gt;&gt;&gt; solve_given_augmented_gauss_eliminated(m.copy()) array([1., 2.]) &quot;&quot;&quot; row_len = len(gauss_eliminated[0]) # start with ones, so unknown variables make no difference when multiplied values = np.ones(len(gauss_eliminated)) for i in range(len(gauss_eliminated)-1, -1, -1): # substitute the values of the known variables gauss_eliminated[i][:len(values)] = gauss_eliminated[i][:len(values)] * values # the numerator is the element on the left minus the sum of the elements on the right numerator = gauss_eliminated[i][row_len-1] - sum(gauss_eliminated[i][i+1:row_len-1]) # determine the value of the i-th element of the solution vector values[i] = numerator / gauss_eliminated[i][i] return values def check_solution(aug_gauss_eliminated, sol): &quot;&quot;&quot; &gt;&gt;&gt; m = np.array([[1, 0, 1],\ [1, 1, 3]], dtype=float) &gt;&gt;&gt; check_solution(m, np.array([1,2])) True &quot;&quot;&quot; return all( (sum(row[:len(sol)] * sol) == row[-1]) for row in aug_gauss_eliminated) def solve(aug_matrix): &quot;&quot;&quot; Example from https://www.cliffsnotes.com/study-guides/algebra/linear-algebra/linear-systems/gaussian-elimination examples 1 and 3 Be careful, the input matrix will be changed in a weird way, use .copy() to be safe. &gt;&gt;&gt; m1 = np.array([[1, 1, 3],\ [3, -2, 4]], dtype=float) &gt;&gt;&gt; solve(m1.copy()) array([2., 1.]) &gt;&gt;&gt; check_solution(m1, _) True &gt;&gt;&gt; m3 = np.array([[1, -2, 1, 0],\ [2, 1, -3, 5],\ [4, -7, 1, -1]], dtype=float) &gt;&gt;&gt; solve(m3.copy()) array([3., 2., 1.]) &gt;&gt;&gt; check_solution(m3, _) True &quot;&quot;&quot; gauss_eliminated = gauss_elimination(aug_matrix) return solve_given_augmented_gauss_eliminated(gauss_eliminated) if __name__ == &quot;__main__&quot;: doctest.testmod() for size in [10, 100, 200, 500, 1000]: coefficients = np.random.rand(size, size) known = np.random.rand(size) random_system = np.hstack((coefficients,known.reshape(size,1))) start = time.time() sol1 = solve(random_system) print(&quot;Size: &quot;, size) print(time.time() - start) start = time.time() sol2 = np.linalg.solve(coefficients, known) print(time.time() - start) # Final check, does my code give the same result as numpy? print(np.allclose(sol1, sol2)) print() </code></pre> <p>I also run the cProfile utility on my code finding out that the <code>gauss_elimination</code> is taking the longest time because it is a quadratic algorithm while <code>solve_given_augmented_gauss_eliminated</code> is linear, if my big O analysis is correct.</p> <pre><code>$&gt;python -m cProfile -s tottime gauss_elim.py Size: 10 0.0005228519439697266 0.0 True Size: 100 0.012234210968017578 0.0023505687713623047 True Size: 200 0.052938222885131836 0.003468036651611328 True Size: 500 0.3867616653442383 0.00789952278137207 True Size: 1000 1.7185072898864746 0.015315055847167969 True 127075 function calls (124279 primitive calls) in 2.382 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 5 2.113 0.423 2.113 0.423 gauss_elim.py:5(gauss_elimination) 1810 0.051 0.000 0.051 0.000 {built-in method builtins.sum} 5 0.028 0.006 0.029 0.006 linalg.py:313(solve) 788 0.028 0.000 0.028 0.000 {built-in method nt.stat} 18 0.013 0.001 0.015 0.001 {built-in method _imp.create_dynamic} 316 0.013 0.000 0.013 0.000 {built-in method builtins.compile} 131 0.011 0.000 0.011 0.000 {built-in method marshal.loads} 10 0.009 0.001 0.009 0.001 {method 'rand' of 'numpy.random.mtrand.RandomState' objects} 2111 0.009 0.000 0.014 0.000 &lt;frozen importlib._bootstrap_external&gt;:91(_path_join) 181 0.007 0.000 0.007 0.000 {built-in method io.open_code} 181 0.007 0.000 0.007 0.000 {method 'read' of '_io.BufferedReader' objects} 5 0.006 0.001 0.057 0.011 gauss_elim.py:22(solve_given_augmented_gauss_eliminated) 1 0.004 0.004 0.004 0.004 {method 'read' of '_io.TextIOWrapper' objects} 318/315 0.004 0.000 0.008 0.000 {built-in method builtins.__build_class__} 57/22 0.003 0.000 0.032 0.001 {built-in method numpy.core._multiarray_umath.implement_array_function} 1 0.003 0.003 0.003 0.003 {built-in method _winapi.CreateProcess} 433 0.003 0.000 0.039 0.000 &lt;frozen importlib._bootstrap_external&gt;:1505(find_spec) 25 0.002 0.000 0.002 0.000 {built-in method builtins.print} 130/43 0.002 0.000 0.005 0.000 sre_parse.py:493(_parse) 18/13 0.001 0.000 0.012 0.001 {built-in method _imp.exec_dynamic} 182 0.001 0.000 0.001 0.000 {method '__exit__' of '_io._IOBase' objects} 131 0.001 0.000 0.035 0.000 &lt;frozen importlib._bootstrap_external&gt;:916(get_code) 13378/13119 0.001 0.000 0.001 0.000 {built-in method builtins.len} 4345 0.001 0.000 0.001 0.000 {built-in method builtins.getattr} 7061 0.001 0.000 0.001 0.000 {method 'endswith' of 'str' objects} 185/17 0.001 0.000 0.165 0.010 &lt;frozen importlib._bootstrap&gt;:1002(_find_and_load) 2111 0.001 0.000 0.001 0.000 &lt;frozen importlib._bootstrap_external&gt;:114(&lt;listcomp&gt;) 612 0.001 0.000 0.001 0.000 _inspect.py:65(getargs) 240/41 0.001 0.000 0.003 0.000 sre_compile.py:71(_compile) 500 0.001 0.000 0.002 0.000 &lt;frozen importlib._bootstrap&gt;:166(_get_module_lock) 5361 0.001 0.000 0.001 0.000 {method 'startswith' of 'str' objects} 8571 0.001 0.000 0.001 0.000 {built-in method builtins.isinstance} 182 0.001 0.000 0.044 0.000 &lt;frozen importlib._bootstrap&gt;:901(_find_spec) 169 0.001 0.000 0.042 0.000 &lt;frozen importlib._bootstrap_external&gt;:1374(_get_spec) 14 0.001 0.000 0.001 0.000 {built-in method nt.listdir} 334 0.001 0.000 0.001 0.000 functools.py:35(update_wrapper) 6614 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects} 262 0.001 0.000 0.004 0.000 &lt;frozen importlib._bootstrap_external&gt;:361(cache_from_source) 286 0.001 0.000 0.003 0.000 overrides.py:89(verify_matching_signatures) 32 0.001 0.000 0.001 0.000 {built-in method io.open} 883 0.001 0.000 0.001 0.000 {method 'format' of 'str' objects} 500 0.001 0.000 0.001 0.000 &lt;frozen importlib._bootstrap&gt;:87(acquire) 6599 0.001 0.000 0.001 0.000 {method 'rstrip' of 'str' objects} 2570/2499 0.001 0.000 0.016 0.000 {method 'join' of 'str' objects} 316 0.001 0.000 0.020 0.000 overrides.py:183(decorator) 162/2 0.001 0.000 0.155 0.077 &lt;frozen importlib._bootstrap&gt;:659(_load_unlocked) 1026 0.001 0.000 0.001 0.000 {method 'match' of 're.Pattern' objects} 14 0.001 0.000 0.285 0.020 __init__.py:1(&lt;module&gt;) 500 0.001 0.000 0.001 0.000 &lt;frozen importlib._bootstrap&gt;:112(release) 448/1 0.001 0.000 2.383 2.383 {built-in method builtins.exec} 686 0.001 0.000 0.001 0.000 {built-in method __new__ of type object at 0x00007FFCBD32CC60} 616 0.001 0.000 0.002 0.000 _inspect.py:96(getargspec) 92 0.001 0.000 0.001 0.000 sre_compile.py:276(_optimize_charset) 2 0.001 0.000 0.001 0.000 {built-in method _ctypes.LoadLibrary} 2334 0.001 0.000 0.001 0.000 sre_parse.py:233(__next) 28 0.001 0.000 0.001 0.000 inspect.py:626(cleandoc) 162 0.001 0.000 0.004 0.000 &lt;frozen importlib._bootstrap&gt;:486(_init_module_attrs) 181 0.001 0.000 0.015 0.000 &lt;frozen importlib._bootstrap_external&gt;:1036(get_data) 185/17 0.000 0.000 0.165 0.010 &lt;frozen importlib._bootstrap&gt;:967(_find_and_load_unlocked) 50 0.000 0.000 0.000 0.000 {built-in method _imp.source_hash} 2253 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:231(_verbose_message) 1729 0.000 0.000 0.001 0.000 sre_parse.py:164(__getitem__) 1925 0.000 0.000 0.000 0.000 {built-in method builtins.hasattr} 131/2 0.000 0.000 0.155 0.077 &lt;frozen importlib._bootstrap_external&gt;:844(exec_module) 1982 0.000 0.000 0.001 0.000 sre_parse.py:254(get) 1 0.000 0.000 0.000 0.000 {built-in method _winapi.WaitForSingleObject} 10 0.000 0.000 0.000 0.000 {built-in method builtins.eval} 290/98 0.000 0.000 0.000 0.000 sre_parse.py:174(getwidth) 1 0.000 0.000 2.383 2.383 gauss_elim.py:1(&lt;module&gt;) 769 0.000 0.000 0.028 0.000 &lt;frozen importlib._bootstrap_external&gt;:135(_path_stat) 371 0.000 0.000 0.000 0.000 {built-in method _thread.allocate_lock} 193/25 0.000 0.000 0.130 0.005 &lt;frozen importlib._bootstrap&gt;:1033(_handle_fromlist) 284 0.000 0.000 0.002 0.000 function_base.py:475(add_newdoc) 177 0.000 0.000 0.010 0.000 re.py:289(_compile) 13 0.000 0.000 0.000 0.000 {built-in method _imp.create_builtin} 1246 0.000 0.000 0.000 0.000 {method 'rpartition' of 'str' objects} 149 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:696(spec_from_file_location) 10 0.000 0.000 0.001 0.000 __init__.py:345(namedtuple) 336/11 0.000 0.000 0.130 0.012 {built-in method builtins.__import__} 119/41 0.000 0.000 0.005 0.000 sre_parse.py:435(_parse_sub) 262 0.000 0.000 0.001 0.000 &lt;frozen importlib._bootstrap_external&gt;:127(_path_split) 1798 0.000 0.000 0.000 0.000 {built-in method builtins.setattr} 162/159 0.000 0.000 0.020 0.000 &lt;frozen importlib._bootstrap&gt;:558(module_from_spec) 433 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:64(_relax_case) 315 0.000 0.000 0.001 0.000 &lt;frozen importlib._bootstrap&gt;:203(_lock_unlock_module) 279 0.000 0.000 0.001 0.000 {built-in method builtins.max} 131 0.000 0.000 0.011 0.000 &lt;frozen importlib._bootstrap_external&gt;:645(_compile_bytecode) 495 0.000 0.000 0.002 0.000 &lt;frozen importlib._bootstrap_external&gt;:1337(_path_importer_cache) 14 0.000 0.000 0.001 0.000 &lt;frozen importlib._bootstrap_external&gt;:1556(_fill_cache) 184 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:185(cb) 131 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:560(_classify_pyc) 786 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:129(&lt;genexpr&gt;) 6 0.000 0.000 0.001 0.000 enum.py:179(__new__) 1 0.000 0.000 0.002 0.002 core.py:1(&lt;module&gt;) 191 0.000 0.000 0.007 0.000 &lt;frozen importlib._bootstrap_external&gt;:145(_path_is_mode_type) 1206 0.000 0.000 0.000 0.000 {built-in method builtins.min} 149 0.000 0.000 0.001 0.000 &lt;frozen importlib._bootstrap_external&gt;:1500(_get_spec) 378 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:398(parent) 15 0.000 0.000 0.001 0.000 doctest.py:1074(_find_lineno) 293 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:79(_unpack_uint32) 616 0.000 0.000 0.000 0.000 _inspect.py:13(ismethod) 149 0.000 0.000 0.003 0.000 &lt;frozen importlib._bootstrap_external&gt;:491(_get_cached) 184 0.000 0.000 0.001 0.000 &lt;frozen importlib._bootstrap&gt;:58(__init__) 41 0.000 0.000 0.009 0.000 sre_compile.py:759(compile) 280 0.000 0.000 0.003 0.000 &lt;frozen importlib._bootstrap&gt;:385(cached) 545 0.000 0.000 0.000 0.000 sre_parse.py:172(append) 343 0.000 0.000 0.000 0.000 {method 'strip' of 'str' objects} 52 0.000 0.000 0.000 0.000 core.py:889(__init__) 1204 0.000 0.000 0.000 0.000 {built-in method _imp.acquire_lock} 185 0.000 0.000 0.002 0.000 &lt;frozen importlib._bootstrap&gt;:156(__enter__) 23 0.000 0.000 0.000 0.000 {built-in method _abc._abc_init} 332 0.000 0.000 0.000 0.000 functools.py:65(wraps) 520 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:878(__exit__) 41 0.000 0.000 0.001 0.000 sre_compile.py:536(_compile_info) 520 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:874(__enter__) 245/2 0.000 0.000 0.154 0.077 &lt;frozen importlib._bootstrap&gt;:220(_call_with_frames_removed) 1002 0.000 0.000 0.000 0.000 {method '__exit__' of '_thread.lock' objects} 2 0.000 0.000 0.000 0.000 {built-in method sys.getwindowsversion} 1 0.000 0.000 0.008 0.008 numeric.py:1(&lt;module&gt;) 1204 0.000 0.000 0.000 0.000 {built-in method _imp.release_lock} 169 0.000 0.000 0.042 0.000 &lt;frozen importlib._bootstrap_external&gt;:1406(find_spec) 131 0.000 0.000 0.000 0.000 {built-in method _imp._fix_co_filename} 1 0.000 0.000 0.013 0.013 multiarray.py:1(&lt;module&gt;) 851 0.000 0.000 0.000 0.000 {method 'get' of 'dict' objects} 524 0.000 0.000 0.000 0.000 {method 'rfind' of 'str' objects} 612 0.000 0.000 0.000 0.000 _inspect.py:41(iscode) 616 0.000 0.000 0.000 0.000 _inspect.py:26(isfunction) 1016 0.000 0.000 0.000 0.000 {built-in method _thread.get_ident} 6 0.000 0.000 0.001 0.000 enum.py:545(&lt;listcomp&gt;) 15 0.000 0.000 0.010 0.001 pdb.py:142(__init__) 131 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:523(_check_name_wrapper) 15 0.000 0.000 0.011 0.001 doctest.py:1423(run) 92 0.000 0.000 0.000 0.000 sre_compile.py:249(_compile_charset) 626 0.000 0.000 0.000 0.000 sre_parse.py:249(match) 106 0.000 0.000 0.000 0.000 {built-in method numpy.array} 131 0.000 0.000 0.005 0.000 &lt;frozen importlib._bootstrap_external&gt;:1077(path_stats) 41 0.000 0.000 0.005 0.000 sre_parse.py:937(parse) 284 0.000 0.000 0.000 0.000 function_base.py:443(_needs_add_docstring) 1 0.000 0.000 0.001 0.001 getlimits.py:94(_register_known_types) 522 0.000 0.000 0.000 0.000 sre_parse.py:160(__len__) 40 0.000 0.000 0.000 0.000 _inspect.py:140(formatargspec) 284 0.000 0.000 0.000 0.000 function_base.py:461(_add_docstring) 177 0.000 0.000 0.007 0.000 &lt;frozen importlib._bootstrap_external&gt;:154(_path_isfile) 381 0.000 0.000 0.000 0.000 sre_parse.py:286(tell) 63 0.000 0.000 0.000 0.000 sre_parse.py:432(_uniq) 182 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:351(__init__) 309 0.000 0.000 0.000 0.000 {built-in method numpy.core._multiarray_umath.add_docstring} 2 0.000 0.000 0.003 0.001 function_base.py:1(&lt;module&gt;) 529 0.000 0.000 0.000 0.000 {method 'lower' of 'str' objects} 6 0.000 0.000 0.000 0.000 getlimits.py:35(__init__) 75 0.000 0.000 0.000 0.000 {built-in method _imp.is_builtin} 131 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:35(_new_module) 364 0.000 0.000 0.000 0.000 {method 'update' of 'dict' objects} 53 0.000 0.000 0.000 0.000 enum.py:88(__setitem__) 316 0.000 0.000 0.000 0.000 overrides.py:141(array_function_dispatch) 879 0.000 0.000 0.000 0.000 {method 'lstrip' of 'str' objects} 6 0.000 0.000 0.000 0.000 enum.py:221(&lt;setcomp&gt;) 185 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:160(__exit__) 83 0.000 0.000 0.000 0.000 enum.py:462(__setattr__) 1 0.000 0.000 0.002 0.002 _add_newdocs.py:1(&lt;module&gt;) 169 0.000 0.000 0.000 0.000 {built-in method _imp.is_frozen} 5 0.000 0.000 0.000 0.000 numeric.py:2257(isclose) 1 0.000 0.000 0.003 0.003 defchararray.py:1(&lt;module&gt;) 86 0.000 0.000 0.000 0.000 sre_parse.py:355(_escape) 5 0.000 0.000 0.000 0.000 numeric.py:2337(within_tol) 41 0.000 0.000 0.000 0.000 enum.py:977(__and__) 24 0.000 0.000 0.015 0.001 _add_newdocs_scalars.py:55(add_newdoc_for_scalar_type) 118 0.000 0.000 0.000 0.000 sre_compile.py:423(_simple) 15/1 0.000 0.000 0.002 0.002 doctest.py:975(_find) 1 0.000 0.000 0.000 0.000 core.py:2706(MaskedArray) 104 0.000 0.000 0.001 0.000 enum.py:358(__call__) 81 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:593(_validate_timestamp_pyc) 294 0.000 0.000 0.000 0.000 {built-in method from_bytes} 52/36 0.000 0.000 0.000 0.000 sre_compile.py:461(_get_literal_prefix) 1 0.000 0.000 0.000 0.000 {function SeedSequence.generate_state at 0x0000019E2E6AFCA0} 256 0.000 0.000 0.000 0.000 sre_parse.py:111(__init__) 151 0.000 0.000 0.000 0.000 {built-in method builtins.issubclass} 1 0.000 0.000 0.000 0.000 threading.py:1(&lt;module&gt;) 43 0.000 0.000 0.000 0.000 {method 'expandtabs' of 'str' objects} 865 0.000 0.000 0.000 0.000 {method 'isupper' of 'str' objects} 1 0.000 0.000 0.005 0.005 socket.py:4(&lt;module&gt;) 63 0.000 0.000 0.000 0.000 {built-in method fromkeys} 2 0.000 0.000 0.002 0.001 polynomial.py:1(&lt;module&gt;) 15 0.000 0.000 0.000 0.000 {method 'reduce' of 'numpy.ufunc' objects} 1 0.000 0.000 0.000 0.000 decoder.py:254(JSONDecoder) 12 0.000 0.000 0.000 0.000 datetime.py:492(__new__) 1 0.000 0.000 0.003 0.003 fromnumeric.py:1(&lt;module&gt;) 2 0.000 0.000 0.000 0.000 {built-in method nt.putenv} 6 0.000 0.000 0.002 0.000 enum.py:528(_convert_) 42 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects} 185 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:152(__init__) 92 0.000 0.000 0.000 0.000 {method 'replace' of 'str' objects} 1 0.000 0.000 0.002 0.002 numerictypes.py:1(&lt;module&gt;) 14 0.000 0.000 0.000 0.000 {method 'split' of 're.Pattern' objects} 41 0.000 0.000 0.003 0.000 sre_compile.py:598(_code) 6 0.000 0.000 0.000 0.000 numeric.py:2514(extend_all) 268 0.000 0.000 0.000 0.000 {method 'find' of 'bytearray' objects} 106 0.000 0.000 0.000 0.000 {method 'extend' of 'list' objects} 209 0.000 0.000 0.000 0.000 socket.py:88(&lt;lambda&gt;) 450 0.000 0.000 0.000 0.000 {built-in method nt.fspath} 14 0.000 0.000 0.000 0.000 hashlib.py:126(__get_openssl_constructor) 18 0.000 0.000 0.000 0.000 sre_compile.py:413(&lt;listcomp&gt;) 57 0.000 0.000 0.000 0.000 sre_parse.py:84(opengroup) 30 0.000 0.000 0.000 0.000 getlimits.py:41(&lt;lambda&gt;) 2 0.000 0.000 0.005 0.003 shape_base.py:1(&lt;module&gt;) 182 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:736(find_spec) 32 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:167(_path_isabs) 14 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:1585(&lt;setcomp&gt;) 169 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:811(find_spec) 1 0.000 0.000 0.005 0.005 linalg.py:1(&lt;module&gt;) 1 0.000 0.000 0.002 0.002 scimath.py:1(&lt;module&gt;) 62 0.000 0.000 0.000 0.000 {built-in method nt.getcwd} 107 0.000 0.000 0.000 0.000 re.py:188(match) 14 0.000 0.000 0.001 0.000 &lt;frozen zipimport&gt;:63(__init__) 1 0.000 0.000 0.000 0.000 ctypeslib.py:365(&lt;dictcomp&gt;) 50 0.000 0.000 0.000 0.000 _internal.py:815(_ufunc_doc_signature_formatter) 14 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:1466(__init__) 1 0.000 0.000 0.000 0.000 laguerre.py:1(&lt;module&gt;) 1 0.000 0.000 0.006 0.006 pdb.py:3(&lt;module&gt;) 20 0.000 0.000 0.000 0.000 {method 'findall' of 're.Pattern' objects} 15 0.000 0.000 0.000 0.000 ntpath.py:289(expanduser) 1 0.000 0.000 0.002 0.002 npyio.py:1(&lt;module&gt;) 14 0.000 0.000 0.000 0.000 mixins.py:26(_reflected_binary_method) 41 0.000 0.000 0.000 0.000 sre_parse.py:224(__init__) 15 0.000 0.000 0.000 0.000 doctest.py:183(_extract_future_flags) 1 0.000 0.000 0.000 0.000 {built-in method nt._add_dll_directory} 14 0.000 0.000 0.001 0.000 &lt;frozen importlib._bootstrap_external&gt;:1324(_path_hooks) 131 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:1006(__init__) 210 0.000 0.000 0.000 0.000 socket.py:93(&lt;lambda&gt;) 1 0.000 0.000 0.001 0.001 nanfunctions.py:1(&lt;module&gt;) 15 0.000 0.000 0.000 0.000 doctest.py:1277(__run) 207 0.000 0.000 0.000 0.000 socket.py:78(&lt;lambda&gt;) 208 0.000 0.000 0.000 0.000 socket.py:83(&lt;lambda&gt;) 98 0.000 0.000 0.000 0.000 enum.py:670(__new__) 1 0.000 0.000 0.002 0.002 hmac.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 stride_tricks.py:1(&lt;module&gt;) 18 0.000 0.000 0.015 0.001 &lt;frozen importlib._bootstrap_external&gt;:1171(create_module) 345 0.000 0.000 0.000 0.000 {method 'add' of 'set' objects} 1 0.000 0.000 0.001 0.001 datetime.py:1(&lt;module&gt;) 1 0.000 0.000 0.011 0.011 index_tricks.py:1(&lt;module&gt;) 18 0.000 0.000 0.000 0.000 _ufunc_config.py:32(seterr) 1 0.000 0.000 0.004 0.004 subprocess.py:10(&lt;module&gt;) 178 0.000 0.000 0.000 0.000 {method 'pop' of 'dict' objects} 1 0.000 0.000 0.000 0.000 subprocess.py:700(Popen) 41 0.000 0.000 0.000 0.000 {built-in method _sre.compile} 13 0.000 0.000 0.000 0.000 {built-in method _imp.exec_builtin} 37 0.000 0.000 0.000 0.000 os.py:674(__getitem__) 41 0.000 0.000 0.000 0.000 os.py:746(encodekey) 1 0.000 0.000 0.000 0.000 result.py:24(TestResult) 1 0.000 0.000 0.000 0.000 _compat_pickle.py:9(&lt;module&gt;) 1 0.000 0.000 0.001 0.001 _type_aliases.py:1(&lt;module&gt;) 32 0.000 0.000 0.000 0.000 {built-in method nt._path_splitroot} 14 0.000 0.000 0.001 0.000 core.py:116(doc_note) 197 0.000 0.000 0.000 0.000 sre_parse.py:81(groups) 18 0.000 0.000 0.000 0.000 sre_compile.py:411(_mk_bitmap) 6 0.000 0.000 0.001 0.000 enum.py:475(_create_) 1 0.000 0.000 0.001 0.001 extras.py:1(&lt;module&gt;) 449 0.000 0.000 0.000 0.000 {built-in method builtins.ord} 1 0.000 0.000 0.000 0.000 arrayprint.py:1(&lt;module&gt;) 15 0.000 0.000 0.000 0.000 arrayprint.py:1527(_guarded_repr_or_str) 265 0.000 0.000 0.000 0.000 {method 'partition' of 'str' objects} 15 0.000 0.000 0.001 0.000 linecache.py:52(checkcache) 1 0.000 0.000 0.004 0.004 subprocess.py:1334(_execute_child) 1 0.000 0.000 0.002 0.002 twodim_base.py:1(&lt;module&gt;) 15 0.000 0.000 0.000 0.000 doctest.py:627(parse) 44 0.000 0.000 0.000 0.000 core.py:132(get_object_signature) 1 0.000 0.000 0.000 0.000 _string_helpers.py:9(&lt;listcomp&gt;) 1 0.000 0.000 0.002 0.002 pickle.py:1(&lt;module&gt;) 15 0.000 0.000 0.000 0.000 fromnumeric.py:69(_wrapreduction) 3 0.000 0.000 0.000 0.000 enum.py:1017(_decompose) 1 0.000 0.000 0.004 0.004 subprocess.py:756(__init__) 1 0.000 0.000 0.018 0.018 doctest.py:9(&lt;module&gt;) 41 0.000 0.000 0.000 0.000 sre_parse.py:76(__init__) 1 0.000 0.000 0.001 0.001 random.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 {built-in method winreg.OpenKeyEx} 40 0.000 0.000 0.000 0.000 sre_parse.py:295(_class_escape) 26 0.000 0.000 0.000 0.000 core.py:6755(getdoc) 15 0.000 0.000 0.001 0.000 bdb.py:54(reset) 18 0.000 0.000 0.000 0.000 _ufunc_config.py:131(geterr) 30 0.000 0.000 0.000 0.000 inspect.py:295(isroutine) 30 0.000 0.000 0.000 0.000 sre_compile.py:492(_get_charset_prefix) 1 0.000 0.000 0.000 0.000 {method 'readlines' of '_io._IOBase' objects} 1 0.000 0.000 0.000 0.000 subprocess.py:1207(_close_pipe_fds) 53 0.000 0.000 0.000 0.000 enum.py:44(_is_private) 1 0.000 0.000 0.001 0.001 parse.py:1(&lt;module&gt;) 10 0.000 0.000 0.000 0.000 {method 'sub' of 're.Pattern' objects} 1 0.000 0.000 0.002 0.002 pathlib.py:1(&lt;module&gt;) 18 0.000 0.000 0.000 0.000 enum.py:582(_find_data_type) 1 0.000 0.000 0.001 0.001 type_check.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 umath.py:1(&lt;module&gt;) 22/12 0.000 0.000 0.000 0.000 {built-in method _abc._abc_subclasscheck} 60 0.000 0.000 0.000 0.000 {method 'copy' of 'numpy.ndarray' objects} 16 0.000 0.000 0.000 0.000 _type_aliases.py:58(bitname) 123 0.000 0.000 0.000 0.000 sre_parse.py:168(__setitem__) 41 0.000 0.000 0.000 0.000 sre_parse.py:921(fix_flags) 1 0.000 0.000 0.002 0.002 _pocketfft.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 encoder.py:1(&lt;module&gt;) 18 0.000 0.000 0.000 0.000 sre_parse.py:267(getuntil) 13 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:757(create_module) 39 0.000 0.000 0.015 0.000 _add_newdocs_scalars.py:62(&lt;genexpr&gt;) 23 0.000 0.000 0.000 0.000 abc.py:105(__new__) 82 0.000 0.000 0.000 0.000 sre_compile.py:595(isstring) 371 0.000 0.000 0.000 0.000 {built-in method builtins.globals} 106 0.000 0.000 0.000 0.000 {built-in method builtins.abs} 51 0.000 0.000 0.009 0.000 re.py:250(compile) 13 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:415(spec_from_loader) 1 0.000 0.000 0.000 0.000 pickle.py:197(&lt;listcomp&gt;) 90 0.000 0.000 0.000 0.000 sre_compile.py:65(_combine_flags) 1 0.000 0.000 0.000 0.000 chebyshev.py:1(&lt;module&gt;) 57 0.000 0.000 0.000 0.000 sre_parse.py:96(closegroup) 1 0.000 0.000 0.000 0.000 {built-in method nt.scandir} 10 0.000 0.000 0.000 0.000 {method 'sort' of 'list' objects} 5 0.000 0.000 0.000 0.000 linalg.py:135(_commonType) 14 0.000 0.000 0.001 0.000 &lt;frozen importlib._bootstrap_external&gt;:1597(path_hook_for_FileFinder) 2 0.000 0.000 0.000 0.000 {built-in method builtins.dir} 43 0.000 0.000 0.000 0.000 os.py:740(check_str) 90 0.000 0.000 0.000 0.000 _inspect.py:131(strseq) 1 0.000 0.000 0.001 0.001 _methods.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 _type_aliases.py:94(_add_aliases) 18/13 0.000 0.000 0.012 0.001 &lt;frozen importlib._bootstrap_external&gt;:1179(exec_module) 50 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:621(_validate_hash_pyc) 1 0.000 0.000 0.000 0.000 getlimits.py:1(&lt;module&gt;) 5 0.000 0.000 0.029 0.006 &lt;__array_function__ internals&gt;:2(solve) 15 0.000 0.000 0.001 0.000 doctest.py:1036(_get_test) 46 0.000 0.000 0.000 0.000 types.py:171(__get__) 2 0.000 0.000 0.000 0.000 {built-in method nt.unsetenv} 15 0.000 0.000 0.000 0.000 arrayprint.py:468(wrapper) 162 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:406(has_location) 1 0.000 0.000 0.024 0.024 _add_newdocs_scalars.py:1(&lt;module&gt;) 1 0.000 0.000 0.002 0.002 decoder.py:1(&lt;module&gt;) 1 0.000 0.000 0.005 0.005 subprocess.py:1090(communicate) 1 0.000 0.000 0.000 0.000 base64.py:3(&lt;module&gt;) 19 0.000 0.000 0.000 0.000 {built-in method numpy.seterrobj} 2 0.000 0.000 0.000 0.000 {built-in method _ctypes.POINTER} 4 0.000 0.000 0.000 0.000 contextlib.py:452(callback) 1 0.000 0.000 0.001 0.001 _internal.py:1(&lt;module&gt;) 257 0.000 0.000 0.000 0.000 hmac.py:18(&lt;genexpr&gt;) 1 0.000 0.000 0.000 0.000 {built-in method _socket.gethostname} 13 0.000 0.000 0.000 0.000 ntpath.py:124(splitdrive) 1 0.000 0.000 0.007 0.007 platform.py:3(&lt;module&gt;) 41 0.000 0.000 0.000 0.000 doctest.py:568(__lt__) 15 0.000 0.000 0.000 0.000 fromnumeric.py:2367(all) 1 0.000 0.000 0.015 0.015 _pickle.py:1(&lt;module&gt;) 1 0.000 0.000 0.013 0.013 doctest.py:1862(testmod) 26 0.000 0.000 0.000 0.000 core.py:916(__init__) 75 0.000 0.000 0.000 0.000 overrides.py:122(decorator) 13 0.000 0.000 0.000 0.000 _dtype_ctypes.py:100(dtype_from_ctypes_type) 53 0.000 0.000 0.000 0.000 enum.py:22(_is_dunder) 30 0.000 0.000 0.015 0.000 platform.py:825(uname) 15 0.000 0.000 0.010 0.001 doctest.py:359(__init__) 6 0.000 0.000 0.000 0.000 enum.py:443(__members__) 29 0.000 0.000 0.000 0.000 inspect.py:727(getmodule) 288 0.000 0.000 0.000 0.000 {built-in method builtins.chr} 257 0.000 0.000 0.000 0.000 hmac.py:19(&lt;genexpr&gt;) 2 0.000 0.000 0.000 0.000 glob.py:117(_iterdir) 53 0.000 0.000 0.000 0.000 enum.py:33(_is_sunder) 1 0.000 0.000 0.001 0.001 selectors.py:1(&lt;module&gt;) 1 0.000 0.000 0.007 0.007 py3k.py:1(&lt;module&gt;) 10 0.000 0.000 0.001 0.000 extras.py:239(getdoc) 23 0.000 0.000 0.001 0.000 overrides.py:223(decorator) 30 0.000 0.000 0.000 0.000 getlimits.py:25(_fr1) 1 0.000 0.000 0.000 0.000 threading.py:95(_RLock) 1 0.000 0.000 0.000 0.000 utils.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 {built-in method _winapi.CreatePipe} 6 0.000 0.000 0.000 0.000 enum.py:618(_find_new_) 15 0.000 0.000 0.000 0.000 doctest.py:1402(__record_outcome) 1 0.000 0.000 0.000 0.000 version.py:1(&lt;module&gt;) 1 0.000 0.000 0.001 0.001 signal.py:1(&lt;module&gt;) 7 0.000 0.000 0.000 0.000 getlimits.py:514(__init__) 1 0.000 0.000 0.009 0.009 platform.py:360(win32_ver) 1 0.000 0.000 0.000 0.000 _polybase.py:18(ABCPolyBase) 5 0.000 0.000 0.000 0.000 textwrap.py:414(dedent) 13 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:241(_requires_builtin_wrapper) 15 0.000 0.000 0.001 0.000 pdb.py:196(reset) 14 0.000 0.000 0.000 0.000 __init__.py:142(_check_size) 1 0.000 0.000 0.000 0.000 __init__.py:337(_sanity_check) 1 0.000 0.000 0.011 0.011 overrides.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 _ufunc_config.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 hermite.py:1(&lt;module&gt;) 75 0.000 0.000 0.000 0.000 overrides.py:111(set_module) 1 0.000 0.000 0.001 0.001 arraysetops.py:1(&lt;module&gt;) 59 0.000 0.000 0.000 0.000 _inspect.py:144(&lt;lambda&gt;) 6 0.000 0.000 0.000 0.000 numeric.py:149(ones) 30 0.000 0.000 0.000 0.000 getlimits.py:40(&lt;lambda&gt;) 131 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:1031(get_filename) 8 0.000 0.000 0.000 0.000 enum.py:971(__or__) 82 0.000 0.000 0.000 0.000 sre_compile.py:453(_get_iscased) 13 0.000 0.000 0.000 0.000 {method 'setter' of 'property' objects} 5 0.000 0.000 0.003 0.001 shape_base.py:285(hstack) 3 0.000 0.000 0.000 0.000 enum.py:938(_create_pseudo_member_) 33 0.000 0.000 0.000 0.000 {method 'items' of 'mappingproxy' objects} 131 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:841(create_module) 115 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects} 30 0.000 0.000 0.000 0.000 getlimits.py:17(_fr0) 3 0.000 0.000 0.000 0.000 decoder.py:343(raw_decode) 18 0.000 0.000 0.000 0.000 enum.py:571(_get_mixins_) 1 0.000 0.000 0.008 0.008 _distributor_init.py:2(&lt;module&gt;) 112 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:1472(&lt;genexpr&gt;) 41 0.000 0.000 0.000 0.000 enum.py:12(_is_descriptor) 76 0.000 0.000 0.000 0.000 inspect.py:64(ismodule) 1 0.000 0.000 0.000 0.000 hashlib.py:5(&lt;module&gt;) 2 0.000 0.000 0.000 0.000 core.py:2974(__array_finalize__) 3 0.000 0.000 0.000 0.000 ntpath.py:180(split) 5 0.000 0.000 0.001 0.000 &lt;__array_function__ internals&gt;:2(allclose) 2 0.000 0.000 0.000 0.000 ntpath.py:450(normpath) 1 0.000 0.000 0.000 0.000 case.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 _endian.py:1(&lt;module&gt;) 5 0.000 0.000 2.170 0.434 gauss_elim.py:68(solve) 1 0.000 0.000 0.000 0.000 records.py:1(&lt;module&gt;) 16 0.000 0.000 0.000 0.000 _type_aliases.py:44(_bits_of) 1 0.000 0.000 0.000 0.000 ctypeslib.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 case.py:309(TestCase) 18 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:1155(__init__) 61 0.000 0.000 0.000 0.000 {method 'translate' of 'str' objects} 17 0.000 0.000 0.000 0.000 inspect.py:494(unwrap) 78 0.000 0.000 0.000 0.000 _internal.py:826(&lt;genexpr&gt;) 1 0.000 0.000 0.000 0.000 pprint.py:103(PrettyPrinter) 15 0.000 0.000 0.000 0.000 arrayprint.py:1534(_array_str_implementation) 7 0.000 0.000 0.000 0.000 {method 'remove' of 'list' objects} 18 0.000 0.000 0.000 0.000 core.py:992(__init__) 6 0.000 0.000 0.000 0.000 {built-in method numpy.empty} 15 0.000 0.000 0.000 0.000 &lt;__array_function__ internals&gt;:2(all) 9 0.000 0.000 0.000 0.000 _ufunc_config.py:429(__enter__) 26 0.000 0.000 0.000 0.000 core.py:6750(__init__) 17 0.000 0.000 0.000 0.000 _collections_abc.py:767(__contains__) 6 0.000 0.000 0.000 0.000 &lt;__array_function__ internals&gt;:2(copyto) 17 0.000 0.000 0.000 0.000 inspect.py:91(ismethoddescriptor) 5 0.000 0.000 0.001 0.000 numeric.py:2179(allclose) 1 0.000 0.000 0.009 0.009 subprocess.py:464(run) 6 0.000 0.000 0.000 0.000 enum.py:164(__prepare__) 1 0.000 0.000 0.000 0.000 numerictypes.py:442(_construct_lookups) 8 0.000 0.000 0.000 0.000 core.py:8103(getdoc) 1 0.000 0.000 0.000 0.000 argparse.py:4(&lt;module&gt;) 15 0.000 0.000 0.000 0.000 doctest.py:776(_min_indent) 1 0.000 0.000 0.000 0.000 {built-in method _hashlib.openssl_sha512} 1 0.000 0.000 0.000 0.000 pickle.py:1136(_Unpickler) 15 0.000 0.000 0.000 0.000 doctest.py:666(get_doctest) 1 0.000 0.000 0.000 0.000 fnmatch.py:80(translate) 1 0.000 0.000 0.000 0.000 posixpath.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 pathlib.py:653(PurePath) 15 0.000 0.000 0.000 0.000 doctest.py:528(__init__) 2 0.000 0.000 0.000 0.000 {method 'close' of '_io.TextIOWrapper' objects} 64 0.000 0.000 0.000 0.000 inspect.py:73(isclass) 15 0.000 0.000 0.000 0.000 pdb.py:200(forget) 1 0.000 0.000 0.000 0.000 _type_aliases.py:74(_add_types) 30 0.000 0.000 0.000 0.000 _type_aliases.py:203(_add_array_type) 1 0.000 0.000 0.005 0.005 secrets.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 difflib.py:1(&lt;module&gt;) 52 0.000 0.000 0.000 0.000 _add_newdocs.py:6230(refer_to_array_attribute) 1 0.000 0.000 0.009 0.009 platform.py:261(_syscmd_ver) 144 0.000 0.000 0.000 0.000 {built-in method builtins.id} 31 0.000 0.000 0.000 0.000 signal.py:10(&lt;lambda&gt;) 1 0.000 0.000 0.000 0.000 mixins.py:59(NDArrayOperatorsMixin) 14 0.000 0.000 0.000 0.000 re.py:223(split) 1 0.000 0.000 0.000 0.000 hermite_e.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 core.py:6439(__new__) 1 0.000 0.000 0.000 0.000 legendre.py:1(&lt;module&gt;) 83 0.000 0.000 0.000 0.000 {method 'get' of 'mappingproxy' objects} 4 0.000 0.000 0.000 0.000 ntpath.py:77(join) 50 0.000 0.000 0.000 0.000 {built-in method sys.intern} 1 0.000 0.000 0.000 0.000 __config__.py:3(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 _globals.py:1(&lt;module&gt;) 59 0.000 0.000 0.000 0.000 {built-in method builtins.repr} 24 0.000 0.000 0.000 0.000 numerictypes.py:515(_scalar_type_key) 5 0.000 0.000 0.000 0.000 shape_base.py:23(atleast_1d) 1 0.000 0.000 0.006 0.006 defmatrix.py:1(&lt;module&gt;) 6 0.000 0.000 0.003 0.001 &lt;__array_function__ internals&gt;:2(concatenate) 1 0.000 0.000 0.000 0.000 histograms.py:1(&lt;module&gt;) 15 0.000 0.000 0.000 0.000 doctest.py:678(get_examples) 5 0.000 0.000 0.000 0.000 {method 'astype' of 'numpy.ndarray' objects} 61 0.000 0.000 0.000 0.000 inspect.py:159(isfunction) 49 0.000 0.000 0.000 0.000 _string_helpers.py:16(english_lower) 1 0.000 0.000 0.000 0.000 loader.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 einsumfunc.py:1(&lt;module&gt;) 1 0.000 0.000 0.009 0.009 subprocess.py:377(check_output) 11 0.000 0.000 0.000 0.000 {built-in method _abc._abc_register} 4 0.000 0.000 0.000 0.000 warnings.py:181(_add_filter) 10 0.000 0.000 0.000 0.000 linalg.py:107(_makearray) 1 0.000 0.000 0.000 0.000 _iotools.py:451(StringConverter) 3 0.000 0.000 0.001 0.000 __init__.py:340(__init__) 1 0.000 0.000 0.000 0.000 os.py:48(&lt;listcomp&gt;) 50 0.000 0.000 0.000 0.000 __init__.py:419(&lt;genexpr&gt;) 15 0.000 0.000 0.000 0.000 bdb.py:273(_set_stopinfo) 2 0.000 0.000 0.000 0.000 {built-in method builtins.sorted} 1 0.000 0.000 0.000 0.000 tokenize.py:388(open) 7 0.000 0.000 0.000 0.000 core.py:2553(_arraymethod) 52 0.000 0.000 0.000 0.000 {method 'setdefault' of 'dict' objects} 91 0.000 0.000 0.000 0.000 {built-in method _sre.unicode_iscased} 2 0.000 0.000 0.000 0.000 {method 'readline' of '_io.BufferedReader' objects} 1 0.000 0.000 0.000 0.000 _exceptions.py:1(&lt;module&gt;) 14 0.000 0.000 0.000 0.000 doctest.py:947(_from_module) 68 0.000 0.000 0.000 0.000 {method 'isidentifier' of 'str' objects} 36 0.000 0.000 0.000 0.000 getlimits.py:39(&lt;lambda&gt;) 1 0.000 0.000 0.000 0.000 {method 'dot' of 'numpy.ndarray' objects} 15 0.000 0.000 0.000 0.000 cmd.py:76(__init__) 1 0.000 0.000 0.001 0.001 scanner.py:1(&lt;module&gt;) 13 0.000 0.000 0.000 0.000 _dtype_ctypes.py:71(_from_ctypes_scalar) 1 0.000 0.000 0.000 0.000 helper.py:1(&lt;module&gt;) 3 0.000 0.000 0.000 0.000 decoder.py:332(decode) 32 0.000 0.000 0.000 0.000 _type_aliases.py:46(&lt;genexpr&gt;) 9 0.000 0.000 0.000 0.000 _ufunc_config.py:434(__exit__) 1 0.000 0.000 0.000 0.000 {built-in method _hashlib.openssl_md5} 3 0.000 0.000 0.000 0.000 warnings.py:130(filterwarnings) 1 0.000 0.000 0.000 0.000 _string_helpers.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 _type_aliases.py:130(_add_integer_aliases) 1 0.000 0.000 0.001 0.001 runner.py:1(&lt;module&gt;) 5 0.000 0.000 0.003 0.001 &lt;__array_function__ internals&gt;:2(hstack) 1 0.000 0.000 0.000 0.000 memmap.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 ufunclike.py:1(&lt;module&gt;) 38 0.000 0.000 0.000 0.000 {built-in method numpy.geterrobj} 48 0.000 0.000 0.000 0.000 inspect.py:81(ismethod) 1 0.000 0.000 0.000 0.000 {built-in method nt.open} 13 0.000 0.000 0.000 0.000 mixins.py:44(_numeric_methods) 1 0.000 0.000 0.000 0.000 defchararray.py:1805(chararray) 30 0.000 0.000 0.000 0.000 enum.py:438(&lt;genexpr&gt;) 2 0.000 0.000 0.000 0.000 subprocess.py:1462(_wait) 5 0.000 0.000 0.000 0.000 sre_parse.py:861(_parse_flags) 1 0.000 0.000 0.002 0.002 main.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 pprint.py:11(&lt;module&gt;) 20 0.000 0.000 0.000 0.000 {built-in method time.time} 63 0.000 0.000 0.000 0.000 abc.py:7(abstractmethod) 1 0.000 0.000 0.000 0.000 polynomial.py:1068(poly1d) 1 0.000 0.000 0.000 0.000 arraypad.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 pdb.py:138(Pdb) 33 0.000 0.000 0.000 0.000 {method 'clear' of 'dict' objects} 1 0.000 0.000 0.000 0.000 bdb.py:1(&lt;module&gt;) 14 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap_external&gt;:159(_path_isdir) 1 0.000 0.000 0.000 0.000 contextlib.py:489(__exit__) 6 0.000 0.000 0.000 0.000 sre_compile.py:432(_generate_overlap_table) 1 0.000 0.000 0.000 0.000 _datasource.py:1(&lt;module&gt;) 50 0.000 0.000 0.000 0.000 {method '__contains__' of 'frozenset' objects} 1 0.000 0.000 0.000 0.000 pathlib.py:120(_WindowsFlavour) 1 0.000 0.000 0.000 0.000 subprocess.py:1240(_get_handles) 1 0.000 0.000 0.000 0.000 format.py:1(&lt;module&gt;) 1 0.000 0.000 0.002 0.002 doctest.py:579(DocTestParser) 10 0.000 0.000 0.001 0.000 extras.py:235(__init__) 1 0.000 0.000 0.000 0.000 _globals.py:77(__new__) 1 0.000 0.000 0.001 0.001 fnmatch.py:1(&lt;module&gt;) 5 0.000 0.000 0.000 0.000 &lt;__array_function__ internals&gt;:2(result_type) 5 0.000 0.000 0.000 0.000 &lt;__array_function__ internals&gt;:2(isclose) 1 0.000 0.000 0.000 0.000 _iotools.py:1(&lt;module&gt;) 2 0.000 0.000 0.000 0.000 core.py:2948(_update_from) 1 0.000 0.000 0.001 0.001 string.py:1(&lt;module&gt;) 18 0.000 0.000 0.000 0.000 {method 'translate' of 'bytearray' objects} 2 0.000 0.000 0.000 0.000 genericpath.py:39(isdir) 46 0.000 0.000 0.000 0.000 enum.py:792(value) 1 0.000 0.000 0.000 0.000 numbers.py:32(Complex) 8 0.000 0.000 0.000 0.000 core.py:8098(__init__) 1 0.000 0.000 0.000 0.000 linalg.py:73(_determine_error_states) 4/3 0.000 0.000 0.000 0.000 {method 'view' of 'numpy.ndarray' objects} 25 0.000 0.000 0.000 0.000 {built-in method numpy.asanyarray} 16 0.000 0.000 0.000 0.000 {built-in method builtins.any} 86 0.000 0.000 0.000 0.000 _compat_pickle.py:167(&lt;genexpr&gt;) 1 0.000 0.000 0.000 0.000 random.py:101(Random) 1 0.000 0.000 0.000 0.000 traceback.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 _asarray.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 platform.py:233(_norm_version) 1 0.000 0.000 0.002 0.002 doctest.py:845(find) 1 0.000 0.000 0.000 0.000 util.py:1(&lt;module&gt;) 6 0.000 0.000 0.000 0.000 enum.py:561(_check_for_existing_members) 48 0.000 0.000 0.000 0.000 {method 'pop' of 'list' objects} 13 0.000 0.000 0.000 0.000 &lt;frozen importlib._bootstrap&gt;:765(exec_module) 16 0.000 0.000 0.000 0.000 {method 'copy' of 'dict' objects} 1 0.000 0.000 0.001 0.001 result.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 suite.py:1(&lt;module&gt;) 15 0.000 0.000 0.000 0.000 {method 'finditer' of 're.Pattern' objects} 2 0.000 0.000 0.000 0.000 sre_compile.py:416(_bytes_to_codes) 1 0.000 0.000 0.000 0.000 datetime.py:1245(time) 1 0.000 0.000 0.000 0.000 _type_aliases.py:211(_set_array_types) 1 0.000 0.000 0.000 0.000 {function Random.seed at 0x0000019E2E70E280} 5 0.000 0.000 0.000 0.000 _collections_abc.py:760(get) 1 0.000 0.000 0.000 0.000 datetime.py:1594(datetime) 15 0.000 0.000 0.000 0.000 fromnumeric.py:70(&lt;dictcomp&gt;) 1 0.000 0.000 0.000 0.000 core.py:2817(__new__) 1 0.000 0.000 0.001 0.001 string.py:69(__init_subclass__) 1 0.000 0.000 0.000 0.000 threading.py:795(__init__) 20 0.000 0.000 0.000 0.000 mixins.py:16(_binary_method) 5 0.000 0.000 0.000 0.000 {method 'reshape' of 'numpy.ndarray' objects} 71 0.000 0.000 0.000 0.000 {built-in method _sre.unicode_tolower} 60 0.000 0.000 0.000 0.000 {built-in method builtins.divmod} 1 0.000 0.000 0.000 0.000 cp1252.py:22(decode) 1 0.000 0.000 0.000 0.000 contextlib.py:76(inner) 6 0.000 0.000 0.000 0.000 enum.py:81(__init__) 1 0.000 0.000 0.000 0.000 linecache.py:80(updatecache) 1 0.000 0.000 0.000 0.000 _type_aliases.py:158(_set_up_aliases) 1 0.000 0.000 0.001 0.001 code.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 numbers.py:4(&lt;module&gt;) 17 0.000 0.000 0.000 0.000 &lt;string&gt;:1(&lt;lambda&gt;) 1 0.000 0.000 0.000 0.000 _polybase.py:1(&lt;module&gt;) 18 0.000 0.000 0.000 0.000 ntpath.py:34(_get_bothseps) 2 0.000 0.000 0.000 0.000 functools.py:478(lru_cache) 1 0.000 0.000 0.002 0.002 glob.py:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 struct.py:1(&lt;module&gt;) 16 0.000 0.000 0.000 0.000 _add_newdocs_scalars.py:18(type_aliases_gen) 1 0.000 0.000 0.000 0.000 threading.py:1307(__init__) 6 0.000 0.000 0.000 0.000 enum.py:197(&lt;dictcomp&gt;) 41 0.000 0.000 0.000 0.000 enum.py:551(&lt;lambda&gt;) </code></pre> <p>I cut the output to stay within the characther limit.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:21:44.770", "Id": "270226", "Score": "0", "Tags": [ "python", "performance", "reinventing-the-wheel", "numpy", "linear-algebra" ], "Title": "Solving a linear system with Gaussian Elimination" }
270226
<p>Environnement :</p> <ul> <li>Rails 6.1.4.1</li> <li>db : PostgreSQL</li> </ul> <p>Hi everyone, I've been working on this for some hours now and want to know how other Rails developpers would react to this type of project structure.</p> <p>Goal of the code structure :</p> <ol> <li>Permit API high versionability by : <ul> <li>Removing all logic from models (making them as agnostic to the project state as possible)</li> <li>Segregating logic and validation through individual controller concerns</li> <li>Using helpers to quickly add or remove concerns from a controller</li> </ul> </li> <li>Avoid controller actions code redundancy</li> <li>Make everything reusable and extendable</li> </ol> <p>As an example, for this project the main resource looks like this :</p> <pre class="lang-rb prettyprint-override"><code>class Iban &lt; ApplicationRecord # Logic is fully handled by the controller for higher versionability # - this can still serve if some behaviours must be ensured within any versions end </code></pre> <p>with a migration simply setting :</p> <ul> <li>id:uuid</li> <li>name:string</li> <li>region:string</li> <li>timestamp</li> </ul> <p>So controllers for each api version inherit from the main Api::ApplicationController:</p> <pre class="lang-rb prettyprint-override"><code># app/controllers/api/application_controller.rb module Api class ApplicationController &lt; ::ApplicationController ''' ---------------- ''' ''' STATIC SHORTCUTS ''' ''' ---------------- ''' def model_class self.class.get_model_class end def permitted_params self.class.get_permitted_params end ''' ------- ''' ''' PRIVATE ''' ''' ------- ''' private def set_model @model = model_class.find_by(id: params[:id]) end def model_params params.require(model_class.to_s.downcase.to_sym).permit(*permitted_params) end ''' ------ ''' ''' STATIC ''' ''' ------ ''' class &lt;&lt; self def model_class(klass) # Class shorthand @model_klass = klass end def get_model_class @model_klass end def permitted_params(*params_list) @permitted_params = params_list end def get_permitted_params @permitted_params end # cherry pick action methods def include_common_concerns(*concerns_sym_list) concerns_sym_list.each do |sym| include &quot;Api::Concerns::#{sym}&quot;.constantize end end # cherry pick included concerns with version def include_versioned_concerns(version, *concerns_sym_list) concerns_sym_list.each do |sym| include &quot;Api::V#{version}::Concerns::#{sym}&quot;.constantize end end end end end </code></pre> <p>Base controller actions are stored in concerns within <code>controllers/api/concerns</code>. An example for <code>Indexable</code> :</p> <pre class="lang-rb prettyprint-override"><code>module Api module Concerns module Indexable extend ActiveSupport::Concern def index @models = model_class.all paginate status: 200, json: @models, adapter: :json_api end end end end </code></pre> <p>and <code>Creatable</code>:</p> <pre class="lang-rb prettyprint-override"><code>require 'errors/standard_error' module Api module Concerns module Creatable extend ActiveSupport::Concern def create @model = model_class.new(model_params) if @model.save success_handler(@model, :created) else raise @model.errors end end end end end </code></pre> <p><code>Errors::StandardError</code> is the base error of the app and inherits from Ruby StandardError.</p> <p>An abstract versioned controller looks like this :</p> <pre class="lang-rb prettyprint-override"><code>module Api module V1 class ApplicationController &lt; ::Api::ApplicationController # cf api/v1/concerns include_versioned_concerns 1, *%i[ ResponseHandler ] end end end </code></pre> <p><code>ResponseHandler</code> is segragated per version so :</p> <pre class="lang-rb prettyprint-override"><code>module Api module V1 module Concerns module ResponseHandler extend ActiveSupport::Concern included do rescue_from ::StandardError do | ex | response_handler(ex) end end def response_handler(res) if res.kind_of? ::StandardError error_handler(res) else success_handler(res) end end def error_handler(e) code = (e.status if e.respond_to?(:status)) || 500 message = (e.detail if e.respond_to?(:detail)) || 'Internal Server Error' render status: code, json: { success: false, error: message, code: code } end def success_handler(e, code = 200) render status: code, json: { success: true, data: e } end end end end end </code></pre> <p>and here what looks like an example resource controller :</p> <pre class="lang-rb prettyprint-override"><code>module Api module V1 class IbansController &lt; ApplicationController # Define which model it should handle model_class ::Iban # Define what CRUD actions are present within this controller - cf : controllers/api/concerns include_common_concerns *%i[ Indexable Showable RandomPickable Creatable Updatable Destroyable ] # limits which params are passed for update or create permitted_params *%i[ name region ] # validations are concerns, this way you can cherry pick which to include in other API versions if no changes are needed # - cf : controllers/api/v1/concerns include_versioned_concerns 1, *%i[ IbanValidation RegionValidation ] # Define valid regions valid_regions *%i[ FRANCE UK ] # Handling attribute validation in the controller for better API versionability before_action :validate_mutation_params, only: [:create, :update] private ''' ---------- ''' ''' OVERWRITES ''' ''' ---------- ''' def set_model return if (@model = model_class.find_by(id: params[:id])).present? @model = model_class.find_by(name: params[:id]) end def model_params hash = super hash[:name] = hash[:name].gsub(/\s+/, &quot;&quot;) hash end ''' ----- ''' ''' HOOKS ''' ''' ----- ''' def validate_mutation_params valid_region? valid_iban? end end end end </code></pre> <p>As said before logic is fully delegated within concerns. And <code>IbanValidation</code> and <code>RegionValidation</code> are V1 concerns implementing the <code>valid_&lt;concern&gt;?</code> methods, they raise custom errors or return true.</p> <p>What do you think about this composition and how would you react to it within a professional environment ? Is it something you would avoid at any price, or something you would prefer over common Rails structure ?</p> <p>The main problems I can see are :</p> <ul> <li>structure could put off other developpers - since it's unconventional</li> <li>I don't know hom much the concern inclusion is hitting on performance - I Think this should only slow the app start up but not sure if inclusions are made each time the controllers are called</li> <li>Could derail into composition monster if structure is not strictly applied</li> </ul> <p>But the pros I see are :</p> <ul> <li>Avoid most merging conflicts once structure is in place</li> <li>Quickly evolve from a version to another</li> <li>Permit high scallability from the get go</li> <li>Can ensure code segregation for maintainability if used correctly</li> </ul> <p>So ... is it complete garbage or are there any bit of concept to save within this project ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T03:23:11.113", "Id": "533557", "Score": "0", "body": "I think this would evolve in a big mess if the app anything but trivial and all the meta programming is extremely hard to understand. I don't see much benefit of this design." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:49:22.883", "Id": "270228", "Score": "0", "Tags": [ "ruby-on-rails", "api", "rest" ], "Title": "Highly versionable API" }
270228
<p>I've implemented a thread pool using C++20. I'm fairly new to concurrently/multi-threaded programming and wanted to work on a project that I could learn from while also getting to know some of the new features available in C++20.</p> <p>To that end I've specifically made use of:</p> <ul> <li><code>std::binary_semaphore</code></li> <li><code>concepts</code></li> <li><code>std::jthread</code></li> </ul> <p>I've also made use of some other language features and overall have tried to implement best practices for &quot;modern&quot; C++ standards.</p> <p>The most up to date version of the code is available <a href="https://github.com/DeveloperPaul123/thread-pool" rel="noreferrer">here</a>. The library I created is header only. For brevity, I have omitted all documentation related comments.</p> <h2><code>thread_pool.h</code></h2> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;concepts&gt; #include &lt;functional&gt; #include &lt;future&gt; #include &lt;memory&gt; #include &lt;queue&gt; #include &lt;semaphore&gt; #include &lt;thread&gt; #include &lt;type_traits&gt; #include &quot;thread_pool/thread_safe_queue.h&quot; namespace dp { namespace detail { template &lt;class T&gt; std::decay_t&lt;T&gt; decay_copy(T &amp;&amp;v) { return std::forward&lt;T&gt;(v); } // Bind F and args... into a nullary one-shot lambda. Lambda captures by value. template &lt;typename... Args, typename F&gt; auto bind(F &amp;&amp;f, Args &amp;&amp;...args) { return [f = decay_copy(std::forward&lt;F&gt;(f)), ... args = decay_copy(std::forward&lt;Args&gt;(args))]() mutable -&gt; decltype(auto) { return std::invoke(std::move(f), std::move(args)...); }; } template &lt;class Queue, class U = typename Queue::value_type&gt; concept is_valid_queue = requires(Queue q) { { q.empty() } -&gt; std::convertible_to&lt;bool&gt;; { q.front() } -&gt; std::convertible_to&lt;U &amp;&gt;; { q.back() } -&gt; std::convertible_to&lt;U &amp;&gt;; q.pop(); }; static_assert(detail::is_valid_queue&lt;std::queue&lt;int&gt;&gt;); static_assert(detail::is_valid_queue&lt;dp::thread_safe_queue&lt;int&gt;&gt;); } // namespace detail template &lt;template &lt;class T&gt; class Queue, typename FunctionType = std::function&lt;void()&gt;&gt; requires std::invocable&lt;FunctionType&gt; &amp;&amp; std::is_same_v&lt;void, std::invoke_result_t&lt;FunctionType&gt;&gt; &amp;&amp; detail::is_valid_queue&lt;Queue&lt;FunctionType&gt;&gt; class thread_pool_impl { public: thread_pool_impl( const unsigned int &amp;number_of_threads = std::thread::hardware_concurrency()) { for (std::size_t i = 0; i &lt; number_of_threads; ++i) { queues_.push_back(std::make_unique&lt;task_pair&gt;()); threads_.emplace_back([&amp;, id = i](std::stop_token stop_tok) { do { // check if we have task if (queues_[id]-&gt;tasks.empty()) { // no tasks, so we wait instead of spinning queues_[id]-&gt;semaphore.acquire(); } // ensure we have a task before getting task // since the dtor releases the semaphore as well if (!queues_[id]-&gt;tasks.empty()) { // get the task auto &amp;task = queues_[id]-&gt;tasks.front(); // invoke the task std::invoke(std::move(task)); // remove task from the queue queues_[id]-&gt;tasks.pop(); } } while (!stop_tok.stop_requested()); }); } } ~thread_pool_impl() { // stop all threads for (std::size_t i = 0; i &lt; threads_.size(); ++i) { threads_[i].request_stop(); queues_[i]-&gt;semaphore.release(); threads_[i].join(); } } /// thread pool is non-copyable thread_pool_impl(const thread_pool_impl &amp;) = delete; thread_pool_impl &amp;operator=(const thread_pool_impl &amp;) = delete; template &lt;typename Function, typename... Args, typename ReturnType = std::invoke_result_t&lt;Function &amp;&amp;, Args &amp;&amp;...&gt;&gt; requires std::invocable&lt;Function, Args...&gt; [[nodiscard]] std::future&lt;ReturnType&gt; enqueue(Function &amp;&amp;f, Args &amp;&amp;...args) { // use shared promise here so that we don't break the promise later auto shared_promise = std::make_shared&lt;std::promise&lt;ReturnType&gt;&gt;(); auto task = [func = std::move(f), ... largs = std::move(args), promise = shared_promise]() { promise-&gt;set_value(func(largs...)); }; // get the future before enqueuing the task auto future = shared_promise-&gt;get_future(); // enqueue the task enqueue_task(std::move(task)); return future; } template &lt;typename Function, typename... Args&gt; requires std::invocable&lt;Function, Args...&gt; &amp;&amp; std::is_same_v&lt;void, std::invoke_result_t&lt;Function &amp;&amp;, Args &amp;&amp;...&gt;&gt; void enqueue_detach(Function &amp;&amp;func, Args &amp;&amp;...args) { enqueue_task(detail::bind(std::forward&lt;Function&gt;(func), std::forward&lt;Args&gt;(args)...)); } private: using semaphore_type = std::binary_semaphore; using task_type = FunctionType; struct task_pair { semaphore_type semaphore{0}; Queue&lt;task_type&gt; tasks{}; }; template &lt;typename Function&gt; void enqueue_task(Function &amp;&amp;f) { const std::size_t i = count_++ % queues_.size(); queues_[i]-&gt;tasks.push(std::forward&lt;Function&gt;(f)); queues_[i]-&gt;semaphore.release(); } std::vector&lt;std::jthread&gt; threads_; // have to use unique_ptr here because std::binary_semaphore is not move/copy // assignable/constructible std::vector&lt;std::unique_ptr&lt;task_pair&gt;&gt; queues_; std::size_t count_ = 0; }; using thread_pool = thread_pool_impl&lt;dp::thread_safe_queue&gt;; } // namespace dp </code></pre> <p>For the sake of completeness, I will also include my safe queue implementation though it is not necessary to review that here. I will more than likely open a new code review post for that class specifically.</p> <h2><code>thread_safe_queue.h</code></h2> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;condition_variable&gt; #include &lt;mutex&gt; #include &lt;queue&gt; namespace dp { template &lt;typename T&gt; class thread_safe_queue { public: using value_type = T; using size_type = typename std::queue&lt;T&gt;::size_type; thread_safe_queue() = default; void push(T&amp;&amp; value) { std::lock_guard lock(mutex_); data_.push(std::forward&lt;T&gt;(value)); condition_variable_.notify_all(); } bool empty() { std::lock_guard lock(mutex_); return data_.empty(); } [[nodiscard]] size_type size() { std::lock_guard lock(mutex_); return data_.size(); } [[nodiscard]] T&amp; front() { std::unique_lock lock(mutex_); condition_variable_.wait(lock, [this] { return !data_.empty(); }); return data_.front(); } [[nodiscard]] T&amp; back() { std::unique_lock lock(mutex_); condition_variable_.wait(lock, [this] { return !data_.empty(); }); return data_.back(); } void pop() { std::unique_lock lock(mutex_); condition_variable_.wait(lock, [this] { return !data_.empty(); }); data_.pop(); } private: using mutex_type = std::mutex; std::queue&lt;T&gt; data_; mutable mutex_type mutex_{}; std::condition_variable condition_variable_{}; }; } // namespace dp </code></pre> <p>Example driver code illustration how to use the thread pool:</p> <pre class="lang-cpp prettyprint-override"><code>dp::thread_pool pool(4); const auto total_tasks = 30; std::vector&lt;std::future&lt;int&gt;&gt; futures; for (auto i = 0; i &lt; total_tasks; i++) { auto task = [index = i]() { return index; }; futures.push_back(pool.enqueue(task)); } </code></pre> <p>Any feedback anyone has would be much appreciated. One thing in particular I'm not too thrilled about is the use of a <code>std::shared_ptr</code> in conjunction with a <code>std::promise</code> in the <code>enqueue</code> function.</p> <pre class="lang-cpp prettyprint-override"><code>auto shared_promise = std::make_shared&lt;std::promise&lt;ReturnType&gt;&gt;(); </code></pre> <p>I could not find a good way around this. I tried pretty extensively to get <code>std::packaged_task</code> to work, but I ran into issues that I wasn't able to solve since <code>std::packaged_task</code> is move only. This, however, may just be due to my lack of familiarity with this part of the standard.</p>
[]
[ { "body": "<h1>Unnecessary abstractions</h1>\n<p>Why is there a <code>class thread_pool_impl</code>, and then a single type alias to that class:</p>\n<pre><code>using thread_pool = thread_pool_impl&lt;dp::thread_safe_queue&gt;;\n</code></pre>\n<p>This indirection doesn't do anything useful as far as I can see, why not just make <code>dp::thread_safe_queue</code> a default value for the first template argument?</p>\n<pre><code>template &lt;template &lt;class T&gt; class Queue = thread_safe_queue,\n typename FunctionType = std::function&lt;void()&gt;&gt;\nrequires std::invocable&lt;FunctionType&gt; &amp;&amp;\n std::is_same_v&lt;void, std::invoke_result_t&lt;FunctionType&gt;&gt; &amp;&amp;\n detail::is_valid_queue&lt;Queue&lt;FunctionType&gt;&gt;\nclass thread_pool {\n ...\n};\n</code></pre>\n<p>However, I would not even make the queue type a template parameter, but just hardcode it to <code>thread_safe_queue</code>. Why would you want the user of a <code>thread_pool</code> to be able to change the queue type? The <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI principle</a> applies here.</p>\n<p>You are also defining type aliases like <code>semaphore_type</code> and <code>mutex_type</code>, but those are all made <code>private</code>. I don't see a good reason for that. Those type aliases are normally meant to be part of the public API, so that users of a class can easily use the right types.</p>\n<h1>Use a <code>std::deque</code> for <code>queues_</code></h1>\n<p>You can avoid having <code>queues_</code> be a vector of <code>std::unique_ptr</code>s by using a <code>std::deque&lt;task_pair&gt;</code> instead.</p>\n<h1>About <code>shared_promise</code></h1>\n<p>You might have already tried this:</p>\n<pre><code>std::promise&lt;ReturnType&gt; promise;\nauto future = promise.get_future();\nauto task = [func = std::move(f), ... largs = std::move(args),\n promise = std::move(promise)]() {\n promise.set_value(func(largs...));\n};\nenqueue_task(std::move(task));\n</code></pre>\n<p>By getting the future before creating the task, we can then <code>std::move()</code> the promise into the lambda. However, that doesn't work, because <code>set_value()</code> is not <code>const</code>, and by default lambda captures are <code>const</code>. So we could make it <code>mutable</code>:</p>\n<pre><code>auto task = [func = std::move(f), ... largs = std::move(args),\n promise = std::move(promise)]() mutable {...};\n</code></pre>\n<p>But then the problem is that pushing the task into <code>queues_[i].tasks</code> doesn't work, because <code>std::function</code> unfortunately cannot hold move-only functions. You will have to wait for C++23 for <a href=\"https://en.cppreference.com/w/cpp/utility/functional/move_only_function\" rel=\"nofollow noreferrer\"><code>std::move_only_function</code></a>, or implement it yourself, or perhaps store the task in a <code>std::unique_ptr</code> (but that would be no better than storing the promise in one).</p>\n<h1>Naming things</h1>\n<p>Functions and variables have very good names, except that I would rename <code>task_pair</code> to <code>task_queue</code>.</p>\n<h1>Unlock the mutex before notifying a condition variable</h1>\n<p>When notifying a condition variable, the idea is that this wakes up another thread waiting on that variable. However, if the corresponding mutex is still locked, the thread that's just woken up then has to first wait for the mutex to be unlocked. It is more efficient to first unlock the mutex, then notify the condition variable, like so:</p>\n<pre><code>void push(T&amp;&amp; value) {\n {\n std::lock_guard lock(mutex_);\n data_.push(std::forward&lt;T&gt;(value));\n }\n condition_variable_.notify_all();`\n}\n</code></pre>\n<h1>Unsafe access to front and back element of <code>thread_safe_queue</code></h1>\n<p>Returning a reference to an element of a thread-safe queue is dangerous. What if another thread pops that element? What if you wanted the back element, and then another thread pushes another element to the queue, then the first thread thinks it has a reference to the back element, but it is no longer the back.</p>\n<p>Also, are you sure references to elements are still valid if another thread pushes or pops elements? A <code>std::queue</code> is a container <em>adapter</em>; it uses a regular container to store its elements. Luckily, the default container it uses is a <code>std::deque</code>, and that one does provide stable references for its elements. However, you could have made a <code>std::queue&lt;T, std::vector&lt;T&gt;&gt;</code>, and then the references would be invalidated as soon as something is pushed to the queue.</p>\n<p>While the <code>pop()</code> functions of STL containers don't return a value (mostly with good reason), it would be better for a thread-safe queue to provide a <code>pop()</code> function that atomically removes the front element and returns it, and remove the <code>front()</code> and <code>back()</code> functions.</p>\n<h1>Consider using a single queue</h1>\n<p>You have one queue for each thread in the thread pool. However, that means if the tasks don't all take the same time, then it can be that one queue has much more work to do than the other queues. At some point the thread belonging to that one queue is the only one still running tasks, while the other threads are idle. If you instead use a single queue for all threads, you will not have this issue.</p>\n<h1>The problem with futures</h1>\n<p>Just for your interest: while using promises and futures is a very good idea to be able to enqueue arbitrary tasks and get back the results, there is a problem with <code>std::future</code>: you can't wait on multiple futures at once. So asynchronously processing the results is hard, unless something like <a href=\"https://en.cppreference.com/w/cpp/experimental/when_any\" rel=\"nofollow noreferrer\"><code>when_any()</code></a> gets implemented.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T17:54:15.450", "Id": "533635", "Score": "0", "body": "Very nice points overall, thank you for the thorough review. I haven't tried anything yet in code, but on the surface, I don't understand how using a `std::deque` would allow me to not use a vector of `unique_ptr`. The reason I did that was because of the semaphore class (it's neither copy-able or move-able). Would a `deque` still help with that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T22:36:34.670", "Id": "533654", "Score": "0", "body": "Unlike a `std::vector`, a `std::deque` doesn't need to move its storage around in memory when it resizes. Thus, it can be used to store move-only types like the `std::binary_semaphore`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T13:54:22.057", "Id": "533690", "Score": "1", "body": "Is `std::binary_semaphore` move-only? Based on the documentation it is not move constructible or move assignable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T15:12:45.177", "Id": "533709", "Score": "0", "body": "I tried it and it works! Thank you, I learned something new today!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T15:43:06.777", "Id": "533711", "Score": "1", "body": "Ah sorry, I meant that `std::deque` can store unmovable types." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T11:29:02.163", "Id": "270242", "ParentId": "270236", "Score": "4" } }, { "body": "<p>It looks like your code is not working as expected. If I try it with the following :</p>\n<pre><code>std::atomic&lt;int&gt; counter = 0;\n\nvoid test_pools(const int taskCount)\n{\n dp::thread_pool pool(4);\n const auto total_tasks = taskCount;\n std::vector&lt;std::future&lt;int&gt;&gt; futures;\n for (auto i = 0; i &lt; total_tasks; i++) {\n auto task = [index = i]() { counter++; return index; };\n futures.push_back(pool.enqueue(task));\n }\n}\n\nint main()\n{\n test_pools(20);\n std::cout &lt;&lt; counter;\n}\n</code></pre>\n<p>Then I would have expected <code>counter</code> to be 20. Changing <code>test_pools</code> to the following partially solves the problem:</p>\n<pre><code>void test_pools(const int taskCount)\n{\n dp::thread_pool pool(4);\n const auto total_tasks = taskCount;\n std::vector&lt;std::future&lt;int&gt;&gt; futures;\n for (auto i = 0; i &lt; total_tasks; i++) {\n auto task = [index = i]() { counter++; return index; };\n futures.push_back(pool.enqueue(task));\n }\n while (counter &lt; taskCount)\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\n}\n</code></pre>\n<p>To fix this, you will have to create some way to determine if all tasks have been created and completed before joining the threads.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T17:52:38.387", "Id": "533634", "Score": "0", "body": "Nice catch! I'll have to add this to the test suite and address it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T18:05:07.667", "Id": "533636", "Score": "0", "body": "@DeveloperPaul, cool. I would perhaps suggest adding another function, something like `waitTillDone`. I get that this should happen in the destructor, but sometimes you don't want `thread_safe_queue` to fall out of the scope to continue. See [this](https://bit.ly/3x8CmGI) for an illustration:" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T13:48:24.650", "Id": "270243", "ParentId": "270236", "Score": "5" } } ]
{ "AcceptedAnswerId": "270242", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T22:21:52.283", "Id": "270236", "Score": "5", "Tags": [ "c++", "multithreading", "thread-safety", "concurrency", "c++20" ], "Title": "C++20 Thread Pool" }
270236
<h3>Intro</h3> <p>This is a spiritual successor to the question <a href="https://codereview.stackexchange.com/questions/262728/stop-cheating-on-home-exams-using-python">Stop cheating on home exams using python</a></p> <p>The details are not important, but I decided to reimplement everything using dataclasses. My script is now working, but is a bit big (around 1200 lines). So in order to ease the burden I will split my codereview into a few questions spaced over a few days or weeks.</p> <p><strong>This question only focuses on how I store and use the configuration options provided by the user</strong></p> <p>My filestructure is as follows</p> <pre><code>uni.py &lt;- mainfile candidates.py exam.py texfile.py variable.py problem.py tools.py default_config.py </code></pre> <p>Now the defaults of the program is stored in a <code>config.py</code> file which looks like this</p> <pre><code>from default_config import Config CONFIG: Config = { &quot;texfile&quot;: &quot;None&quot;, &quot;candidates&quot;: 0, &quot;set_variable&quot;: &quot;setfpvar&quot;, &quot;get_variable&quot;: &quot;fv&quot;, &quot;input_formats&quot;: [&quot;input&quot;, &quot;include&quot;], &quot;latex_comment&quot;: &quot;%&quot;, &quot;PDFLATEX_OR_XELATEX&quot;: &quot;xelatex&quot;, &quot;equal_comment_indent_per_problem&quot;: True, &quot;python_code_as_comment&quot;: True, &quot;use_python_in_comment&quot;: False, &quot;candidate_number_pad&quot;: 3, &quot;subdir&quot;: True, &quot;all_subdirs_equal&quot;: True, &quot;tex_dir&quot;: &quot;tex&quot;, &quot;pdf_dir&quot;: &quot;pdf&quot;, &quot;solution_dir&quot;: &quot;solution&quot;, &quot;build_dir&quot;: &quot;aux&quot; } </code></pre> <p>Every file that needs it, imports this file to read of the default values. For ease of readability I decided that the user interacts with this config file using a <code>config.yaml</code> file that is identical, but with added comments.</p> <pre><code>config: texfile: None candidates: 0 # Sets the names of misc commands used in the texfile set_variable: setfpvar get_variable: fv input_formats: - input - include latex_comment: '%' # Decides which engine to use to compile the texfile # Standard options are 'xelatex' or 'pdflatex' PDFLATEX_OR_XELATEX: xelatex # If comment is true the python code to generate the # variable's value is placed as a comment next to it # in the tex file equal_comment_indent_per_problem: true python_code_as_comment: true # If true the comment mentined above can be used in reverse; # meaning if a comment is present next to a varible we try # to run it as a Python command to generate the value. # DANGEROUS use_python_in_comment: false # Number of places to pad the candidate number (001)=3 candidate_number_pad: 3 # Defines which subdirectories to put each file in # if subdir is false everything is dumped into main subdir: true all_subdirs_equal: true tex_dir: tex pdf_dir: pdf solution_dir: solution build_dir: aux </code></pre> <p>The idea is that command line arguments succeed the config options, which again succeeds the default config options. The following code below has two jobs it either populates the <code>config.py</code> file, or it creates a <code>config.yaml</code> file for the user to play around with.</p> <ul> <li>I was very happy with being able to do <code>from config import CONFIG</code> in all of my classes, which was a major reason why I decided to implement the config system in this manner.</li> </ul> <p>This is just the parser, as mentioned I have not included the exam generation. Run as</p> <p><code>uni.py exam -h</code> or <code>uni.py config -h</code></p> <p>To see the possible options.</p> <h3>uni.py</h3> <pre><code>import argparse from pathlib import Path from typing import Union from default_config import ( dump_config_2_yaml, load_default_config, load_yaml_from_config, dump_config_2_python, ) def is_float(potential_float: str) -&gt; bool: try: float(potential_float) return True except ValueError: return False # Refference # Title: In Python, using argparse, allow only positive integers # Source: https://stackoverflow.com/a/14117511/1048781 def non_negative_int(value: str): &quot;&quot;&quot;Raises an exception unless value is non-negative Args: param1: A value parsed as a string Returns: The input string value as an integer. Raises: ArgumentTypeError: uni.py: error: argument --candidates/-n: Expected a positive int for number of candidates, got &quot;&quot;&quot; if not is_float(value): raise argparse.ArgumentTypeError( f&quot;Expected a positive int for number of candidates, got {value}&quot; ) negative, not_integer = (ivalue := float(value)) &lt; 0, int(ivalue) != ivalue if negative or not_integer: raise argparse.ArgumentTypeError( f&quot;Expected a positive int for number of candidates, got {value}&quot; ) return ivalue def check_dir(path: Union[Path, str]): if (dir_ := Path(path)).is_dir(): return dir_.resolve() raise argparse.ArgumentTypeError( f&quot;Expected a directory, but got '{path}' instead, which does not exist&quot; ) def check_path(path: Path, suffix: str) -&gt; Path: if not path.is_file(): raise argparse.ArgumentTypeError( &quot;Expected a .{suffix} file, but the path provided does not exist&quot; ) elif not path.suffix == &quot;.&quot; + suffix: raise argparse.ArgumentTypeError( f&quot;Expected a .{suffix} file, got a {path.suffix} instead&quot; ) return path def texfile(path: str) -&gt; Path: &quot;&quot;&quot;Check if the provided path is an existing tex file&quot;&quot;&quot; return check_path(Path(path), &quot;tex&quot;) def yamlfile(path: str) -&gt; Path: &quot;&quot;&quot;Check if the provided path is an existing yaml file&quot;&quot;&quot; return check_path(Path(path), &quot;yaml&quot;) def yaml_or_texfile(path: str) -&gt; Path: suffixes = [&quot;.tex&quot;, &quot;.yaml&quot;] if not (path_ := Path(path)).is_file(): raise argparse.ArgumentTypeError( &quot;Expected one of {suffixes} type file,&quot; + &quot; but the path provided does not exist&quot; ) elif path_.suffix not in suffixes: raise argparse.ArgumentTypeError( &quot;Expected one of {suffixes} type file, &quot; + f&quot;but got a {path_.suffix} instead&quot; ) return path_ def yaml_or_dir(path: str) -&gt; Path: suffixes = [&quot;.yaml&quot;] if (path_ := Path(path)).is_dir(): return path_.resolve() if path_.suffix in suffixes: return path_ raise argparse.ArgumentTypeError( &quot;Expected a '.yaml' type filename or an &quot; + f&quot;existing dir, got a {path_} type instead&quot; ) def new_parser(): # create the top-level parser parser = argparse.ArgumentParser(prog=&quot;PROG&quot;) subparsers = parser.add_subparsers( help=&quot;command help&quot;, dest=&quot;commands&quot;, required=True ) # ================================================================================= # uni exam # ================================================================================= parsers_exam = subparsers.add_parser( &quot;exam&quot;, help=&quot;Generate random variants from a texfile&quot; ) parsers_exam.add_argument( &quot;path&quot;, type=yaml_or_texfile, metavar=&quot;PATH&quot;, help=&quot;The exam.tex file OR a config.yaml file (use 'uni generate&quot; + &quot;config' to generate a default config file&quot;, ) parsers_exam.add_argument( &quot;--texfile&quot;, type=texfile, metavar=&quot;PATH&quot;, help=&quot;The exam.tex (Useful if you set a config file using PATH&quot; + &quot; , and want to override the texfile in it)&quot;, ) parsers_exam.add_argument( &quot;--candidates&quot;, &quot;-n&quot;, type=non_negative_int, help=&quot;Number of candidates (Exams to generate)&quot;, ) parsers_exam.add_argument( &quot;--subdirs-equal&quot;, action=argparse.BooleanOptionalAction, default=None ) parsers_exam.add_argument( &quot;--texdir&quot;, type=str, help=&quot;Sets the directory to place the tex files&quot;, ) parsers_exam.add_argument( &quot;--pdfdir&quot;, type=str, help=&quot;Sets the directory to place the pdf files&quot;, ) parsers_exam.add_argument( &quot;--solutiondir&quot;, type=str, help=&quot;Sets the directory to place the solutions files&quot;, ) parsers_exam.add_argument( &quot;--builddir&quot;, type=str, help=&quot;Sets the directory to place the build files&quot;, ) parsers_exam.add_argument( &quot;--save-config&quot;, type=yaml_or_dir, metavar=&quot;PATH&quot;, nargs=&quot;?&quot;, const=Path().cwd(), default=None, help=&quot;Save the current settings.&quot; + &quot; Default path is current working directory&quot;, ) # ================================================================================= # uni config # ================================================================================= parser_default_config = subparsers.add_parser( &quot;config&quot;, help=&quot;Use to generate the default config file in PATH&quot; ) parser_default_config.add_argument( &quot;path&quot;, type=yaml_or_dir, metavar=&quot;PATH&quot;, nargs=&quot;?&quot;, default=Path().cwd(), help=&quot;Path (filename or dir) to generate the&quot; + &quot; default config file for exams&quot;, ) return parser ARGPARSE_2_CONFIG = { &quot;texfile&quot;: &quot;texfile&quot;, &quot;candidates&quot;: &quot;candidates&quot;, &quot;subdirs_equal&quot;: &quot;subdirs-equal&quot;, &quot;texdir&quot;: &quot;texdir&quot;, &quot;solutiondir&quot;: &quot;solutiondir&quot;, &quot;builddir&quot;: &quot;builddir&quot;, &quot;pdfdir&quot;: &quot;pdfdir&quot;, } def generate_config(args): if args.path.suffix == &quot;.yaml&quot;: config = load_yaml_from_config(args.path) else: config = load_default_config() # The default config has no texfile by default config[&quot;config&quot;][&quot;texfile&quot;] = args.path # Command line arguments takes president over config.yaml for argparse_name, config_name in ARGPARSE_2_CONFIG.items(): if (argument := getattr(args, argparse_name)) is not None: config[&quot;config&quot;][config_name] = argument return config def exam(args): config = generate_config(args) # The user may have written a badly formated value for number of candidates non_negative_int(config[&quot;config&quot;][&quot;candidates&quot;]) if config[&quot;config&quot;][&quot;texfile&quot;] is None: raise argparse.ArgumentTypeError( &quot;PROG exam: error: the following arguments&quot; + &quot; are required: PATH, --candidates/-n&quot; ) if args.save_config is not None: if args.save_config.is_dir(): directory = args.save_config name = &quot;config.yaml&quot; else: directory = args.save_config.parent name = args.save_config.name dump_config_2_yaml(config=config, path=directory / name) dump_config_2_python(config) def config(args): if args.path.suffix == &quot;.yaml&quot;: config_path = args.path else: directory = args.path config_path = directory / &quot;config.yaml&quot; if dump_config_2_yaml(config=load_default_config(), path=config_path): print(f&quot;'{config_path}' successfully created&quot;) if __name__ == &quot;__main__&quot;: parser = new_parser() args = parser.parse_args() if args.commands == &quot;exam&quot;: exam(args) elif args.commands == &quot;config&quot;: config(args) </code></pre> <h3>default_config.py</h3> <pre><code>import pprint from pathlib import Path import ruamel.yaml from typing import TypedDict yaml = ruamel.yaml.YAML() yaml.preserve_quotes = True DEFAULT_YAML = &quot;&quot;&quot;\ config: texfile: None candidates: 0 # Sets the names of misc commands used in the texfile set_variable: setfpvar get_variable: fv input_formats: - input - include latex_comment: '%' # Decides which engine to use to compile the texfile # Standard options are 'xelatex' or 'pdflatex' PDFLATEX_OR_XELATEX: xelatex # If comment is true the python code to generate the # variable's value is placed as a comment next to it # in the tex file equal_comment_indent_per_problem: True python_code_as_comment: True # If true the comment mentined above can be used in reverse; # meaning if a comment is present next to a varible we try # to run it as a Python command to generate the value. # DANGEROUS use_python_in_comment: False # Number of places to pad the candidate number (001)=3 candidate_number_pad: 3 # Defines which subdirectories to put each file in # if subdir is false everything is dumped into main subdir: True all_subdirs_equal: True tex_dir: tex pdf_dir: pdf solution_dir: solution build_dir: aux &quot;&quot;&quot; class Config(TypedDict): texfile: str candidates: int set_variable: str get_variable: str input_formats: list[str] latex_comment: str PDFLATEX_OR_XELATEX: str equal_comment_indent_per_problem: bool python_code_as_comment: bool use_python_in_comment: bool candidate_number_pad: int subdir: bool all_subdirs_equal: bool tex_dir: str pdf_dir: str solution_dir: str build_dir: str PATH = Path(__file__) DIR = PATH.parent YAML_CONFIG_PATH = DIR / PATH.with_suffix(&quot;.yaml&quot;) PYTHON_CONFIG_PATH = DIR / &quot;config.py&quot; if not YAML_CONFIG_PATH.is_file(): yaml.dump(yaml.load(DEFAULT_YAML), YAML_CONFIG_PATH) def load_yaml_from_config(path): return yaml.load(path) def dump_config_2_yaml(config, path): if not path.is_file(): yaml.dump(config, path) return True print( &quot;Ooops, it looks like the file \n\n&quot; + str(path) + &quot;\n\n already exists. Do you want to override it?&quot; ) if input(&quot;[y/N]&quot;).lower()[0] == &quot;y&quot;: yaml.dump(config, path) return True return False def load_default_config(path=YAML_CONFIG_PATH): if not path.is_file(): yaml.dump(yaml.load(path), YAML_CONFIG_PATH) return yaml.load(path) def dump_config_2_python(config, path=PYTHON_CONFIG_PATH, indent=4): imports = &quot;from default_config import Config&quot; config_body = pprint.pformat(config[&quot;config&quot;], indent=indent, sort_dicts=False)[ 1:-1 ] with open(path, &quot;w&quot;) as f: f.writelines( imports + &quot;\n\nCONFIG: Config = {\n &quot; + config_body.replace(&quot;'&quot;, '&quot;') + &quot;\n}&quot; ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T00:41:36.083", "Id": "533600", "Score": "0", "body": "`The user may have written a badly formated value for number of candidates` <- I did read your previous question, but just to clarify, your students will not be users of the script, it's just you, right? My reason for asking is because if your students will be using this script, that will influence to what extent reviewers should comment on how user-friendly the script should be" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T09:07:36.023", "Id": "533606", "Score": "1", "body": "@Setris Just me, I will post the code on github where (hopefully) other lectures can also take advantage of it. Prequisites being somewhat familiar with running things from the commandline and LaTeX" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T09:45:32.177", "Id": "533853", "Score": "0", "body": "@Setris I have updated my config somewhat. Is it fine to update the question as no one has answered? =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T12:53:49.730", "Id": "533858", "Score": "0", "body": "Ya that definitely should be okay" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T16:28:06.597", "Id": "533875", "Score": "0", "body": "Has this made it to GitHub yet?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T17:14:35.153", "Id": "533879", "Score": "1", "body": "@Reinderien It is ready, but I've been swamped at work. I will upload it during the weekend. Just missing a bunch of docstrings =)" } ]
[ { "body": "<p>Your <code>uni.py</code> is your &quot;main file&quot;; fine. As such, it should have a <code>#!/usr/bin/env python3</code> shebang. The nicer option is to make a proper module directory tree containing a <code>__main__.py</code> such that running <code>python -m uni</code> runs your module's main entry point.</p>\n<p>It's a good idea to ship a default <code>config.yaml</code> file inside of your module; this will mean that all of your <code>DEFAULT_YAML = &quot;&quot;&quot;</code> should simply be deleted.</p>\n<p><code>is_float</code> is, first of all, not <em>actually</em> what you care to evaluate; you care specifically about the narrower case of integers. Secondly, the way it's structured now prevents you from being able to raise with an inner exception cause object using a <code>from</code> clause. Also, you don't care about positive integers; you care about non-negative integers, which include 0. I would instead expect:</p>\n<pre><code>def non_negative_int(value: str, name: str) -&gt; int:\n &quot;&quot;&quot;Raises an exception unless value is non-negative&quot;&quot;&quot;\n\n try:\n ivalue = int(value)\n except ValueError as e:\n raise argparse.ArgumentTypeError(\n f&quot;Expected an integer for {name}, got {value}&quot;\n ) from e\n\n if ivalue &lt; 0:\n raise argparse.ArgumentTypeError(\n f&quot;Expected a non-negative int for {name}, got {ivalue}&quot;\n )\n\n return ivalue\n</code></pre>\n<p>Also note that this should not be hard-coded for <code>number of candidates</code> and should just accept a <code>name</code>.</p>\n<p>You're over-using the walrus operator. It's useful for the inside of a generator when you really, really need variables in-line. I've not found any of your cases that benefit from it, and you should just use traditional variable assignment instead.</p>\n<p>You've started some type hinting (good!) but it's incomplete. For instance, <code>check_dir</code> is missing its return hint.</p>\n<p>Some of your error messages don't make sense, like</p>\n<pre><code>if not path.is_file():\n raise argparse.ArgumentTypeError(\n &quot;Expected a .{suffix} file, but the path provided does not exist&quot;\n )\n</code></pre>\n<p>It doesn't matter what suffix you expect; all that matters is that the provided path doesn't exist but you don't actually tell the user what that was. Instead, just say <code>f'{path} does not exist'</code>.</p>\n<p>Avoid passing around two different suffix formats, one with a <code>.</code> and one without. Just use <code>.suffix</code> everywhere since that's what <code>pathlib</code> expects; and remove <code>&quot;.&quot; + suffix</code>.</p>\n<p><code>texfile</code> and <code>yamlfile</code> are a little awkward. They have two responsibilities - convert a string to a <code>Path</code>, and validate that path. <code>check_path</code> should, then, not return anything, and the first two functions should do the path construction, pass the path to <code>check_path</code>, and then return it.</p>\n<p><code>suffixes</code> should be a set literal <code>{}</code> instead of a list <code>[]</code>.</p>\n<p>Some of your string interpolation is incorrect. For example, <code>&quot;Expected one of {suffixes} type file,&quot;</code> is missing an <code>f</code> prefix.</p>\n<p>You don't need <code>+</code> string concatenation in many of the places you've currently written it, and can use implicit literal concatenation instead - for example,</p>\n<pre><code> raise argparse.ArgumentTypeError(\n &quot;Expected one of {suffixes} type file,&quot;\n + &quot; but the path provided does not exist&quot;\n )\n</code></pre>\n<p>can become</p>\n<pre><code> raise argparse.ArgumentTypeError(\n f&quot;Expected one of {suffixes} type file, &quot;\n &quot;but the path provided does not exist&quot;\n )\n</code></pre>\n<p>Whenever you have the temptation to write a &quot;chapter-heading comment&quot; like</p>\n<pre><code># =================================================================================\n# uni exam\n# =================================================================================\n</code></pre>\n<p>that's a very good indication that you should just make a subroutine. It will be self-documenting, you can delete the big comment header, and it will be more testable and maintainable.</p>\n<p>Some of your documentation can use a little work; for instance there's a parenthesis imbalance here:</p>\n<pre><code> help=&quot;The exam.tex file OR a config.yaml file (use 'uni generate&quot;\n + &quot;config' to generate a default config file&quot;,\n</code></pre>\n<p>When you want to call <code>cwd</code> like <code>Path().cwd()</code>, it's a static function. Don't construct a <code>Path</code>; just call it on the type like <code>Path.cwd()</code>.</p>\n<p>It's good that you have a <code>__main__</code> check. However, the symbols on the inside of that <code>if</code> are still in global scope. Make a <code>main()</code> to contain that code.</p>\n<p>When checking your <code>args.comments</code>, you should add a sanity <code>else:</code> at the end that raises if the command is unrecognized.</p>\n<p>The initialization of these globals:</p>\n<pre><code>PATH = Path(__file__)\nDIR = PATH.parent\nYAML_CONFIG_PATH = DIR / PATH.with_suffix(&quot;.yaml&quot;)\nPYTHON_CONFIG_PATH = DIR / &quot;config.py&quot;\n\nif not YAML_CONFIG_PATH.is_file():\n yaml.dump(yaml.load(DEFAULT_YAML), YAML_CONFIG_PATH)\n</code></pre>\n<p>should be captured in a function:</p>\n<pre><code>def make_default_paths() -&gt; Tuple[Path, Path]:\n path = Path(__file__)\n dir = path.parent\n yaml_config_path = dir / path.with_suffix(&quot;.yaml&quot;)\n python_config_path = dir / &quot;config.py&quot;\n\n if not yaml_config_path.is_file():\n yaml.dump(yaml.load(DEFAULT_YAML), yaml_config_path)\n\n return yaml_config_path, python_config_path\n\n\nYAML_CONFIG_PATH, PYTHON_CONFIG_PATH = make_default_paths()\n</code></pre>\n<p>Your <code>if input(&quot;[y/N]&quot;).lower()[0] == &quot;y&quot;:</code> is fragile. The <code>[0]</code> is going to raise if the user did what you told them and pressed enter to use the default of &quot;no&quot;. Instead, use <code>startswith</code> which will still work with a blank string.</p>\n<p><code>writelines</code> is not what you want; just call <code>write</code> - you have a single string, not an iterable of strings.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T16:57:28.703", "Id": "270359", "ParentId": "270244", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T15:18:19.640", "Id": "270244", "Score": "2", "Tags": [ "python", "python-3.x", "configuration" ], "Title": "Stop exam cheating using python: Part 2 - Argparse and config" }
270244
<p>This is my code to extract data from the DOL website for a project I'm doing for my portfolio. The code does extract all of the data that I need, however it runs really slowly. I think it took like 15 minutes for it to finish extracting everything. I would really appreciate if someone could just point me in the right direction.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.support.select import Select from selenium.webdriver.common.action_chains import ActionChains url = 'https://oui.doleta.gov/unemploy/claims.asp' driver = webdriver.Chrome(executable_path=r&quot;C:\Program Files (x86)\chromedriver.exe&quot;) driver.implicitly_wait(10) driver.get(url) driver.find_element_by_css_selector('input[name=&quot;level&quot;][value=&quot;state&quot;]').click() Select(driver.find_element_by_name('strtdate')).select_by_value('2020') Select(driver.find_element_by_name('enddate')).select_by_value('2021') driver.find_element_by_css_selector('input[name=&quot;filetype&quot;][value=&quot;html&quot;]').click() select = Select(driver.find_element_by_id('states')) for opt in select.options: opt.click() input('Press ENTER to submit the form') driver.find_element_by_css_selector('input[name=&quot;submit&quot;][value=&quot;Submit&quot;]').click() rows = driver.find_elements_by_xpath('//*[@id=&quot;content&quot;]/table/tbody') unemployment = [] # Iterate over the rows # Loop through tables from url with help of BeautifulSoup for table in rows: headers = [] for head in table.find_elements_by_xpath('//*[@id=&quot;content&quot;]/table/tbody/tr[2]/th'): headers.append(head.text) values = [] for row in table.find_elements_by_xpath('//*[@id=&quot;content&quot;]/table/tbody/tr')[2:]: values = [] for col in row.find_elements_by_xpath(&quot;./*[name()='th' or name()='td']&quot;): values.append(col.text) if values: unemp_dict = {headers[i]: values[i] for i in range(len(headers))} unemployment.append(unemp_dict) input('Press ENTER to close the automated browser') driver.quit() <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>To keep the review short, if you can get the data from an API instead of scraping, that's always going to be the faster option.</p>\n<p>Luckily, in this case there is such an API. Open the site with Chrome developer tools and request data for an arbitrary state. You will see that the website calls <code>POST https://oui.doleta.gov/unemploy/wkclaims/report.asp</code> to retrieve the data you're interested in.</p>\n<p>The following code snippet shows the API call and parsing of the response.</p>\n<pre class=\"lang-python prettyprint-override\"><code>#!/usr/bin/env python3\n\nimport requests\nimport xml.etree.ElementTree as ET\n\n&quot;&quot;&quot;\nExample XML response returned from API:\n\n&lt;r539cyState&gt;\n &lt;week&gt;\n &lt;stateName&gt;California&lt;/stateName&gt;\n &lt;weekEnded&gt;10/17/2020&lt;/weekEnded&gt;\n &lt;InitialClaims&gt;159,876&lt;/InitialClaims&gt;\n &lt;ReflectingWeekEnded&gt;10/10/2020&lt;/ReflectingWeekEnded&gt;\n &lt;ContinuedClaims&gt;1,836,240&lt;/ContinuedClaims&gt;\n &lt;CoveredEmployment&gt;17,473,068&lt;/CoveredEmployment&gt;\n &lt;InsuredUnemploymentRate&gt;10.51&lt;/InsuredUnemploymentRate&gt;\n &lt;/week&gt;\n ...\n&lt;/r539cyState&gt;\n&quot;&quot;&quot;\n\n\ndef main():\n # map of XML tag names to table column names\n tag_to_column_names = {\n &quot;stateName&quot;: &quot;State&quot;,\n &quot;weekEnded&quot;: &quot;Filed week ended&quot;,\n &quot;InitialClaims&quot;: &quot;Initial Claims&quot;,\n &quot;ReflectingWeekEnded&quot;: &quot;Reflecting Week Ended&quot;,\n &quot;ContinuedClaims&quot;: &quot;Continued Claims&quot;,\n &quot;CoveredEmployment&quot;: &quot;Covered Employment&quot;,\n &quot;InsuredUnemploymentRate&quot;: &quot;Insured Unemployment Rate&quot;,\n }\n\n data = {\n &quot;level&quot;: &quot;state&quot;,\n &quot;final_yr&quot;: 2022,\n &quot;strtdate&quot;: 2020,\n &quot;enddate&quot;: 2021,\n &quot;filetype&quot;: &quot;xml&quot;,\n &quot;states[]&quot;: &quot;CA&quot;,\n &quot;submit&quot;: &quot;Submit&quot;,\n }\n\n with requests.Session() as s:\n r = s.post(\n &quot;https://oui.doleta.gov/unemploy/wkclaims/report.asp&quot;, data=data\n )\n root = ET.fromstring(r.text)\n\n # iterating over &lt;week&gt; elements\n for week in root:\n for tag_name, column_name in tag_to_column_names.items():\n print(\n f&quot;{column_name} ({tag_name}): {week.find(tag_name).text}&quot;\n )\n print(&quot;\\n&quot;)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>State (stateName): California\nFiled week ended (weekEnded): 01/04/2020\nInitial Claims (InitialClaims): 36,720\nReflecting Week Ended (ReflectingWeekEnded): 12/28/2019\nContinued Claims (ContinuedClaims): 359,606\nCovered Employment (CoveredEmployment): 17,203,829\nInsured Unemployment Rate (InsuredUnemploymentRate): 2.09\n\n...\n</code></pre>\n<p>You can extend this example by iterating over all the states and making a request for each one. And if I were you I would just hard code the states in the script since there are only 53 of them (53 because the site's data includes District of Columbia (DC), Puerto Rico (PR), and the Virgin Islands (VI)).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T13:59:39.483", "Id": "533611", "Score": "0", "body": "Thank you very much @Setris." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T10:10:44.030", "Id": "270264", "ParentId": "270245", "Score": "1" } } ]
{ "AcceptedAnswerId": "270264", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T15:49:54.413", "Id": "270245", "Score": "1", "Tags": [ "python", "performance", "selenium" ], "Title": "Web Scraping DOL with Selenium" }
270245
<p>Although I have long experience of other languages, I've not used C until playing around with microcontrollers using the Arduino IDE. I'm a bit uncomfortable with my use of pointers in conjunction with C strings.</p> <p>Since this is a microcontroller project, I want to avoid the String class and try to write code that will be reasonably efficient as well as readable by C programmers (i.e. idiomatic or following best practise)</p> <p>I read data from a serial port, including a number in ASCII character form. I will display that number on a three-digit seven-segment display, so I want to right-justify numbers less than three digits and if the number is larger than 999 I just want to display the last three digits. I can indicate errors like out-of range numbers separately.</p> <p>I have the following working code</p> <pre><code>void setup() { Serial.begin(115200); Serial.println(last3Digits(&quot;12345&quot;)); // 345 Serial.println(last3Digits(&quot;789&quot;)); // 789 Serial.println(last3Digits(&quot;60&quot;)); // _60 Serial.println(last3Digits(&quot;5&quot;)); // __5 Serial.println(last3Digits(&quot;&quot;)); // __0 } char * last3Digits(char * aString) { char * retVal = &quot;abc&quot;; byte len = strlen(aString); switch (len) { case 0: strncpy(retVal, &quot;__0&quot;, 3); break; case 1: retVal[0] = '_'; retVal[1] = '_'; retVal[2] = aString[0]; break; case 2: retVal[0] = '_'; retVal[1] = aString[0]; retVal[2] = aString[1]; break; default: // len &gt;= 3 strncpy(retVal, aString+len-3, 3); // copy only last 3 digits } retVal[3] = 0; return retVal; } // --------------------------------------------------- byte counter = 0; void loop() { Serial.print(counter); Serial.print(&quot; &quot;); delay(1000); if (++counter &gt; 9) { counter = 0; } } </code></pre> <p>The above can be run in an online emulator at <a href="https://wokwi.com/arduino/projects/315730913481720385" rel="nofollow noreferrer">https://wokwi.com/arduino/projects/315730913481720385</a></p> <p>My function <code>last3Digits()</code> seems clumsy to me. I imagine it can be made smaller without losing readability, and I imagine I must have made some other rookie mistakes.</p> <ul> <li>overwriting a string constant (what is the better way to allocate space?)</li> <li>redundant setting of string terminator (felt safer)</li> <li>?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T16:34:27.230", "Id": "533621", "Score": "1", "body": "Re *\"write code that will be reasonably efficient\"*: Why do you assume that? Using C strings can become very very slow [if not used correctly](https://www.joelonsoftware.com/2001/12/11/back-to-basics/) (Shlemiel the painter’s algorithm). [A case](https://martynplummer.wordpress.com/2015/10/16/shlemiel-the-painter-strikes-again/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T17:18:24.900", "Id": "533629", "Score": "0", "body": "@PeterMortensen Oh just concerns about [potential issues described in this article](https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/) and a desire to develop skills that will be transferable to smaller microcontrollers like the ATtiny85 or ATtiny402." } ]
[ { "body": "<p>Well, there are some concerning points about your code:</p>\n<ol>\n<li><p>You are not using <code>const</code> where appropriate. It is there to help you avoid obvious bugs, like overwriting constants. Crank up the warning-level, and the compiler warns about assigning string-constants to mutable pointers.</p>\n</li>\n<li><p>If you need a small persistent space, ask for it. Don't misuse string-constants:</p>\n<pre><code> static char result[4] = &quot;&quot;;\n</code></pre>\n<p>Be aware static state breaks re-entrancy and thread-safety.</p>\n</li>\n<li><p><code>strncpy()</code> is not a string-function. It is a fixed-buffer-function, filling it with the start of the given string and zero-padding the end, thus generally wasting time or not adding a string-terminator.</p>\n</li>\n<li><p>Decide what to do with leading <code>'0'</code>. I would discard them.</p>\n</li>\n<li><p>Re-writing the same data already written is generally a poor use of your time. Still, it doesn't hurt that much, especially without any caches to invalidate and pages to dirty, like outside small microcontrollers.</p>\n</li>\n<li><p>If you unconditionally write underscores in the first two places of the return-buffer, you can thereafter ignore them if you don't have better things for them.</p>\n</li>\n<li><p>If you want a generic name for a string-argument, <code>s</code> conveys all the information you need.</p>\n</li>\n</ol>\n<p>Putting it all together and simplifying a bit:</p>\n<pre><code>char* last3Digits(const char* s) {\n static char r[4] = &quot;&quot;;\n r[0] = r[1] = '_';\n while (*s == '0')\n ++s;\n if (!*s)\n s = &quot;0&quot;;\n size_t n = strlen(s);\n s += n;\n if (n &gt; 3) n = 3;\n memcpy(r + 3 - n, s - n, n);\n return r;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T19:35:11.783", "Id": "270252", "ParentId": "270248", "Score": "4" } }, { "body": "<p>You can run into problems with thread safety when using a <code>static</code> buffer. I prefer the following form which should also work for any size display:</p>\n<pre><code>void lastDigits(char* buf, const size_t size, const char* num) \n{\n size_t len = strlen(num);\n if (len &gt;= size)\n {\n memcpy(buf, num + len - size, size + 1);\n }\n else\n {\n memset(buf, '_', size - len);\n memcpy(buf + size - len, num, len + 1);\n }\n}\n\nint main()\n{\n char buf[4];\n lastDigits(buf, 3, &quot;12&quot;);\n printf(&quot;%s\\n&quot;, buf);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T20:21:19.623", "Id": "533590", "Score": "1", "body": "Use `memset()` for filling underscores." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T20:23:29.387", "Id": "533591", "Score": "0", "body": "@Deduplicator thanks, updated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T20:35:57.083", "Id": "533592", "Score": "1", "body": "Rework and polish for a nice generic tool: Rename `rightJustify()`, argument for fill-character, ensure the input- and output-buffer may overlap (use `memmove()` instead of `memcpy()`, swap filling and moving)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T20:38:40.277", "Id": "533593", "Score": "0", "body": "@Deduplicator, sounds like a good idea for a whole new question ;-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T19:49:30.177", "Id": "270253", "ParentId": "270248", "Score": "4" } } ]
{ "AcceptedAnswerId": "270252", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T18:38:24.140", "Id": "270248", "Score": "3", "Tags": [ "c", "strings", "formatting", "pointers" ], "Title": "Simple string manipulation in C (for small microcontrollers)" }
270248
JScript is a scripting language based on the ECMAScript standard, created by Microsoft and implemented in a range of environments. You would expect this tag to accompany questions regarding these environments, such as Windows Script Host (WSH), Active Server Pages (ASP) and HTML Applications (HTA).
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T18:39:37.170", "Id": "270250", "Score": "0", "Tags": null, "Title": null }
270250
<p>I wrote the code below as a Kata to practice the <a href="https://clean-code-developer.com/grades/grade-1-red/#Integration_Operation_Segregation_Principle_IOSP" rel="nofollow noreferrer">Integration Operation Segregation Principle (IOSP, <code>clean-code-developers.com</code>)</a>. I would like to have some feedback on the code wrt. IOSP.</p> <p>I know that the code is not as efficient as it could be (mostly due to the fact that I am generating some copies of <code>List</code>s), but as I said: the focus of the Kata is IOSP, not efficiency.</p> <hr /> <p>Acceptance criteria:</p> <ul> <li>Method <code>merge(...)</code>: <ul> <li>takes two (possibly <code>null</code> or empty), sorted <code>List</code>s of some <code>T extends Comparable&lt;T&gt;</code> <ul> <li>If either of the input-<code>List</code>s is <code>null</code>, it should be treated as empty list</li> </ul> </li> <li>returns a single <code>List</code>, containing all elements of the two input lists, that is also sorted</li> </ul> </li> <li>The method should be pure, i.e.: <ul> <li>it must not throw any exception, and</li> <li>the input-<code>List</code>s should not be modified</li> </ul> </li> <li>Method <code>merge(...)</code> does not need to be stable.</li> </ul> <hr /> <p>Implementation:</p> <pre><code>import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; class SortedListMerger&lt;T extends Comparable&lt;T&gt;&gt; { private static final ConcurrentHashMap&lt;Class&lt;?&gt;, SortedListMerger&lt;?&gt;&gt; instanceMap = new ConcurrentHashMap&lt;&gt;(); @SuppressWarnings(&quot;unchecked&quot;) public static &lt;T extends Comparable&lt;T&gt;&gt; SortedListMerger&lt;T&gt; getInstance(Class&lt;T&gt; clazz) { return (SortedListMerger&lt;T&gt;) instanceMap.computeIfAbsent( clazz, unused -&gt; new SortedListMerger&lt;T&gt;()); } private SortedListMerger() { } public List&lt;T&gt; merge(List&lt;? extends T&gt; lhs, List&lt;? extends T&gt; rhs) { final MergeResult&lt;T&gt; mergeResult = mergeLists(lhs, rhs); return appendRest(mergeResult); } private MergeResult&lt;T&gt; mergeLists(List&lt;? extends T&gt; lhs, List&lt;? extends T&gt; rhs) { final List&lt;? extends T&gt; safeLhs = Optional.ofNullable(lhs).orElseGet(List::of); final List&lt;? extends T&gt; safeRhs = Optional.ofNullable(rhs).orElseGet(List::of); final int lhsSize = safeLhs.size(); final int rhsSize = safeRhs.size(); ArrayList&lt;T&gt; merged = new ArrayList&lt;&gt;(lhsSize + rhsSize); int lhsIndex = 0; int rhsIndex = 0; while (lhsIndex &lt; lhsSize &amp;&amp; rhsIndex &lt; rhsSize) { final T lhsValue = safeLhs.get(lhsIndex); final T rhsValue = safeRhs.get(rhsIndex); if (lhsValue.compareTo(rhsValue) &lt;= 0) { merged.add(lhsValue); ++lhsIndex; } else { merged.add(rhsValue); ++rhsIndex; } } return new MergeResult&lt;&gt;(safeLhs, lhsIndex, safeRhs, rhsIndex, merged); } private List&lt;T&gt; appendRest(MergeResult&lt;T&gt; result) { final List&lt;T&gt; intermediate = appendRest( result.safeLhs(), result.lhsIndex(), result.merged()); return appendRest(result.safeRhs(), result.rhsIndex(), intermediate); } private List&lt;T&gt; appendRest(List&lt;? extends T&gt; from, int firstIndexOfRest, List&lt;T&gt; to) { List&lt;T&gt; result = new ArrayList&lt;&gt;(to); int index = firstIndexOfRest; while (index &lt; from.size()) { result.add(from.get(index)); ++index; } return result; } private record MergeResult&lt;T extends Comparable&lt;T&gt;&gt;( List&lt;? extends T&gt; safeLhs, int lhsIndex, List&lt;? extends T&gt; safeRhs, int rhsIndex, List&lt;T&gt; merged) { private MergeResult( List&lt;? extends T&gt; safeLhs, int lhsIndex, List&lt;? extends T&gt; safeRhs, int rhsIndex, List&lt;T&gt; merged) { this.safeLhs = List.copyOf(safeLhs); this.lhsIndex = lhsIndex; this.safeRhs = List.copyOf(safeRhs); this.rhsIndex = rhsIndex; this.merged = List.copyOf(merged); } } } </code></pre> <hr /> <p>In case you want to run the code, here are some manual tests:</p> <pre><code>class Main { public static void main(String[] args) { final SortedListMerger&lt;Integer&gt; merger = SortedListMerger.getInstance(Integer.class); System.out.println(merger.merge(null, null)); System.out.println(merger.merge(List.of(), null)); System.out.println(merger.merge(null, List.of())); System.out.println(merger.merge(List.of(), List.of())); System.out.println(merger.merge(null, List.of(0, 1, 3, 5, 7, 9, 11))); System.out.println(merger.merge(List.of(), List.of(0, 1, 3, 5, 7, 9, 11))); System.out.println(merger.merge(List.of(0, 2, 4, 6), null)); System.out.println(merger.merge(List.of(0, 2, 4, 6), List.of())); System.out.println(merger.merge(List.of(0, 2, 4, 6), List.of(0, 1, 3, 5, 7, 9, 11))); } } </code></pre>
[]
[ { "body": "<h2>Mixed concerns</h2>\n<p>Rather than just letting the client create instances of the <code>SortedListMerger</code> class, there's a private constructor and a singleton map construction mechanic.</p>\n<p>If you really need to be able to construct the merger, based around the runtime class information then consider moving this responsibility out to a different class. This would allow the merger to concentrate on merging and the new class to concentrate on construction.</p>\n<p>If you don't actually need to be able to construct instances based on the <code>.class</code> information, consider if you really need to create an instance at all. Changing the signature of the method to:</p>\n<pre><code>public static &lt;S extends Comparable&lt;S&gt;&gt; List&lt;S&gt; merge(List&lt;? extends S&gt; lhs, \n List&lt;? extends S&gt; rhs) \n</code></pre>\n<p>Simplifies it for the caller, since it's possible for the compiler to infer the necessary types:</p>\n<pre><code>System.out.println(SortedListMerger.merge(List.of(0, 2, 4, 6), \n List.of(0, 1, 3, 5, 7, 9, 11)));\n</code></pre>\n<h2>Testing</h2>\n<p>Rather than printing the output of the merge to the console, consider writing actual unit tests. This would allow the reader to know what to expect from the method call. When merging '0,1,2' and '1,3,4' do I expect '0,1,2,3,4' or '0,1,1,2,3,4' for example? Without seeing the expected output, it's a run-it and see situation, particularly since none of your examples had any duplicates in the source data.</p>\n<p>There's an assumption in the code that sorted means in ascending order, however this doesn't seem to be explicitly stated in the requirements or method names. To me '4,3,2' is still sorted, it's just sorted the other direction. Consider if you want to support this, or make it more explicit that the sort direction must be ascending (maybe this is subjective since you're doing it the same what that <code>sorted</code> would).</p>\n<h2>Readability</h2>\n<p>I didn't find the code particularly easy to read. It felt overly complex, for the task that it's solving. Part of that is because the method names didn't really seem to necessarily convey what the methods were doing. So, looking at this <code>Integration</code> method:</p>\n<pre><code>public List&lt;T&gt; merge(List&lt;? extends T&gt; lhs, List&lt;? extends T&gt; rhs) {\n final MergeResult&lt;T&gt; mergeResult = mergeLists(lhs, rhs);\n return appendRest(mergeResult);\n}\n</code></pre>\n<p>At first glance it seems like it could be reasonable. But on reflection, you've got:</p>\n<ol>\n<li>Merge the lists.</li>\n<li>Append the rest.</li>\n</ol>\n<p>Ok, but if 1 has merged the lists, then what 'rest' is there to append? It turns out that 'merge list' really means merge until you've merged everything from one side or the other, then stop. If I drill into append the rest, it actually calls <code>append the rest</code> twice inside, once for the lhs and once for the rhs.</p>\n<p>A similar thing could have been achieved at the end of the <code>mergeLists</code> method:</p>\n<pre><code> merged.addAll(safeLhs.subList(lhsIndex, lhsSize));\n merged.addAll(safeRhs.subList(rhsIndex, rhsSize));\n</code></pre>\n<p>Which would have removed the need for the <code>MergeResult</code> etc.\nWhilst the logic has been split, it doesn't actually seem to have been split in a way that makes the code easier to understand.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T00:54:03.257", "Id": "270282", "ParentId": "270256", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T20:43:46.183", "Id": "270256", "Score": "3", "Tags": [ "java", "programming-challenge", "mergesort" ], "Title": "IOSP Kata: merge two sorted arrays without iterators" }
270256
<p>While playing with a <a href="https://codereview.stackexchange.com/questions/252659/fast-native-memory-manipulation-in-vba">VBA project</a> involving Windows APIs, I have noticed some odd behavior: API calls under Excel 2016/VBA7/x64 appeared to be much slower than under Excel 2002/VBA6/x32. Since I wanted to follow the recipe described in the <a href="https://rubberduckvba.wordpress.com/2018/09/11/lazy-object-weak-reference/" rel="nofollow noreferrer">Weak Reference</a> post, I decided to look into this performance matter more closely.</p> <h3>DLL side: Mock DLL library with test fixtures and a C-client</h3> <p>To simplify the interpretation of results, I created a small C-based dll with several stubs (memtools.c shown below) and a C-based client calling this dll and timing the calls (memtoolsclient.c). This C-code to C-code call timings provide performance references. The DLL includes five stubs. The first function, PerfGauge, takes a loop counter, times execution of an empty For loop within the DLL, and returns the result. The remaining stubs permit timing the dll calls and examine differences associated with passing arguments and returning a value. As their names suggest, these stubs</p> <ul> <li>are either a Sub or Function and</li> <li>take either zero or three arguments.</li> </ul> <p><strong>memtools.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;memtools.h&quot; // Volatile loop counter should be used here to prevent optimization. MEMTOOLSAPI int MEMTOOLSCALL PerfGauge(unsigned int ForCount) { struct timeb start, end; ftime(&amp;start); for (volatile unsigned int i=0; i &lt; ForCount; i++) { ; } ftime(&amp;end); return 1000 * (end.time - start.time) + (end.millitm - start.millitm); } MEMTOOLSAPI void MEMTOOLSCALL DummySub0Args() { return; } MEMTOOLSAPI void MEMTOOLSCALL DummySub3Args(void* Destination, const void* Source, size_t Length) { return; } MEMTOOLSAPI int MEMTOOLSCALL DummyFnc0Args() { volatile int Result = 10241024; return Result; } MEMTOOLSAPI int MEMTOOLSCALL DummyFnc3Args(void* Destination, const void* Source, size_t Length) { volatile int Result = 10241024; return Result; } </code></pre> <p><strong>memtools.h</strong></p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; #include &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;string.h&gt; #ifndef MEMTOOLS_H #define MEMTOOLS_H #ifdef _WIN32 /* You should define MEMTOOLS_EXPORTS *only* when building the DLL. */ #ifdef MEMTOOLS_EXPORTS #define MEMTOOLSAPI __declspec(dllexport) #else #define MEMTOOLSAPI __declspec(dllimport) #endif /* Define calling convention in one place, for convenience. */ #define MEMTOOLSCALL __stdcall #else /* _WIN32 not defined. */ /* Define with no value on non-Windows OSes. */ #define MEMTOOLSAPI #define MEMTOOLSCALL #endif /* _WIN32 */ /* Make sure functions are exported with C linkage under C++ compilers. */ #ifdef __cplusplus extern &quot;C&quot; { #endif /* Declare our function using the above definitions. */ MEMTOOLSAPI int MEMTOOLSCALL PerfGauge(unsigned int ForCount); MEMTOOLSAPI void MEMTOOLSCALL DummySub0Args(); MEMTOOLSAPI void MEMTOOLSCALL DummySub3Args(void*, const void*, size_t); MEMTOOLSAPI int MEMTOOLSCALL DummyFnc0Args(); MEMTOOLSAPI int MEMTOOLSCALL DummyFnc3Args(void*, const void*, size_t); #ifdef __cplusplus } // extern &quot;C&quot; #endif #endif /* MEMTOOLS_H */ </code></pre> <p><strong>memtoolsclient.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;memtools.h&quot; void DummySub0ArgsGauge(); void DummySub3ArgsGauge(); void DummyFnc0ArgsGauge(); void DummyFnc3ArgsGauge(); int main(int argc, char** argv) { DummySub0ArgsGauge(); DummySub3ArgsGauge(); DummyFnc0ArgsGauge(); DummyFnc3ArgsGauge(); return 0; } void DummySub0ArgsGauge() { void (*volatile MEMTOOLSCALL pDummySub0Args)(); pDummySub0Args = DummySub0Args; struct timeb start, end; ftime(&amp;start); for (volatile int i=0; i &lt; 1e9; i++) { pDummySub0Args(); } ftime(&amp;end); const int MSEC_IN_SEC = 1000; int diff; diff = MSEC_IN_SEC * (end.time - start.time) + (end.millitm - start.millitm); printf(&quot;\nDummySub0Args - 1e9 times - %u milliseconds\n&quot;, diff); } void DummySub3ArgsGauge() { char Src[] = &quot;ABCDEFGHIJKLMNOPGRSTUVWXYZABCDEFGHIJKLMNOPGRSTUVWXYZ&quot;; char Dst[255]; size_t SrcLen = sizeof(Src); struct timeb start, end; ftime(&amp;start); for (volatile int i=0; i &lt; 1e9; i++) { DummySub3Args(Dst, Src, SrcLen); } ftime(&amp;end); const int MSEC_IN_SEC = 1000; int diff; diff = MSEC_IN_SEC * (end.time - start.time) + (end.millitm - start.millitm); printf(&quot;\nDummySub3Args - 1e9 times - %u milliseconds\n&quot;, diff); } void DummyFnc0ArgsGauge() { int Result __attribute__((unused)); struct timeb start, end; ftime(&amp;start); for (volatile int i=0; i &lt; 1e9; i++) { Result = DummyFnc0Args(); } ftime(&amp;end); const int MSEC_IN_SEC = 1000; int diff; diff = MSEC_IN_SEC * (end.time - start.time) + (end.millitm - start.millitm); printf(&quot;\nDummyFnc0Args - 1e9 times - %u milliseconds\n&quot;, diff); } void DummyFnc3ArgsGauge() { char Src[] = &quot;ABCDEFGHIJKLMNOPGRSTUVWXYZABCDEFGHIJKLMNOPGRSTUVWXYZ&quot;; char Dst[255]; size_t SrcLen = sizeof(Src); int Result __attribute__((unused)); struct timeb start, end; ftime(&amp;start); for (volatile int i=0; i &lt; 1e9; i++) { Result = DummyFnc3Args(Dst, Src, SrcLen); } ftime(&amp;end); const int MSEC_IN_SEC = 1000; int diff; diff = MSEC_IN_SEC * (end.time - start.time) + (end.millitm - start.millitm); printf(&quot;\nDummyFnc3Args - 1e9 times - %u milliseconds\n&quot;, diff); } </code></pre> <hr /> <h3>VBA side: DllPerfLib class with VBA fixtures</h3> <p>The DllPerfLib VBA class calls these stubs and times them. Out of curiosity, I also added VBA stubs with signatures matching those in the dll so that DllPerfLib also times calls to these stubs yielding performance of native calls. DllPerfLib includes several blocks. The first block starting from the top contains dll stub declarations, factory, constructor, and attribute accessors. The second block handles dll loading from the project directory via the <a href="https://codereview.stackexchange.com/questions/268630/">DllManager</a> class. Then follows a wrapper for the performance reference routine (empty timed For loop inside the dll). The next block includes four functions, timing calls to corresponding dll stubs and their VBA twins defined in the last section of the class.</p> <p><strong>DllPerfLib.cls</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;DllManager.Demo.Custom and Extended DLL.DLL Call Performance&quot; '@ModuleDescription &quot;Provides utilities for guaging performance of DLL calls via the memtools DLL.&quot; '@PredeclaredId Option Explicit Private Const LIB_NAME As String = &quot;DllManager&quot; Private Const PATH_SEP As String = &quot;\&quot; Private Const LIB_RPREFIX As String = _ &quot;Library&quot; &amp; PATH_SEP &amp; LIB_NAME &amp; PATH_SEP &amp; _ &quot;Demo - DLL - STDCALL and Adapter&quot; &amp; PATH_SEP Public Enum TargetTypeEnum TARGET_DLL = 0&amp; TARGET_VBA = 1&amp; End Enum #If Win64 Then Private Declare PtrSafe Sub DummySub0Args Lib &quot;MemToolsLib&quot; () Private Declare PtrSafe Sub DummySub3Args Lib &quot;MemToolsLib&quot; (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long) Private Declare PtrSafe Function DummyFnc0Args Lib &quot;MemToolsLib&quot; () As Long Private Declare PtrSafe Function DummyFnc3Args Lib &quot;MemToolsLib&quot; (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long) As Long Private Declare PtrSafe Function PerfGauge Lib &quot;MemToolsLib&quot; (ByVal ForCount As Long) As Long #Else Private Declare Sub DummySub0Args Lib &quot;MemToolsLib&quot; () Private Declare Sub DummySub3Args Lib &quot;MemToolsLib&quot; (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long) Private Declare Function DummyFnc0Args Lib &quot;MemToolsLib&quot; () As Long Private Declare Function DummyFnc3Args Lib &quot;MemToolsLib&quot; (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long) As Long Private Declare Function PerfGauge Lib &quot;MemToolsLib&quot; (ByVal ForCount As Long) As Long #End If Private Type TDllPerfLib DllMan As DllManager DummyForCount As Long GaugeForCount As Long PrintToImmediate As Boolean Src() As Byte Dst() As Byte SrcLen As Long End Type Private this As TDllPerfLib Public Function Create( _ Optional ByVal DummyForCount As Long = 10000000, _ Optional ByVal GaugeForCount As Long = 10000000) As DllPerfLib Dim Instance As DllPerfLib Set Instance = New DllPerfLib Instance.Init DummyForCount, GaugeForCount Set Create = Instance End Function Friend Sub Init(Optional ByVal DummyForCount As Long = 10000000, _ Optional ByVal GaugeForCount As Long = 10000000) With this .DummyForCount = DummyForCount .GaugeForCount = GaugeForCount .PrintToImmediate = True End With Set this.DllMan = DllManager.Singleton If DllManager.Singleton Is Nothing Then LoadDlls this.Src = &quot;ABCDEFGHIJKLMNOPGRSTUVWXYZ&quot; this.Dst = String(255, &quot;_&quot;) this.SrcLen = (UBound(this.Src) - LBound(this.Src) + 1 + Len(vbNullChar)) * 2 End Sub Private Sub Class_Terminate() UnLoadDlls End Sub Public Property Get DummyForCount() As Long DummyForCount = this.DummyForCount End Property Public Property Let DummyForCount(ByVal Value As Long) this.DummyForCount = Value End Property Public Property Get GaugeForCount() As Long GaugeForCount = this.GaugeForCount End Property Public Property Let GaugeForCount(ByVal Value As Long) this.GaugeForCount = Value End Property Public Sub TogglePrint() this.PrintToImmediate = Not this.PrintToImmediate End Sub '''' ==================== HANDLE DLL LOADING ==================== '''' Private Sub LoadDlls() Dim DllPath As String DllPath = ThisWorkbook.Path &amp; PATH_SEP &amp; LIB_RPREFIX &amp; &quot;memtools\&quot; &amp; ARCH Dim DllName As String DllName = &quot;MemToolsLib.dll&quot; Set this.DllMan = DllManager.Create(DllPath, DllName, True) End Sub Private Sub UnLoadDlls() this.DllMan.ForgetSingleton this.DllMan.FreeMultiple Set this.DllMan = Nothing End Sub '''' ==================== PERFORMANCE GAUGE WRAPPER ==================== '''' Public Function PerfGaugeGet(Optional ByVal GaugeForCount As Long = -1) As Long Dim GaugeMax As Long GaugeMax = IIf(GaugeForCount &gt; 0, GaugeForCount, this.GaugeForCount) Dim TimeDiffMs As Long TimeDiffMs = PerfGauge(GaugeMax) If this.PrintToImmediate Then Debug.Print &quot;PerfGauge&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(GaugeMax, &quot;#,##0&quot;) &amp; _ &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If PerfGaugeGet = TimeDiffMs End Function '''' ==================== TEST STUBS WRAPPERS ==================== '''' Public Function Sub0ArgsDLLVBA(Optional ByVal DummyForCount As Long = -1, _ Optional ByVal TargetType As TargetTypeEnum = TARGET_DLL) As Long Dim DummyMax As Long DummyMax = IIf(DummyForCount &gt; 0, DummyForCount, this.DummyForCount) Dim CycleIndex As Long Dim Start As Single Start = Timer If TargetType = TARGET_DLL Then For CycleIndex = 0 To DummyMax DummySub0Args Next CycleIndex Else For CycleIndex = 0 To DummyMax DummySub0ArgsVBA Next CycleIndex End If Dim TimeDiffMs As Long TimeDiffMs = Round((Timer - Start) * 1000, 0) Dim Source As String Source = &quot;Sub0ArgsDLLVBA/&quot; &amp; Array(&quot;DLL&quot;, &quot;VBA&quot;)(TargetType) If this.PrintToImmediate Then Debug.Print Source &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) _ &amp; &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If Sub0ArgsDLLVBA = TimeDiffMs End Function Public Function Sub3ArgsDLLVBA(Optional ByVal DummyForCount As Long = -1, _ Optional ByVal TargetType As TargetTypeEnum = TARGET_DLL) As Long Dim Src() As Byte Src = this.Src Dim Dst() As Byte Dst = this.Dst Dim SrcLen As Long SrcLen = this.SrcLen Dim DummyMax As Long DummyMax = IIf(DummyForCount &gt; 0, DummyForCount, this.DummyForCount) Dim CycleIndex As Long Dim Start As Single Start = Timer If TargetType = TARGET_DLL Then For CycleIndex = 0 To DummyMax DummySub3Args Dst(0), Src(0), SrcLen Next CycleIndex Else For CycleIndex = 0 To DummyMax DummySub3ArgsVBA Dst(0), Src(0), SrcLen Next CycleIndex End If Dim TimeDiffMs As Long TimeDiffMs = Round((Timer - Start) * 1000, 0) If this.PrintToImmediate Then Debug.Print &quot;Sub3ArgsDLLVBA&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) _ &amp; &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If Sub3ArgsDLLVBA = TimeDiffMs End Function Public Function Fnc0ArgsDLLVBA(Optional ByVal DummyForCount As Long = -1, _ Optional ByVal TargetType As TargetTypeEnum = TARGET_DLL) As Long Dim Result As Long Dim DummyMax As Long DummyMax = IIf(DummyForCount &gt; 0, DummyForCount, this.DummyForCount) Dim CycleIndex As Long Dim Start As Single Start = Timer If TargetType = TARGET_DLL Then For CycleIndex = 0 To DummyMax Result = DummyFnc0Args Next CycleIndex Else For CycleIndex = 0 To DummyMax Result = DummyFnc0ArgsVBA Next CycleIndex End If Dim TimeDiffMs As Long TimeDiffMs = Round((Timer - Start) * 1000, 0) If this.PrintToImmediate Then Debug.Print &quot;Fnc0ArgsDLLVBA&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) _ &amp; &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If Fnc0ArgsDLLVBA = TimeDiffMs End Function Public Function Fnc3ArgsDLLVBA(Optional ByVal DummyForCount As Long = -1, _ Optional ByVal TargetType As TargetTypeEnum = TARGET_DLL) As Long Dim Src() As Byte Src = this.Src Dim Dst() As Byte Dst = this.Dst Dim SrcLen As Long SrcLen = this.SrcLen Dim Result As Long Dim DummyMax As Long DummyMax = IIf(DummyForCount &gt; 0, DummyForCount, this.DummyForCount) Dim CycleIndex As Long Dim Start As Single Start = Timer If TargetType = TARGET_DLL Then For CycleIndex = 0 To DummyMax Result = DummyFnc3Args(Dst(0), Src(0), SrcLen) Next CycleIndex Else For CycleIndex = 0 To DummyMax Result = DummyFnc3ArgsVBA(Dst(0), Src(0), SrcLen) Next CycleIndex End If Dim TimeDiffMs As Long TimeDiffMs = Round((Timer - Start) * 1000, 0) If this.PrintToImmediate Then Debug.Print &quot;Fnc3ArgsDLLVBA&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) _ &amp; &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If Fnc3ArgsDLLVBA = TimeDiffMs End Function '''' ==================== PERFORMANCE TEST STUBS ==================== '''' Private Sub DummySub0ArgsVBA() End Sub Private Sub DummySub3ArgsVBA(ByRef Destination As Byte, _ ByRef Source As Byte, ByVal Length As Long) End Sub Private Function DummyFnc0ArgsVBA() As Long Dim Result As Long Result = 10241024 DummyFnc0ArgsVBA = Result End Function Private Function DummyFnc3ArgsVBA(ByRef Destination As Byte, _ ByRef Source As Byte, ByVal Length As Long) As Long Dim Result As Long Result = 10241024 DummyFnc3ArgsVBA = Result End Function </code></pre> <p>The runner instantiates the DllPerLib class, sets repetition counts, and calls individual test members of DllPerLib performing secondary averaging.</p> <p><strong>DllPerfRun.bas</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;DllManager.Demo.Custom and Extended DLL.DLL Call Performance&quot; Option Explicit Private Sub Runner() Dim GaugeMax As Long GaugeMax = 10 ^ 9 Dim DummyMax As Long DummyMax = 10 ^ 7 Dim PerfTool As DllPerfLib Set PerfTool = DllPerfLib.Create(DummyMax, GaugeMax) Dim TimeDiffMs As Long Dim LoopIndex As Long With PerfTool .TogglePrint Dim AverageCountGAU As Long Dim AverageCountDLL As Long Dim AverageCountVBA As Long AverageCountGAU = 20 AverageCountDLL = 2 AverageCountVBA = 10 '''' ========== PerfGauge ========== '''' TimeDiffMs = 0 For LoopIndex = 1 To AverageCountGAU TimeDiffMs = TimeDiffMs + .PerfGaugeGet Next LoopIndex If AverageCountGAU &gt; 0 Then TimeDiffMs = TimeDiffMs / AverageCountGAU Debug.Print &quot;PerfGauge&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(GaugeMax, &quot;#,##0&quot;) &amp; _ &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If DoEvents '''' ---------- PerfGauge ---------- '''' '''' ========== Sub0ArgsDLLVBA ========== '''' TimeDiffMs = 0 For LoopIndex = 1 To AverageCountDLL TimeDiffMs = TimeDiffMs + .Sub0ArgsDLLVBA(, TARGET_DLL) Next LoopIndex If AverageCountDLL &gt; 0 Then TimeDiffMs = TimeDiffMs / AverageCountDLL Debug.Print &quot;Sub0ArgsDLLVBA/DLL&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) &amp; _ &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If DoEvents TimeDiffMs = 0 For LoopIndex = 1 To AverageCountVBA TimeDiffMs = TimeDiffMs + .Sub0ArgsDLLVBA(, TARGET_VBA) Next LoopIndex If AverageCountVBA &gt; 0 Then TimeDiffMs = TimeDiffMs / AverageCountVBA Debug.Print &quot;Sub0ArgsDLLVBA/VBA&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) &amp; _ &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If DoEvents '''' ---------- Sub0ArgsDLLVBA ---------- '''' '''' ========== Sub3ArgsDLLVBA ========== '''' TimeDiffMs = 0 For LoopIndex = 1 To AverageCountDLL TimeDiffMs = TimeDiffMs + .Sub3ArgsDLLVBA(, TARGET_DLL) Next LoopIndex If AverageCountDLL &gt; 0 Then TimeDiffMs = TimeDiffMs / AverageCountDLL Debug.Print &quot;Sub3ArgsDLLVBA/DLL&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) &amp; _ &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If DoEvents TimeDiffMs = 0 For LoopIndex = 1 To AverageCountVBA TimeDiffMs = TimeDiffMs + .Sub3ArgsDLLVBA(, TARGET_VBA) Next LoopIndex If AverageCountVBA &gt; 0 Then TimeDiffMs = TimeDiffMs / AverageCountVBA Debug.Print &quot;Sub3ArgsDLLVBA/VBA&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) &amp; _ &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If DoEvents '''' ---------- Sub3ArgsDLLVBA ---------- '''' '''' ========== Fnc0ArgsDLLVBA ========== '''' TimeDiffMs = 0 For LoopIndex = 1 To AverageCountDLL TimeDiffMs = TimeDiffMs + .Fnc0ArgsDLLVBA(, TARGET_DLL) Next LoopIndex If AverageCountDLL &gt; 0 Then TimeDiffMs = TimeDiffMs / AverageCountDLL Debug.Print &quot;Fnc0ArgsDLLVBA/DLL&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) &amp; _ &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If DoEvents TimeDiffMs = 0 For LoopIndex = 1 To AverageCountVBA TimeDiffMs = TimeDiffMs + .Fnc0ArgsDLLVBA(, TARGET_VBA) Next LoopIndex If AverageCountVBA &gt; 0 Then TimeDiffMs = TimeDiffMs / AverageCountVBA Debug.Print &quot;Fnc0ArgsDLLVBA/VBA&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) &amp; _ &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If DoEvents '''' ---------- Fnc0ArgsDLLVBA ---------- '''' '''' ========== Fnc3ArgsDLLVBA ========== '''' TimeDiffMs = 0 For LoopIndex = 1 To AverageCountDLL TimeDiffMs = TimeDiffMs + .Fnc3ArgsDLLVBA(, TARGET_DLL) Next LoopIndex If AverageCountDLL &gt; 0 Then TimeDiffMs = TimeDiffMs / AverageCountDLL Debug.Print &quot;Fnc3ArgsDLLVBA/DLL&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) &amp; _ &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If DoEvents TimeDiffMs = 0 For LoopIndex = 1 To AverageCountVBA TimeDiffMs = TimeDiffMs + .Fnc3ArgsDLLVBA(, TARGET_VBA) Next LoopIndex If AverageCountVBA &gt; 0 Then TimeDiffMs = TimeDiffMs / AverageCountVBA Debug.Print &quot;Fnc3ArgsDLLVBA/VBA&quot; &amp; &quot;:&quot; &amp; &quot; - &quot; &amp; Format$(DummyMax, &quot;#,##0&quot;) &amp; _ &quot; times in &quot; &amp; TimeDiffMs &amp; &quot; ms&quot; End If DoEvents '''' ---------- Fnc3ArgsDLLVBA ---------- '''' End With End Sub </code></pre> <h3>Test results</h3> <p>I compiled x32 and x64 versions of the DLL and the C-client with MSYS/MinGW toolchains on Windows with no optimization (-O0), ran tests on each pair, and used the two DLL's to run tests from Excel 2002/VBA6/x32 and Excel 2016/VBA7/x64 respectively. I ran DllPerfRun.Runner multiple times, discarded results that were much slower than the rest, and calculated average timings. Table 1 shows a representative subset of results.</p> <p><strong>Table 1. Time in seconds required for completion of 10<sup>9</sup> repetitions.</strong> <br /> <img src="https://raw.githubusercontent.com/pchemguy/SQLiteC-for-VBA/develop/Assets/Diagrams/VBA%20Performance.png" alt="Results" /></p> <h4>C-client timings</h4> <p>The leftmost column of Table 1 contains the PerfGauge timing. While I am not examining the disassembled code (which is a prudent thing to do), an empty unoptimized C-language For loop should require at least three machine instructions:</p> <ul> <li>increment the loop variable,</li> <li>compare the loop variable with the target,</li> <li>perform a conditional jump.</li> </ul> <p>On a 2.2 GHz multi-core processor with dynamic frequency adjustment (Intel Core i7-8750H @2.2GHz), the number of 2.1 s for 10<sup>9</sup> repetitions, therefore, appears to be qualitatively reasonable. The second column shows the timing for calling DummySub0Args from the C-client (see DummySub0ArgsGauge routine). I do not have sufficient experience to explain why the numbers in the second column are lower. However, I am more concerned about the results in the right half of the table.</p> <h4>VBA timings</h4> <p>The green cell highlights the efficiency of calling a DLL routine from VBA6/x32/Excel 2002. This number indicates that a DLL call taking no arguments and returning no value is only 5x times slower than the same call from a compiled C-client. Further, this call is 7x times faster than a native VBA call (rightmost column) with the same signature. When the called routine either takes arguments or returns a value, the difference is less pronounced. Still, with the other three implemented mock calls, the tendency is qualitatively similar.</p> <p>The primary concern is the cell with an orange background, indicating that a single DLL call takes 2 microseconds under 2016/VBA7/x64 instead of 8 nanoseconds under VBA6/x32/Excel 2002.</p> <p>Sources and precompiled binaries are available from the GitHub <a href="https://github.com/pchemguy/DllTools" rel="nofollow noreferrer">repository</a> and additional information - from GitHub <a href="https://pchemguy.github.io/DllTools/" rel="nofollow noreferrer">pages</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T15:25:49.760", "Id": "533615", "Score": "2", "body": "This is clearly good detailed research, but I think you would do better if you could make an even simpler minrepro and post it over on stack overflow. Something like _\"Here is a no-op function written in C which can be compiled into a dll. It can be invoked like `this ...` from C and takes 1.6ns on average (`C profiling code`). Alternatively it can be invoked from VBA like `this ...` and takes 8ns in VBA6 32 bit, 1950ns in 64 bit VBA7 (`VBA profiling code`)\"_. All this stuff about different dummy methods and dynamically loading the dll is added noise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T15:30:01.573", "Id": "533616", "Score": "2", "body": "... Or are you asking for a review of your profiling methodology rather than trying to work out why your 64 bit code is not performing as expected?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T16:41:36.857", "Id": "533624", "Score": "0", "body": "@Greedo Right, I posted a question on SO regarding the performance issue. I am also interested in feedback/review on my approach/code, which is why I posted it here and included all details. Another reason for adding the details is that this is not a standard approach, so I feel like providing a description is important." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T10:15:16.417", "Id": "533668", "Score": "0", "body": "@PChemGuy I get the slow performance on VBA7 x32 while on VBA7 x64 all dll calls are super fast as expected. The bitness is not necessarily related with the slow performance. It is rather the type of Antivirus/Firewall used in the system that seems to be causing performance issues. At least on my machines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T12:12:04.847", "Id": "533672", "Score": "0", "body": "@CristianBuse, I do not have antivirus on the computer where I ran tests. I believe that the only security feature enabled is the Windows firewall. It appears that Microsoft screwed up something fundamental with VBA. When I run test code, Excel uses its core at 100% level for the entire period." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T12:15:43.840", "Id": "533674", "Score": "0", "body": "@PChemGuy Might be unrelated. I just posted a comment to your answer [here](https://codereview.stackexchange.com/a/270053/227582) so you can see how bad it is for me on x32 VBA7 when using ```RtlMoveMemory```" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T12:21:09.510", "Id": "533675", "Score": "0", "body": "@PChemGuy Maybe my problem is completely different and makes API calls even slower on top of what you found already." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T12:24:14.533", "Id": "533676", "Score": "0", "body": "@CristianBuse, yes I see it. I tested RtlMoveMemory, and on VBA7/x-64, RtlMoveMemory is as slow as a dummy DLL call. I created dummy dll fixtures intentionally to make it as simple as possible. The fact that a dummy call rate matches that of the API call suggests that the problem is not about WinAPI, but specifically about DLL calls. Any Office extension may be affected, therefore!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T12:26:23.543", "Id": "533677", "Score": "0", "body": "@PChemGuy Yes, hence I spent an enormous amount of time to come up with that ByRef method for copying bytes. So, that I am not affected by Office version. As a side note, the [WeakRef](https://rubberduckvba.wordpress.com/2018/09/11/lazy-object-weak-reference/) you linked is leaking. Greedo found a very nice case when reviewing my old implementation [here](https://codereview.stackexchange.com/questions/245660/simulated-weakreference-class). There must be some safety in place so that VBA does not reuse the same memory location after deallocating a previous instance referred by the saved pointer." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-20T23:12:11.070", "Id": "270258", "Score": "2", "Tags": [ "performance", "vba", "excel", "winapi" ], "Title": "Evaluate performance of DLL calls from VBA" }
270258
<p>I just joined here. I have been doing python for a couple of weeks and I would like for some experienced programmers to review my code. I made this for a school project and I am proud of it. The code below works well but I would like to know what things I can improve on. Thank you for taking the time to review this.</p> <p><strong>main.py</strong></p> <pre><code>main_grid = [['+' for col in range(3)] for row in range(3)] player_one = {'key': 'P1', 'name': None, 'symbol': 'X', 'pos': []} player_two = {'key': 'P2', 'name': None, 'symbol': 'O', 'pos': []} player_list = [player_one, player_two] def title_screen(): print(' '*15, ' _____ _____ _____') print(' '*15, '|__ __|__ __| ____|') print(' '*15, ' | | |_| |_| |___') print(' '*15, ' _|_|_|_____|_____|') print(' '*15, '|__ __| ___ | ____|') print(' '*15, ' | | | | | | |___ ') print(' '*15, '__|_|_|_|_|_|_____|') print(' '*15, '|__ __| ___ | ____|') print(' '*15, ' | | | |_| | ____|') print(' '*15, ' |_| |_____|_____|') def info_screen(): print('-'*51) print('2021 L.A | A python school project. ') print() print(&quot;This game is a python version of 'TIC TAC TOE'.&quot;) print('I hope you enjoy! :]') print() def intro_screen(): print('RULES:') print('Rows and columns can only have inputs from [0-2].') print('Players can only enter value once unless value is') print('not valid.') print(&quot;Players can't put their symbol in already occupied&quot;) print('cells.') print('Players win if their symbol is placed 3 in a row') print('horizontally, vertically or diagonally. Anything') print('else does not count as a win.') print('If the grid is filled, the game results as a tie.') print() def start_screen(): title_screen() info_screen() intro_screen() def get_name(): for player_type in player_list: print(f&quot;Enter [{player_type['key']}] name:&quot;) player_type['name'] = input(f&quot;[{player_type['key']}] &gt; &quot;) print() def get_input(player_type, desc): print(desc) user_input = input(f&quot;[{player_type['key']}] {player_type['name']} &gt; &quot;) print() return user_input def get_point(player_type, desc): &quot;&quot;&quot;Makes user get a point value which could be a row or col.&quot;&quot;&quot; point = -1 while point not in range(3): try: point = int(get_input(player_type, desc)) except ValueError: print('The entered value must be an integer.') print('Please try again.') print() continue if point in range(3): return point elif point not in range(3): print('The entered value must be in range between 0-2.') print('Please try again.') print() continue else: print('Unknown error') print('Please try again.') print() continue def check_pos(pos): &quot;&quot;&quot;Check whether the pos value is in a player's coords list.&quot;&quot;&quot; if pos in player_one['pos'] or pos in player_two['pos']: print('The entered coordinate is occupied by a player.') print('Please try again.') print() return False else: return True def update_grid(pos): &quot;&quot;&quot;Updates grid using player coords.&quot;&quot;&quot; for player_type in player_list: for prev_pos in player_type['pos']: main_grid[prev_pos[0]][prev_pos[1]] = player_type['symbol'] def print_stats(player_type, turn_count): &quot;&quot;&quot;Prints current game stats.&quot;&quot;&quot; print('-'*51) print(f&quot;CURRENT TURNS | {turn_count}/9&quot;) print(f&quot;CURRENT PLAYER | {player_type['key']}&quot;) print(f&quot;CURRENT SYMBOL | {player_type['symbol']}&quot;) def print_grid(): &quot;&quot;&quot;Prints the grid&quot;&quot;&quot; print() for row in range(3): print(' '*21, end='') for col in range(3): print(main_grid[row][col], end=' ') print() print() def check_grid(player_type, pos): &quot;&quot;&quot;End game when symbol is three in a row or grid is filled. Continues if not three in a row or not filled.&quot;&quot;&quot; row = pos[0] col = pos[1] symbol = player_type['symbol'] win_msg = f&quot;[{player_type['key']}] {player_type['name']} has won the game.&quot; tie_msg = 'The game has resulted a tie.' if symbol == main_grid[row][0] == main_grid[row][1] == main_grid[row][2]: print_result(win_msg) return True elif symbol == main_grid[0][col] == main_grid[1][col] == main_grid[2][col]: print_result(win_msg) return True elif row == col and symbol == main_grid[0][0] == main_grid[1][1] == main_grid[2][2]: print_result(win_msg) return True elif row + col == 2 and symbol == main_grid[0][2] == main_grid[1][1] == main_grid[2][0]: print_result(win_msg) return True elif '+' not in main_grid[0] and '+' not in main_grid[1] and '+' not in main_grid[2]: print_result(tie_msg) return True else: return False def print_result(msg): &quot;&quot;&quot;Prints end result of game&quot;&quot;&quot; print('-'*51) print('RESULT:') print_grid() print(msg) exit_result() def setup_pos(player_type): &quot;&quot;&quot;Sets up position value Gets each point value. Checks each point value Checks position value Adds position value to player dictionary &quot;&quot;&quot; valid_pos = False while valid_pos is False: row = get_point(player_type, 'Select a row:') col = get_point(player_type, 'Select a column:') new_pos = (row, col) valid_pos = check_pos(new_pos) if valid_pos is True: player_type['pos'].append(new_pos) return new_pos def exit_result(): &quot;&quot;&quot;Choice to exit result screen.&quot;&quot;&quot; print() print(f&quot;Press any key to exit.&quot;) user_input = input('&gt; ') exit(0) def setup_game(): turn_count = 1 game_finish = False while game_finish is False: for player_type in player_list: print_stats(player_type, turn_count) print_grid() new_pos = setup_pos(player_type) update_grid(new_pos) game_finish = check_grid(player_type, new_pos) turn_count += 1 if game_finish is True: # If player won, break for loop on player's turn. break def main(): start_screen() get_name() setup_game() if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T09:56:47.680", "Id": "533607", "Score": "2", "body": "This is really good for someone just starting out! Keep it up!" } ]
[ { "body": "<p>As a beginner, you have done fantastic!</p>\n<p>There is always something to improve, in your code, mainly, performance.</p>\n<ul>\n<li><code>print()</code></li>\n</ul>\n<p>Instead of priniting again and again, create a string of output, and print it in a single call. It is way faster than printing in sperate calls.</p>\n<hr />\n<p>Your code has doc-strings, follows pep8 and is overall very readable. You could also add type-hints to make it even more explicit.</p>\n<hr />\n<p>In terms of user experience, it would be more comfortable to type 1-9 instead of both the row and column.\nYou could manage your grid as a nine element list.</p>\n<p>At the end, your project is awesome!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T02:13:32.863", "Id": "533841", "Score": "1", "body": "I disagree with your `print`-aggregation suggestion - at this scale, performance differences will be invisible and legibility is more important." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T11:46:36.433", "Id": "270267", "ParentId": "270261", "Score": "1" } }, { "body": "<p>So this is a great start for someone just starting out. I will go off on a huge tangent here, but hopefully you can take something away from how I approached improving a very minor part of your code.</p>\n<h3>Player states</h3>\n<pre><code>class Player:\n id: int\n name: str = &quot;&quot;\n symbol: str = &quot;&quot;\n is_winner: bool = False\n</code></pre>\n<p>Now we can build the list of players as follows</p>\n<pre><code>player_list = [Player(1, symbol=&quot;X&quot;), Player(2, symbol=&quot;O&quot;)]\n</code></pre>\n<p>Where did <code>pos</code> go? It would be better (and clearer) if the gamestate\nwas handled globally and not as a property of the players. It makes sense that the players are part of the game, not that the game is part of the players.</p>\n<p>There is no reason why your players could not be implemented as classes</p>\n<h3>Printing</h3>\n<p>The line <code>print(&quot;-&quot;*51)</code> can be improved in a few ways. <code>51</code> (and in general all non specified numbers in code) are known colloquially as\n<a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\"><code>magic-numbers</code></a> and is an <a href=\"https://stackoverflow.com/questions/980601/what-is-an-anti-pattern\">anti-pattern</a>. Where does the number come from?\nWhy is it not <code>52</code> or <code>50</code>? We can fix this by defining it as a constant</p>\n<pre><code>BLANKLINE = &quot;-&quot; * 51\n</code></pre>\n<p>As a sidenote notice that we wrote <code>*</code> and not <code>*</code>, this is because\nPython has style guide that specifies that operators need a little breathing room<sup><a href=\"https://stackoverflow.com/a/37956466/1048781\">This is a lie</a></sup>. If you use <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\">Black</a> or another formater it fixes these things for you.</p>\n<p><code>info_screen</code> can now look like</p>\n<pre><code>def info_screen() -&gt; str:\n &quot;&quot;&quot;Information about the game&quot;&quot;&quot;\n\n return f&quot;&quot;&quot;{BLANKLINE}\n \n 2021 L.A | A python school project. &quot;\n This game is a python version of 'TIC TAC TOE'.\n &quot;I hope you enjoy! :]&quot;\n &quot;&quot;&quot;\n</code></pre>\n<p>Where we have added a very short docstring and <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">typing hints</a>.\nPerhaps more importantly we have split generating the information\nand printing the information. While now there would be nothing wrong\nwith printing in the <code>info_screen</code> file, what if we wanted to append text to it later?</p>\n<h3>Overall principles</h3>\n<ul>\n<li>Implement your game using classes and objects it will make it easier to handle the game logic.</li>\n<li>Consider (just for fun) implementing a <a href=\"https://codepen.io/labiej/post/using-bit-logic-to-keep-track-of-a-tic-tac-toe-game\" rel=\"nofollow noreferrer\">bitboard</a> to handle the game state, or again take an <a href=\"https://www.youtube.com/watch?v=7Djh-Cbgi0E\" rel=\"nofollow noreferrer\">object oriented approach</a>.</li>\n<li>Separate printing from creation (Programmers tend to refer to this as <a href=\"https://www.ics.com/blog/heres-why-you-should-separate-ui-business-logic-your-application\" rel=\"nofollow noreferrer\">seperate UI (user interface) from business logic</a>)</li>\n<li>Get rid of your <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic-numbers</a> (I see a floating 15, 21 and a few others)</li>\n<li>Consider using the <a href=\"https://realpython.com/python-walrus-operator/\" rel=\"nofollow noreferrer\">walrus operator</a></li>\n</ul>\n<p>Turing this</p>\n<pre><code>def setup_pos(player_type):\n valid_pos = False\n while valid_pos is False:\n row = get_point(player_type, &quot;Select a row:&quot;)\n col = get_point(player_type, &quot;Select a column:&quot;)\n new_pos = (row, col)\n valid_pos = check_pos(new_pos)\n if valid_pos is True:\n player_type[&quot;pos&quot;].append(new_pos)\n return new_pos\n</code></pre>\n<p>into this</p>\n<pre><code>def get_pos(player_type):\n row = get_point(player_type, &quot;Select a row:&quot;)\n col = get_point(player_type, &quot;Select a column:&quot;)\n return (row, col)\n\ndef setup_pos(player_type):\n while not valid_pos(pos := get_pos(player_type)):\n pass\n player_type[&quot;pos&quot;].append(pos)\n return pos\n</code></pre>\n<p>Where <code>check_pos</code> was renamed <code>valid_pos</code>.</p>\n<ul>\n<li>The <code>player_type[&quot;pos&quot;].append(pos)</code> in the code above is another antipattern. Notice how <code>player_type</code> is a global function, we try to avoid those as best as we can. Limiting the scope of functions and variables makes it much easier to squash bugs! Again the proper solution is classes =)</li>\n</ul>\n<h3>Overall principles</h3>\n<p>I will leave the bullet points above for you to implement and adapt.\nInstead I will focus on how I would &quot;improve&quot; (totally over-engineer).</p>\n<p><strong>Notice how I would never do the improvements I do here in production</strong></p>\n<p>If you can (and you should) find libraries that can handle the pretty printing to the command line. However, <em>just for learning</em>. Let us see how we can implement something simple</p>\n<pre><code>def title_screen():\n print(' '*15, ' _____ _____ _____')\n print(' '*15, '|__ __|__ __| ____|')\n print(' '*15, ' | | |_| |_| |___')\n print(' '*15, ' _|_|_|_____|_____|')\n print(' '*15, '|__ __| ___ | ____|')\n print(' '*15, ' | | | | | | |___ ')\n print(' '*15, '__|_|_|_|_|_|_____|')\n print(' '*15, '|__ __| ___ | ____|')\n print(' '*15, ' | | | |_| | ____|')\n print(' '*15, ' |_| |_____|_____|')\n</code></pre>\n<ul>\n<li>There is repetition as aforementioned.</li>\n<li>While subjective I find the particular ASCII font hard to read.\nParticularly an issue is that the lines are not connected.</li>\n</ul>\n<p>An improvement would be something like this</p>\n<p><a href=\"https://i.stack.imgur.com/OLHEF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OLHEF.png\" alt=\"enter image description here\" /></a></p>\n<p>So how do we get there?</p>\n<ol>\n<li><p>We split everything to do with generating a fancy title into it's own file. At the end of the day we will use it as follows</p>\n<pre><code>from title import Title, asciify, fullborder\n\nTIC_TAC_TITLE = Title(asciify(&quot;TIC TAC &quot;TOE&quot;), border=fullborder, width=79)\n\n\ndef title_screen():\n print(TIC_TAC_TITLE)\n</code></pre>\n</li>\n</ol>\n<p>Which is your <code>main</code> and with much imagination we named the new file &quot;title.py&quot;.</p>\n<p>It is getting quite late but I will just leave the code here with a few highlights</p>\n<ul>\n<li><p>We split the generation of the fancy title into three parts</p>\n<ul>\n<li>We need to generate the ascii letters</li>\n<li>We need to make a border</li>\n<li>We need to combine the letters and the borders into a title</li>\n</ul>\n</li>\n<li><p>The first problem is solved in the <code>asciify</code> file. Using a dictionary we have defined a few handful of letters.</p>\n</li>\n<li><p>The title and border can both naturally be expressed as a classes</p>\n</li>\n<li><p>We add typing hints, docstrings and doctests wherever necessary.</p>\n</li>\n</ul>\n<p>Note that for improving the rest of the code you would do exactly the same.\nYou would try to split the code into separate parts, each part would go into it's own file. Here you would add classes as needed, add typing hints, doctests and then import it into your main file.</p>\n<h1>Code</h1>\n<pre><code>&quot;&quot;&quot;Takes in a list of letters [A,C,E,O,T,I, ] and returns them as ascii letters\n&quot;&quot;&quot;\nfrom dataclasses import dataclass\nfrom typing import Annotated\n\nASCII = {\n &quot;A&quot;: &quot;&quot;&quot;\n┌─────┐\n│ ┌─┐ │\n│ ├─┤ │\n└─┘ └─┘\n&quot;&quot;&quot;,\n &quot;C&quot;: &quot;&quot;&quot;\n┌─────┐\n│ ┌───┘\n│ └───┐\n└─────┘\n&quot;&quot;&quot;,\n &quot;E&quot;: &quot;&quot;&quot;\n┌─────┐\n│ ───┤\n│ ───┤\n└─────┘\n&quot;&quot;&quot;,\n &quot;O&quot;: &quot;&quot;&quot;\n┌─────┐\n│ ┌─┐ │\n│ └─┘ │\n└─────┘\n&quot;&quot;&quot;,\n &quot;T&quot;: &quot;&quot;&quot;\n┌─────┐\n└─┐ ┌─┘\n │ │ \n └─┘ \n&quot;&quot;&quot;,\n &quot;I&quot;: &quot;&quot;&quot;\n┌─────┐\n└─┐ ┌─┘\n┌─┘ └─┐\n└─────┘\n&quot;&quot;&quot;,\n &quot; &quot;: &quot;&quot;&quot;\n \n \n \n&quot;&quot;&quot;,\n &quot;-&quot;: &quot;&quot;&quot;\n\n ┌───┐ \n └───┘ \n&quot;&quot;&quot;,\n}\n\nPYTHON_MAX_CHAR_WIDTH = 79\nAsciiLetters = Annotated[str, &quot;A multiline string of big ascii letters&quot;]\nLength = Annotated[int, &quot;How long a particular string should be&quot;]\n\n\ndef asciify(letters: str, ascii_dict: dict = ASCII) -&gt; AsciiLetters:\n &quot;&quot;&quot;Turns a string into big ascii letters\n\n Args:\n letters: Optional. The word / collection of letters you want to asciify\n ascii_dict: A dictionary (mapping) between letters and their ascii representation\n\n Returns:\n The inputed letters in asccii form formated as a multiline string\n\n Example:\n &gt;&gt;&gt; print(asciify('A'))\n ┌─────┐\n │ ┌─┐ │\n │ ├─┤ │\n └─┘ └─┘\n &gt;&gt;&gt; print(asciify('TAC'))\n ┌─────┐┌─────┐┌─────┐\n └─┐ ┌─┘│ ┌─┐ ││ ┌───┘\n │ │ │ ├─┤ ││ └───┐\n └─┘ └─┘ └─┘└─────┘\n &gt;&gt;&gt; print(asciify('I-E-A-I-A-I-O'))\n ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐\n └─┐ ┌─┘ ┌───┐ │ ───┤ ┌───┐ │ ┌─┐ │ ┌───┐ └─┐ ┌─┘ ┌───┐ │ ┌─┐ │ ┌───┐ └─┐ ┌─┘ ┌───┐ │ ┌─┐ │\n ┌─┘ └─┐ └───┘ │ ───┤ └───┘ │ ├─┤ │ └───┘ ┌─┘ └─┐ └───┘ │ ├─┤ │ └───┘ ┌─┘ └─┐ └───┘ │ └─┘ │\n └─────┘ └─────┘ └─┘ └─┘ └─────┘ └─┘ └─┘ └─────┘ └─────┘\n &quot;&quot;&quot;\n ascii_letter_list = [ascii_dict[l] for l in list(letters)]\n lines = [letter.split(&quot;\\n&quot;) for letter in ascii_letter_list]\n letter_widths = [max(map(len, line)) for line in lines]\n ascii_art = []\n\n for letterlines in zip(*lines):\n line = &quot;&quot;\n for i, letter in enumerate(letterlines):\n line = line + f&quot;{letter:{letter_widths[i]}}&quot;\n ascii_art.append(line)\n\n ascii_letters = &quot;\\n&quot;.join(ascii_art)\n return ascii_letters.strip()\n\n\ndef repeat_to_length(string: str, wanted: Length) -&gt; str:\n &quot;&quot;&quot;Repeats a string to the desired length&quot;&quot;&quot;\n a, b = divmod(wanted, len(string))\n return string * a + string[:b]\n\n\n@dataclass\nclass Border:\n SW: str = &quot;&quot;\n SE: str = &quot;&quot;\n NE: str = &quot;&quot;\n NW: str = &quot;&quot;\n\n top: str = &quot;&quot;\n bottom: str = &quot;&quot;\n right: str = &quot;&quot;\n left: str = &quot;&quot;\n\n symmetric: bool = False\n\n def __post_init__(self):\n if not self.symmetric:\n return\n self.top, self.bottom = self.equal_values([self.top, self.bottom])\n self.left, self.right = self.equal_values([self.left, self.right])\n self.SW, self.SE, self.NE, self.NW = self.equal_values(\n [self.SW, self.SE, self.NE, self.NW]\n )\n\n def border_top(self, width):\n return self.horizontal(self.top, self.NW, self.NE, width)\n\n def border_bottom(self, width):\n return self.horizontal(self.bottom, self.SW, self.SE, width)\n\n @staticmethod\n def horizontal(symbol, left_corner, right_corner, width):\n if not symbol:\n return &quot;&quot;\n if width == 1:\n return left_corner\n main = repeat_to_length(symbol, width)\n return left_corner + main[:-2] + right_corner if len(main) &gt;= 2 else main\n\n @staticmethod\n def equal_values(values):\n total_values = len(values)\n for value in values:\n if value is None:\n continue\n return [value for _ in range(total_values)]\n return [None for _ in range(total_values)]\n\n\n@dataclass\nclass Title:\n text: str = &quot;&quot;\n border: Border = Border()\n center: bool = True\n width: int = 0\n\n def __post_init__(self):\n left, center = &quot;&lt;&quot;, &quot;^&quot;\n self.alignment = center if self.center else left\n\n def __str__(self):\n title = self.center_text() if self.center else self.text\n if self.border == Border():\n return title.rstrip()\n return self.add_border(text=title.rstrip())\n\n def center_text(self, width=None):\n width = width if width is not None else self.width\n textlines = self.text.split(&quot;\\n&quot;)\n textwidth = (\n max(len(l) for l in textlines)\n + len(self.border.left)\n + len(self.border.right)\n )\n width = textwidth if not width else width\n lines = [f&quot;{line:^{width}}&quot; for line in textlines]\n minimum_indent = &quot; &quot; * min(map(lambda l: len(l) - len(l.lstrip()), lines))\n return &quot;\\n&quot;.join(minimum_indent + line for line in textlines)\n\n def add_border(self, text, width=None):\n &quot;&quot;&quot;\n Adds a border to the self.text property of the Title class\n\n Args:\n width: Optional. If set the top and bottom border keeps this width.\n\n Returns:\n A title formated as a multiline string\n\n Example:\n &gt;&gt;&gt; print(Title(&quot;A&quot;, border=Border(), center=True, width=3))\n A\n &gt;&gt;&gt; print(Title(&quot;A&quot;, border=Border(top=&quot;=&quot;, SW=&quot;*&quot;, left=&quot;|&quot;, symmetric=True), center=True, width=3))\n *=*\n |A|\n *=*\n &gt;&gt;&gt; print(Title(&quot;A&quot;, border=Border(top=&quot;=&quot;, SW=&quot;*&quot;, left=&quot;|&quot;, symmetric=True), center=True, width=5))\n *===*\n | A |\n *===*\n &gt;&gt;&gt; print(Title(&quot;title&quot;, border=Border(bottom=&quot;=&quot;), center=True, width=79))\n title\n =============================================================================\n &quot;&quot;&quot;\n text = text if text is not None else self.text\n width = width if width is not None else self.width\n textlines = text.split(&quot;\\n&quot;)\n textwidth = (\n max(len(l.strip()) for l in textlines)\n + len(self.border.left)\n + len(self.border.right)\n )\n width = textwidth if not width else width\n\n top_border = self.border.border_top(width)\n bottom_border = self.border.border_bottom(width)\n if len(top_border) &lt; textwidth:\n if self.center:\n top_border = f&quot;{top_border:^{textwidth}}&quot;.rstrip()\n bottom_border = f&quot;{bottom_border:^{textwidth}}&quot;.rstrip()\n content_with_border = &quot;&quot; if not top_border else (top_border + &quot;\\n&quot;)\n content_with_border += text\n content_with_border += &quot;&quot; if not bottom_border else (&quot;\\n&quot; + bottom_border)\n return content_with_border\n\n content_with_border_list = []\n start = 0 if not self.border.left else 1\n for line in textlines:\n post_indent = &quot; &quot; * (\n width\n - len(line)\n - (0 if not self.border.right else len(self.border.right))\n )\n content_with_border_list.append(\n (\n self.border.left + line[start::] + post_indent + self.border.right\n ).rstrip()\n )\n content_with_border = &quot;\\n&quot;.join(content_with_border_list)\n return &quot;\\n&quot;.join([top_border, content_with_border, bottom_border]).rstrip()\n\n\nstarborder = Border(SW=&quot;*&quot;, top=&quot;=-&quot;, left=&quot;&quot;, symmetric=True)\nfullborder = Border(\n SW=&quot;└&quot;, SE=&quot;┘&quot;, NE=&quot;┐&quot;, NW=&quot;┌&quot;, top=&quot;─&quot;, bottom=&quot;─&quot;, left=&quot;│&quot;, right=&quot;│&quot;\n)\n\nif __name__ == &quot;__main__&quot;:\n import doctest\n\n doctest.testmod()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T15:16:39.710", "Id": "533869", "Score": "0", "body": "\"As a sidenote notice that we wrote `*` and not `*`\" – I think the Stackexchange software gobbles any spaces that you put into the code markup." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T23:42:24.963", "Id": "270280", "ParentId": "270261", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T06:21:04.937", "Id": "270261", "Score": "3", "Tags": [ "python", "beginner", "game", "tic-tac-toe" ], "Title": "Python TIC TAC TOE Project" }
270261
<p>I have implemented generic doubly linked list in C language in which you can store any data type you want. Just like in C++ and Java, where a list can store any data type, like - string, int, long, structure, etc., you can do the same using this program.</p> <p>Can someone please review the code.</p> <p>The code is below:</p> <hr /> <h2>generic_doubly_linked_list.c</h2> <pre><code> #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &quot;generic_doubly_linked_list.h&quot; /* * generic_doubly_linked_list.c: * * This program implements a linked list in which you can store any data type * you want. Just like in C++ and Java, a list can store any data type, like - * string, int, long, structure, etc., you can do the same using this program. * * There are comments in generic_doubly_linked_list.h which will help in * understanding the program. */ /* * char *get_error_string(int error_num): * * Function get_error_string() returns the string that corresponds to the error * number passed to it. * */ char *get_error_string(int error_num) { if (error_num == NO_ERROR) { return &quot;No error happened.&quot;; } else if (error_num == INVALID_DATA_TYPE) { return &quot;Argument 'data_type' is neither SIMPLE_DATA_TYPE nor COMPLEX_DATA_TYPE.&quot;; } else if (error_num == NO_MEMORY) { return &quot;No memory available.&quot;; } else if (error_num == INVALID_DATA_LEN) { return &quot;Argument 'data_len' is &lt;= 0.&quot;; } else if (error_num == ROOT_IS_NULL) { return &quot;Argument 'root' is NULL.&quot;; } else if (error_num == MATCHING_NODE_NOT_FOUND) { return &quot;No node found whose data matches the data given by the user.&quot;; } else if (error_num == DATA_IS_NULL) { return &quot;Argument 'data' is NULL.&quot;; } else { return &quot;Invalid error number given.&quot;; } } // end of get_error_string /* * dlln_ptr add_to_front(dlln_ptr root, long double data, int data_type, long data_len, int *error_num): * * Function add_to_front() adds a list node to the front of the list contaning data * passed to it by the user and the new root is returned. The root of the list will * change because the list node is added to front, so the user must update the * root value with the value returned by this function. * * In case any error happens, the error number is saved in the argument 'error_num'. * * If 'data_type' is SIMPLE_DATA_TYPE then the argument 'data_len' is ignored. * * The details of SIMPLE_DATA_TYPE and COMPLEX_DATA_TYPE can be found in * generic_doubly_linked_list.h. * * When you pass in a simple data type, the same data is stored in the data field * of the list node. So, if you pass in interger 4 then 4 will be stored in the * data field. If you pass a pointer to integer (for example - 0xABABABAB) * then 0xABABABAB will be stored in the data field. * * When you pass in a complex data type, then the data pointed to by the passed * in pointer is copied and not the pointer itself. So, if you pass in a pointer * to a string then new memory is allocated whose length is equal to the passed * in parameter 'data_len' and then contents of string are copied into this * new memory. Same goes for pointers to structures, unions, etc. */ dlln_ptr add_to_front(dlln_ptr root, long double data, int data_type, long data_len, int *error_num) { dlln_ptr temp = NULL; *error_num = NO_ERROR; if ((data_type != SIMPLE_DATA_TYPE) &amp;&amp; (data_type != COMPLEX_DATA_TYPE)) { *error_num = INVALID_DATA_TYPE; return root; } if (data_type == COMPLEX_DATA_TYPE) { //check if data is NULL if (data == 0) { *error_num = DATA_IS_NULL; return root; } // check data_len if (data_len &lt;= 0) { *error_num = INVALID_DATA_LEN; return root; } } temp = calloc(1, DLL_STRUCT_SIZE); if (!temp) { *error_num = NO_MEMORY; return root; } #if DEBUG_ON printf(&quot;Allocated memory for list node. Number of bytes allocated = %ld.\n&quot;, DLL_STRUCT_SIZE); #endif temp-&gt;data_type = data_type; if (data_type == SIMPLE_DATA_TYPE) { temp-&gt;data_len = 0; temp-&gt;data = data; } else { // COMPLEX_DATA_TYPE temp-&gt;data_len = data_len; temp-&gt;data = (long long)(calloc(data_len, 1)); if (temp-&gt;data == 0) { *error_num = NO_MEMORY; // zero out memory before free to catch some use after free bugs if any memset(temp, 0, DLL_STRUCT_SIZE); free(temp); return root; } #if DEBUG_ON printf(&quot;Allocated memory for data. Number of bytes allocated = %ld.\n&quot;, data_len); #endif memcpy((void *)(long long)(temp-&gt;data), (void *)(long long)(data), data_len); } // end of if else condition data_type == SIMPLE_DATA_TYPE temp-&gt;next = root; if (root) root-&gt;prev = temp; temp-&gt;prev = NULL; return temp; } // end of add_to_front /* * dlln_ptr delete_node_matching_data(dlln_ptr root, long double data, int data_type, long data_len, int *error_num): * * Function delete_node_matching_data() deletes a list node that contains the data * that matches the data passed in by the user and [new] root is returned. * In case, the list node to be deleted is the root itself then the list will have * a new root, so the user must update the root value with the value returned * by this function. * * In case any error happens, the error number is saved in the argument 'error_num'. * * If 'data_type' is SIMPLE_DATA_TYPE then the user supplied data is directly * compared with the data in the list node. If both the data are same, then * the node is deleted else the next node is inspected. In SIMPLE_DATA_TYPE data * type case argument 'data_len' is ignored. * * If 'data_type' is COMPLEX_DATA_TYPE then the value of the argument 'data_len' is * compared to the value of 'data_len' field of the list node. If they are not * equal then next node is inspected. If they are equal then the contents of the * memory pointed to by the user supplied data pointer is compared with the contents * of the memory pointed to by the data pointer in the list node and if they are * same then this node is deleted else the next node is inspected. * */ dlln_ptr delete_node_matching_data(dlln_ptr root, long double data, int data_type, long data_len, int *error_num) { dlln_ptr temp = NULL; int delete_this_node = 0; *error_num = NO_ERROR; if (!root) { *error_num = ROOT_IS_NULL; return root; } if ((data_type != SIMPLE_DATA_TYPE) &amp;&amp; (data_type != COMPLEX_DATA_TYPE)) { *error_num = INVALID_DATA_TYPE; return root; } if (data_type == COMPLEX_DATA_TYPE) { //check if data is NULL if (data == 0) { *error_num = DATA_IS_NULL; return root; } // check data_len if (data_len &lt;= 0) { *error_num = INVALID_DATA_LEN; return root; } } for (temp = root; temp != NULL; temp = temp-&gt;next) { if (data_type == SIMPLE_DATA_TYPE) { if (temp-&gt;data == data) { root = delete_node(root, temp); return root; } } else { // COMPLEX_DATA_TYPE if (temp-&gt;data_len != data_len) { continue; } if (memcmp((void *)(long long)(temp-&gt;data), (void *)(long long)(data), data_len) == 0) { root = delete_node(root, temp); return root; } } // end of if else condition data_type == SIMPLE_DATA_TYPE } // end of for loop // matching node not found *error_num = MATCHING_NODE_NOT_FOUND; return root; } // end of delete_node_matching_data /* * dlln_ptr delete_node(dlln_ptr root, dlln_ptr node_to_delete): * * Function delete_node() deletes the list node whose pointer is passed in the * argument 'node_to_delete' and returns [new] root. * * In case, the list node to be deleted is the root itself then the list will have * a new root, so the user must update the root value with the value returned * by this function. * */ dlln_ptr delete_node(dlln_ptr root, dlln_ptr node_to_delete) { dlln_ptr new_root = root; if (!root) { return root; } if (!node_to_delete) { return root; } if (node_to_delete == root) { // deleting root node new_root = root-&gt;next; if (new_root) { new_root-&gt;prev = NULL; } } else { node_to_delete-&gt;prev-&gt;next = node_to_delete-&gt;next; if (node_to_delete-&gt;next) { node_to_delete-&gt;next-&gt;prev = node_to_delete-&gt;prev; } } if (node_to_delete-&gt;data_type == COMPLEX_DATA_TYPE) { void *cmp_data = (void *)(long long)(node_to_delete-&gt;data); // zero out memory before free to catch some use after free bugs if any memset(cmp_data, 0, node_to_delete-&gt;data_len); free(cmp_data); #if DEBUG_ON printf(&quot;Freed data memory.\n&quot;); #endif } // zero out memory before free to catch some use after free bugs if any memset(node_to_delete, 0, DLL_STRUCT_SIZE); free(node_to_delete); #if DEBUG_ON printf(&quot;Freed list node memory.\n&quot;); #endif return new_root; } // end of delete_node /* * dlln_ptr delete_all_nodes_from_list(dlln_ptr root): * * Function delete_all_nodes_from_list() deletes all the nodes in the list and * returns NULL. * */ dlln_ptr delete_all_nodes_from_list(dlln_ptr root) { while (root) { root = delete_node(root, root); } return NULL; } // end of delete_all_nodes_from_list </code></pre> <hr /> <h2>generic_doubly_linked_list.h</h2> <pre><code> #ifndef _GENERIC_DOUBLY_LINKED_LIST_H #define _GENERIC_DOUBLY_LINKED_LIST_H /* * generic_doubly_linked_list.c: * * This program implements a linked list in which you can store any data type * you want. Just like in C++ and Java, a list can store any data type, like - * string, int, long, structure, etc., you can do the same using this program. * * There are comments in in this header file which will help in understanding * the program. */ #define NO_ERROR 0 // no error happened. #define INVALID_DATA_TYPE -1 // argument 'data_type' is neither SIMPLE_DATA_TYPE nor COMPLEX_DATA_TYPE. #define NO_MEMORY -2 // no memory available. #define INVALID_DATA_LEN -3 // argument 'data_len' is &lt;= 0. #define ROOT_IS_NULL -4 // argument 'root' is NULL. #define MATCHING_NODE_NOT_FOUND -5 // no node found whose data matches the data given by the user. #define DATA_IS_NULL -6 // argument 'data' is NULL. /* * SIMPLE_DATA_TYPE and COMPLEX_DATA_TYPE are used to tell the program that the * data is of simple type or of complex type. * * SIMPLE_DATA_TYPE: * Simple data type means char, short, int, long, float, double, long long, * long double, etc. and pointers to these data types. When you pass in a * simple data type, the same data is stored in the data field of the list node. * So, if you pass in interger 4 then 4 will be stored in the data field. If * you pass a pointer to integer (for example - 0xABABABAB) then 0xABABABAB will * be stored in the data field. The argument 'data_len' is ignored for * SIMPLE_DATA_TYPE. * * COMPLEX_DATA_TYPE: * Complex data type is always a pointer and it is a pointer to string, * structures, unions, etc. But pointer to int, float, etc. (basically, pointer * to basic data types) should be considered as SIMPLE_DATA_TYPE. When you * pass in a complex data type, then the data pointed to by the passed in pointer * is copied and not the pointer itself. So, if you pass in a pointer to a * string then new memory is allocated whose length is equal to the passed in * parameter 'data_len' and then contents of string are copied into this new memory. * Same goes for pointers to structures, unions, etc. * * IMPORTANT NOTE: When you are passing in a pointer to string, please make sure that * the length of the data that you pass in includes 1 extra byte * for null byte. */ #define SIMPLE_DATA_TYPE 1 // char, short, int, long, float, double, long long, long double, etc. and pointers to these data types #define COMPLEX_DATA_TYPE 2 // always a pointer which is pointer to string, structures, unions, etc. /* * Converting from long double to pointer and vice-versa: * * If you want to convert long double type to pointer type then please follow * the code below: * long double a; * char *b = (char *)(long long)(a); * * If you want to convert pointer type to long double type then please follow * the code below: * char *a; * long double b = (long double)(long long)(a); */ struct doubly_linked_list_node { int data_type; long data_len; long double data; struct doubly_linked_list_node *prev; struct doubly_linked_list_node *next; }; #define DLL_STRUCT_SIZE sizeof(struct doubly_linked_list_node) typedef struct doubly_linked_list_node *dlln_ptr; /* * NOTE: * * If you want to loop through the list and get the data then you can use the * following code: * * dlln_ptr temp = root; * while (temp) { * YOUR_DATA_TYPE data = (YOUR_DATA_TYPE)(long long)(temp-&gt;data); * // do something with data * temp = temp-&gt;next; * } */ /* * char *get_error_string(int error_num): * * Function get_error_string() returns the string that corresponds to the error * number passed to it. * */ char *get_error_string(int error_num); /* * dlln_ptr add_to_front(dlln_ptr root, long double data, int data_type, long data_len, int *error_num): * * Function add_to_front() adds a list node to the front of the list contaning data * passed to it by the user and the new root is returned. The root of the list will * change because the list node is added to front, so the user must update the * root value with the value returned by this function. * * In case any error happens, the error number is saved in the argument 'error_num'. * * If 'data_type' is SIMPLE_DATA_TYPE then the argument 'data_len' is ignored. * * The details of SIMPLE_DATA_TYPE and COMPLEX_DATA_TYPE can be found in * generic_doubly_linked_list.h. * * When you pass in a simple data type, the same data is stored in the data field * of the list node. So, if you pass in interger 4 then 4 will be stored in the * data field. If you pass a pointer to integer (for example - 0xABABABAB) * then 0xABABABAB will be stored in the data field. * * When you pass in a complex data type, then the data pointed to by the passed * in pointer is copied and not the pointer itself. So, if you pass in a pointer * to a string then new memory is allocated whose length is equal to the passed * in parameter 'data_len' and then contents of string are copied into this * new memory. Same goes for pointers to structures, unions, etc. */ dlln_ptr add_to_front(dlln_ptr root, long double data, int data_type, long data_len, int *error_num); /* * dlln_ptr delete_node_matching_data(dlln_ptr root, long double data, int data_type, long data_len, int *error_num): * * Function delete_node_matching_data() deletes a list node that contains the data * that matches the data passed in by the user and [new] root is returned. * In case, the list node to be deleted is the root itself then the list will have * a new root, so the user must update the root value with the value returned * by this function. * * In case any error happens, the error number is saved in the argument 'error_num'. * * If 'data_type' is SIMPLE_DATA_TYPE then the user supplied data is directly * compared with the data in the list node. If both the data are same, then * the node is deleted else the next node is inspected. In SIMPLE_DATA_TYPE data * type case argument 'data_len' is ignored. * * If 'data_type' is COMPLEX_DATA_TYPE then the value of the argument 'data_len' is * compared to the value of 'data_len' field of the list node. If they are not * equal then next node is inspected. If they are equal then the contents of the * memory pointed to by the user supplied data pointer is compared with the contents * of the memory pointed to by the data pointer in the list node and if they are * same then this node is deleted else the next node is inspected. * */ dlln_ptr delete_node_matching_data(dlln_ptr root, long double data, int data_type, long data_len, int *error_num); /* * dlln_ptr delete_node(dlln_ptr root, dlln_ptr node_to_delete): * * Function delete_node() deletes the list node whose pointer is passed in the * argument 'node_to_delete' and returns [new] root. * * In case, the list node to be deleted is the root itself then the list will have * a new root, so the user must update the root value with the value returned * by this function. * */ dlln_ptr delete_node(dlln_ptr root, dlln_ptr node_to_delete); /* * dlln_ptr delete_all_nodes_from_list(dlln_ptr root): * * Function delete_all_nodes_from_list() deletes all the nodes in the list and * returns NULL. * */ dlln_ptr delete_all_nodes_from_list(dlln_ptr root); #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T11:49:11.277", "Id": "533608", "Score": "1", "body": "I see you can add and delete nodes, but what about finding nodes, accessing the front or back of the list, and iterating over nodes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T12:32:58.893", "Id": "533678", "Score": "0", "body": "I am planning to implement them." } ]
[ { "body": "<p><code>get_error_string()</code> needs to return <code>const char*</code>, since it returns pointers to string literals.</p>\n<p>It should probably be implemented using <code>switch</code>. My preference is not to have a <code>default</code> case when dealing with enumerations (which the errors should be), so that I can have a compiler warning when I miss one of the values.</p>\n<pre><code>enum dll_error {\n NO_ERROR = 0,\n INVALID_DATA_TYPE = -1, \n NO_MEMORY = -2,\n INVALID_DATA_LEN = -3,\n ROOT_IS_NULL = -4,\n MATCHING_NODE_NOT_FOUND = -5,\n DATA_IS_NULL = -6,\n};\n</code></pre>\n\n<pre><code>const char *get_error_string(enum dll_error error_num)\n{\n switch (error_num) {\n case NO_ERROR: return &quot;No error happened.&quot;;\n case INVALID_DATA_TYPE: return &quot;Argument 'data_type' is neither SIMPLE_DATA_TYPE nor COMPLEX_DATA_TYPE.&quot;;\n case NO_MEMORY: return &quot;No memory available.&quot;;\n case INVALID_DATA_LEN: return &quot;Argument 'data_len' is &lt;= 0.&quot;;\n case ROOT_IS_NULL: return &quot;Argument 'root' is NULL.&quot;;\n case MATCHING_NODE_NOT_FOUND: return &quot;No node found whose data matches the data given by the user.&quot;;\n case DATA_IS_NULL: return &quot;Argument 'data' is NULL.&quot;;\n }\n return &quot;Invalid error number given.&quot;;\n}\n</code></pre>\n<hr />\n<p>I'm not a big fan of writing typedefs of pointer types like this:</p>\n<blockquote>\n<pre><code>typedef struct doubly_linked_list_node *dlln_ptr;\n</code></pre>\n</blockquote>\n<p>We lose the <code>*</code> in the code that shows we're dealing with a pointer type, and have to remember more context.</p>\n<hr />\n<blockquote>\n<pre><code>struct doubly_linked_list_node {\n int data_type;\n long data_len;\n long double data;\n struct doubly_linked_list_node *prev;\n struct doubly_linked_list_node *next;\n};\n</code></pre>\n</blockquote>\n<p><code>data_type</code> should probably be an <code>enum</code> type, rather than <code>int</code>.</p>\n<p>Why is <code>data_len</code> a signed type? This causes quite a few warnings, as we convert to <code>size_t</code> when using with <code>calloc()</code> and <code>memcpy()</code>, for example.</p>\n<hr />\n<p>When adding a node, we're very type-unsafe here:</p>\n<blockquote>\n<pre><code> temp-&gt;data = (long long)(calloc(data_len, 1));\n</code></pre>\n</blockquote>\n<p>Firstly, casting a <code>void*</code> to <code>long long</code> may not be reversible (as <code>long long</code> may have a different range to <code>intptr_t</code>). Secondly, converting this to a <code>long double</code> may also lose precision.</p>\n<p>Why is <code>data</code> not a suitable <code>union</code> type so that it can hold integer, floating or pointer types, without such risks?</p>\n<p>Fixing that would probably eliminate the static analyser warning I get, where it's unable to track the lifetime of the pointer due to the type conversion.</p>\n<hr />\n<p>What's the purpose of <code>delete_this_node</code> variable in <code>delete_node_matching_data()</code>? It seems to be always zero.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T12:43:32.233", "Id": "533679", "Score": "0", "body": "Thanks for the code review. data_len is signed type so that if user passes a negative value, then it can be caught. On my system (Ubuntu), I am using gcc 9.3.0. I don't get any warnings when I compile the program. There is no precision loss because long double is 16 bytes long and all pointers are 8 bytes. So, there is no precision loss because we are storing 8 bytes into 16 bytes. In linux kernel, they store pointers as unsigned long. Please see this: https://stackoverflow.com/questions/49675297/why-previous-kernel-cast-a-pointer-to-unsigned-long-in-c" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T13:06:07.567", "Id": "533682", "Score": "0", "body": "You should get more warnings - make sure you have enabled all the ones that could be useful (I used `gcc -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Wstrict-prototypes -fanalyzer`, for example)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T13:09:54.450", "Id": "533684", "Score": "0", "body": "If you only ever target one specific platform, then you may well get away with the conversion problems (assuming that the integer value of the pointer fits into the _mantissa_ of the floating-point type), but that unnecessarily limits portability when there are better solutions. And the question never mentioned that you only care about a single target platform. You shouldn't take Linux _kernel_ sources to be a good guide for creating portable _user programs_ - it has very different constraints." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T13:59:55.623", "Id": "270269", "ParentId": "270262", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T06:46:51.743", "Id": "270262", "Score": "1", "Tags": [ "c", "linked-list", "generics" ], "Title": "Generic doubly linked list in C" }
270262
<p>I have a simple project that I built that protects the routes/pages of the website by using the if and else statement and putting each page with a function <code>withAuth()</code>, but I'm not sure if that is the best way to protect routes with nextjs, and I noticed that there is a delay in protecting the route or pages, like 2-3 seconds long, in which they can see the content of the page before it redirects the visitor or unregistered user to the login page.</p> <p>Is there a way to get rid of it or make the request faster so that unregistered users don't view the page's content? Is there a better approach to safeguard a certain route in the nextjs framework?</p> <h1>Code</h1> <hr /> <pre><code>import { useContext, useEffect } from &quot;react&quot;; import { AuthContext } from &quot;@context/auth&quot;; import Router from &quot;next/router&quot;; const withAuth = (Component) =&gt; { const Auth = (props) =&gt; { const { user } = useContext(AuthContext); useEffect(() =&gt; { if (!user) Router.push(&quot;/login&quot;); }); return &lt;Component {...props} /&gt;; }; return Auth; }; export default withAuth; </code></pre> <h2>Sample of the use of withAuth</h2> <pre><code>import React from &quot;react&quot;; import withAuth from &quot;./withAuth&quot;; function sample() { return &lt;div&gt;This is a protected page&lt;/div&gt;; } export default withAuth(sample); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T09:20:25.017", "Id": "533908", "Score": "1", "body": "Hello, welcome to CR! This code looks like a stub, which is great for StackOverflow, but not great for CodeReview. There really isn't enough to work with (what you have looks good)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T03:55:09.737", "Id": "533962", "Score": "0", "body": "Does or doesn't, to the best of your knowledge, the code presented work as needed?" } ]
[ { "body": "<p>Obviously <code>AuthContext</code> from <code>@context/auth</code> is a blackbox to me here, so I'm unable to know if there's a server side auth capability. However, if you're able to retrieve the session server side, then with Next.js, you can use <a href=\"https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering\" rel=\"nofollow noreferrer\"><code>getServerSideProps</code></a> to redirect to <code>/login</code> if there's no user found. This would prevent the user from seeing any protected content on the page as you mentioned.</p>\n<p>For example:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// pages/myPage.js\n\nimport { getUser } from &quot;@context/auth&quot;;\n\nexport async function getServerSideProps(context) {\n const { user } = await getUser();\n\n if (!user) {\n return {\n redirect: {\n destination: &quot;/login&quot;,\n permanent: false,\n },\n };\n }\n\n return {\n props: { user },\n };\n}\n\nconst MyPage = ({ user }) =&gt; {\n return &lt;div&gt;This is a protected page&lt;/div&gt;;\n};\n\nexport default MyPage;\n</code></pre>\n<p>In general, on the client side (if you're unable to do this server side), I think that avoiding a higher order component pattern will improve readability. I'd create a simple composition instead, something like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>import { useContext, useEffect, useState } from &quot;react&quot;;\nimport { AuthContext } from &quot;@context/auth&quot;;\nimport Router from &quot;next/router&quot;;\n\nconst Authorised = ({ children }) =&gt; {\n const { user } = useContext(AuthContext);\n\n useEffect(() =&gt; {\n if (!user) Router.push(&quot;/login&quot;);\n }, [user]);\n\n if (!user) {\n return null;\n }\n\n return children;\n};\n\nconst Sample = () =&gt; {\n &lt;Authorised&gt;\n &lt;div&gt;This is protected content&lt;/div&gt;\n &lt;/Authorised&gt;\n};\n</code></pre>\n<p>Due to the fact you mentioned a delay (before the redirect?), I'd suggest you render a loading component, rather than <code>null</code>, for a better user experience, until you have retrieved the user session.</p>\n<p>I think it's also worth you reading the docs from <a href=\"https://nextjs.org/docs/authentication\" rel=\"nofollow noreferrer\">Next.js on authentication</a>, if you haven't done so already.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T16:08:21.967", "Id": "270389", "ParentId": "270263", "Score": "3" } } ]
{ "AcceptedAnswerId": "270389", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T08:57:18.897", "Id": "270263", "Score": "1", "Tags": [ "javascript", "security", "react.js" ], "Title": "Protect Routes/Page with NextJS" }
270263
<p>I'm currently learning C/C++ and I saw this question on Reddit on how to create a linked from an array and decided that would make a good exercise for learning the absolute basics of C, so without looking at the answers I wrote this.</p> <p>Anyways, preamble aside, here's the code:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; typedef struct Node Node; typedef struct Node { int data; Node *next; } Node; Node *array_to_list(int32_t array[], int32_t length) { if (length &lt;= 0) { return NULL; } Node* tail = NULL; for (int32_t i = length - 1; i &gt;= 0; i--) { Node* current = (Node*) malloc(sizeof(Node)); current-&gt;data = array[i]; current-&gt;next = tail; tail = current; } return tail; } void free_list(Node *head) { while (head != NULL) { Node *next = head-&gt;next; free(head); head = next; } } int main() { int array[] = { 1, 2, 3, 4, 5 }; Node *list = array_to_list(array, 5); Node *current = list; while (current != NULL) { printf(&quot;%d\n&quot;, current-&gt;data); current = current-&gt;next; } free_list(list); return 0; } </code></pre> <p>As of now this is all inside <code>main.c</code> and I didn't implement any other methods a linked list would normally have, I'm just trying to see if I'm doing things right</p>
[]
[ { "body": "<h1>Use the correct types</h1>\n<p>Use <code>size_t</code> instead of <code>int32_t</code> for the array size and index. Using <code>int32_t</code> will limit it to arrays containing 2,147,483,647 elements even if you compiled it for 64-bit mode.</p>\n<p>Also, note that it does not make sense to check if <code>i</code> or <code>length</code> is less than zero since it is unsigned.</p>\n<pre><code>Node* array_to_list(int array[], size_t length) {\n // ...\n for (size_t i = 0; i &lt; length; i++) {\n // ...\n }\n return tail;\n}\n</code></pre>\n<h1>Check if malloc was successful</h1>\n<p>You cannot simply assume that there will be enough memory available.</p>\n<h1>Putting it all together:</h1>\n<pre><code>Node* array_to_list(int array[], size_t length) {\n Node* tail = NULL;\n for (size_t i = 0; i &lt; length; i++) {\n Node* current = malloc(sizeof(Node));\n if (!current)\n {\n fprintf(stderr, &quot;Out of memory error&quot;);\n exit(EXIT_FAILURE);\n }\n current-&gt;data = array[length - 1 - i];\n current-&gt;next = tail;\n tail = current;\n }\n return tail;\n}\n\nint main() {\n int array[] = { 1, 2, 3, 4, 5 };\n struct Node* list = array_to_list(array, sizeof(array) / sizeof(array[0]));\n for (Node* node = list; node; node = node-&gt;next)\n printf(&quot;%d\\n&quot;, node-&gt;data);\n free_list(list);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T21:03:30.250", "Id": "533646", "Score": "0", "body": "Totally forgot about checking if malloc failed or not, but I think I'll still have to check if size isn't 0, because I need to loop over the array in reverse (so the linked list created is in the same order as the array), and if the length is 0 it'd underflow to 4294967295 and as such I'd index into an invalid place in the array" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T21:15:30.963", "Id": "533649", "Score": "0", "body": "@MindSwipe, see my latest edit. You don't have to check if `length` is 0. `array[length - 1 - i]` reverses the array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T22:03:34.343", "Id": "533650", "Score": "0", "body": "`Node* current = malloc(sizeof(Node));` could be `Node* current = malloc(sizeof(*current));`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T23:16:49.210", "Id": "533658", "Score": "0", "body": "@ggorlen potato, patata ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T23:27:13.883", "Id": "533659", "Score": "0", "body": "Not quite -- there's benefit to the second approach. See [sizeof style: sizeof(type) or sizeof variable?](https://softwareengineering.stackexchange.com/questions/201104/sizeof-style-sizeoftype-or-sizeof-variable)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T17:05:21.427", "Id": "533810", "Score": "0", "body": "There are benefits and downsides to both approaches. `#define MALLOC(t, n) (t*)malloc(sizeof(t) * n)` eliminates the downsides." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T18:31:06.723", "Id": "270276", "ParentId": "270268", "Score": "1" } } ]
{ "AcceptedAnswerId": "270276", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T12:50:52.657", "Id": "270268", "Score": "1", "Tags": [ "c", "array", "linked-list" ], "Title": "Create a linked list from an array, and also free that list" }
270268
<p>Could you please have a look at our naive bayes model. We look at a corpus of emails where an email is either spam or not. To classifiy we naively assume a bag of words and estimate prior probabilities through maximum likelihood. The model defintion can be found <a href="https://en.wikipedia.org/wiki/Naive_Bayes_classifier#Probabilistic_model" rel="nofollow noreferrer">here</a>:</p> <p>Specifically we are interested to understand if:</p> <ol> <li>Usage of <code>self</code> variables is fine or e.g. if methods should return things functionally instead of changing inplace.</li> <li>Splitting of methods is good practice or if it should be more condensed (i.e., less methods, bigger methods)</li> <li>Any unpythonic things or things you find hard to understand.</li> <li>I am aware lambda functions are supposedly no good practice but for the purpose I found them convenient. But please comment on that as well. I could declare a local function instead of using lambda.</li> </ol> <p><strong>Model</strong>:</p> <pre class="lang-py prettyprint-override"><code>from collections import defaultdict import sys import os import pickle import operator import math class NaiveBayes: def __init__(self, mode): # Sets file path arguments depending on mode of model usage self.mode = mode self.set_arguments() # Variables to save frequencies to self.freq_word_given_class = self.create_class_defaultdict() self.freq_word = defaultdict(int) self.freq_class = defaultdict(int) # Variables to save ML estimators to self.prob_word_given_class = self.create_class_defaultdict() self.prob_word = defaultdict(int) self.prob_class = defaultdict(int) # Variables needed for backoff smoothing self.rel_freq_word_given_class = self.create_class_defaultdict() self.prob_word_given_class_backoff = self.create_class_defaultdict() def predict(self): &quot;&quot;&quot; Doc string &quot;&quot;&quot; for file, target in self.get_files(): with open(f&quot;{os.getcwd()}/test/{target}/{file}&quot;, encoding=&quot;latin-1&quot;) as f: email = f.read().split() # Get probability score for each class # Operating in log space because probabilities get very small log_score = dict() for _class in self.classes: log_prob_class = math.log(self.prob_class[_class]) log_prob_doc = 0 for word in email: prob_given_class = self.prob_word_given_class_backoff[_class] # It would be bad to assume unknown have 0 probability. That would likely # misclassify documents simply because a word wasnt seen during data. if word not in prob_given_class: continue # Just skip log_prob_doc += math.log(prob_given_class[word]) log_score[_class] = log_prob_class + log_prob_doc # Save the prediction prediction = max(log_score.items(), key=operator.itemgetter(1))[0] self.save_score(target, prediction) print(file + &quot;\t&quot; + prediction + &quot;\n&quot;) # Show result self.show_score(which=&quot;accuracy&quot;) def save_score(self, target, prediction): &quot;&quot;&quot;Increase counter[0] when classified correctly else increase counter[1] by 1.&quot;&quot;&quot; self.counter[target==prediction] += 1 def show_score(self, which): &quot;&quot;&quot; Doc string &quot;&quot;&quot; if which == &quot;accuracy&quot;: accuracy = self.counter[0]/(self.counter[0] + self.counter[1]) print(&quot;Accuracy: &quot; + str(accuracy)) # print(self.counter) def fit(self): &quot;&quot;&quot;Estimates probabilities given the frequencies. Then apply backoff smoothing.&quot;&quot;&quot; if self.mode == &quot;test&quot;: params = self.load_parameters() self.prob_word_given_class = params[&quot;prob_word_given_class&quot;] self.prob_word = params[&quot;prob_word&quot;] self.prob_class = params[&quot;prob_class&quot;] self.prob_word_given_class_backoff = params[&quot;prob_word_given_class_backoff&quot;] self.counter = [0,0] # Preliminary counter to count how many times classification is right elif self.mode == &quot;train&quot;: self.count_frequencies() self.estimate_parameters() self.smooth_parameters() def count_frequencies(self): &quot;&quot;&quot;Count word frequencies, word frequencies given the class and class frequencies.&quot;&quot;&quot; for file, _class in self.get_files(): file = os.path.join(os.getcwd(),&quot;train&quot;, _class, file) with open(file, encoding=&quot;latin-1&quot;) as f: email = f.read().split() # Count emails frequencies self.freq_class[_class] += 1 for word in email: self.freq_word_given_class[_class][word] += 1 self.freq_word[word] += 1 def estimate_parameters(self): &quot;&quot;&quot;Estimates the model parameters given the words frequencies.&quot;&quot;&quot; for _class in self.classes: # Estimate probability of word given class: p(w|c) = f(w,c) / sum_w' f(w',c) frequencies = self.freq_word_given_class[_class] _sum = sum(frequencies.values()) self.prob_word_given_class[_class] = {k: v/_sum for k, v in frequencies.items()} # Estimate probability of word: p(w) = f(w) / sum(f(w') _sum = sum(self.freq_word.values()) self.prob_word = {k: v/_sum for k, v in self.freq_word.items()} # Estimate probability of class: p(c) = f(c) / sum(f(c')) _sum = sum(self.freq_class.values()) self.prob_class = {k: v/_sum for k, v in self.freq_class.items()} def smooth_parameters(self): &quot;&quot;&quot;Smoothes the model by Kneser-Ney smoothing.&quot;&quot;&quot; # Calulcate discount factor delta after Kneser/Essen/Ney n = lambda x: sum(list(self.freq_word_given_class[_class].values()).count(x) for _class in self.classes) delta = n(1) / (n(1) + 2*n(2)) # Calulcate relativ frequencies of word given class: r(w|c) = max(0, f(w,c) - delta) / sum_w' f(w',c) for _class in self.classes: _sum = sum(self.freq_word_given_class[_class].values()) # Sum_w' f(w',c) self.rel_freq_word_given_class[_class] = {k: max(0, v - delta) / _sum for k, v in self.freq_word_given_class[_class].items()} # Dynamically calculate backoff factor alpha alpha = lambda _class: 1 - sum(self.rel_freq_word_given_class[_class].values()) # Calulcate discount probability: p(w|c) = r(w|c) + alpha(c)p(w) for _class in self.classes: _alpha, rel_word_freq = alpha(_class), self.rel_freq_word_given_class[_class] self.prob_word_given_class_backoff[_class]= {k: rel_word_freq[k] + _alpha * self.prob_word[k] for k, v in self.prob_word_given_class[_class].items()} def set_arguments(self): &quot;&quot;&quot;Sets variables depending on the mode of model usage.&quot;&quot;&quot; self.paramfile = sys.argv[1] self.data_dir = sys.argv[2] # In train mode parameters are passed vice versa if self.mode == &quot;train&quot;: self.data_dir, self.paramfile = self.paramfile, self.data_dir self.classes = next(os.walk(self.data_dir))[1] def create_class_defaultdict(self): &quot;&quot;&quot;Helper method to create defaultdict of classes.&quot;&quot;&quot; return {_class: defaultdict(int) for _class in self.classes} def get_files(self): &quot;&quot;&quot; Generator object that returns the next file and its corresponding class every time next() is called. &quot;&quot;&quot; for root, dirs, files in os.walk(self.data_dir): for _class in self.classes: if root.endswith(_class): for file in files: yield file, _class def load_parameters(self): with open(self.paramfile, 'rb') as handle: return pickle.load(handle) def save_parameters(self): params = {&quot;prob_word&quot;: self.prob_word, &quot;prob_class&quot;: self.prob_class, &quot;prob_word_given_class&quot;: self.prob_word_given_class, &quot;prob_word_given_class_backoff&quot;: self.prob_word_given_class_backoff} with open(f&quot;{self.paramfile}.pickle&quot;, 'wb') as handle: pickle.dump(params, handle, protocol=pickle.HIGHEST_PROTOCOL) </code></pre> <p><strong>Training call:</strong></p> <pre><code>from model import NaiveBayes import sys if __name__ == &quot;__main__&quot;: assert len(sys.argv) == 3, &quot;Call script as $ python3 test.py paramfile mail-dir&quot; nb = NaiveBayes(mode=&quot;train&quot;) nb.fit() nb.save_parameters() </code></pre> <p><strong>Test/inference call:</strong></p> <pre><code>from model import NaiveBayes import sys if __name__ == &quot;__main__&quot;: assert len(sys.argv) == 3, &quot;Call script as python3 train.py train-dir paramfile&quot; nb = NaiveBayes(mode=&quot;test&quot;) nb.fit() nb.predict() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T14:22:35.590", "Id": "270270", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Naive Bayes spam classifier improvements" }
270270
<p><strong>Edit</strong>: A new and improved version can be found in <a href="https://codereview.stackexchange.com/questions/270439/custom-implementation-to-provide-an-immutable-range-of-a-container-without-copyi">this question</a>, based on the feedback!</p> <hr /> <p>I needed to pass a const reference to part of a <code>std::vector</code> without copy.</p> <p>Some research, particularly <a href="//stackoverflow.com/q/30469063">this SO question</a>, suggested that it is not something supported by default, so I created my own code for it:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iterator&gt; #include &lt;vector&gt; template &lt;typename T&gt; class ConstVectorSubrange{ public: ConstVectorSubrange(typename std::vector&lt;T&gt;::const_iterator start_, uint32 size_) : start(start_) , range_size(size_) { } ConstVectorSubrange(std::initializer_list&lt;typename std::vector&lt;T&gt;::const_iterator&gt; list) : start(*list.begin()) , range_size(std::distance(*list.begin(), *(list.end()-1))) { } const T&amp; operator[](std::size_t index) const{ assert(index &lt; range_size); return *(start + index); } const T&amp; back(void) const{ return *(cend()-1); } std::size_t size(void) const{ return range_size; } const typename std::vector&lt;T&gt;::const_iterator cbegin(void) const{ return start; } const typename std::vector&lt;T&gt;::const_iterator cend(void) const{ return (start + range_size); } private: const typename std::vector&lt;T&gt;::const_iterator start; const uint32 range_size; }; </code></pre> <p>An example of using this would be a member function where not the whole array is visible, although copies are to be avoided:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;vector&gt; class BigData{ std::vector&lt;int&gt; big_array = vector&lt;int&gt;(10000); public: ConstVectorSubrange get_last_five_thousand_elements(){ return{(big_array.cend()-5000), big_array.cend()}; } }; </code></pre> <p>How can this code be improved?</p> <p>Especially considering the iterators might be invalidated after the creation of this object, is there a way to make it safer?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T05:24:11.183", "Id": "533662", "Score": "1", "body": "Some C++ programmers will find the void arguments offensive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T06:12:54.230", "Id": "533663", "Score": "0", "body": "Yes, you are right, and I think I'll remove them in the next version! Do you know why that is by the way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T06:18:47.383", "Id": "533664", "Score": "0", "body": "They are not needed in C++. If they appeared in a header file that may be read by a C compiler, I think it would be fine. But they appear in the middle of templated code. No C compiler is going to read that." } ]
[ { "body": "<h1>You are implementing <code>std::span</code></h1>\n<p>What you are trying to implement is basically C++20's <a href=\"https://en.cppreference.com/w/cpp/container/span\" rel=\"nofollow noreferrer\"><code>std::span</code></a>. It might be worthwhile to look at how it is implemented, and copy its interface if possible, so if you ever want to change the codebase using your class to use <code>std::span</code>, it will be easy.</p>\n<p>I'll also use <code>std::span</code> as a reference and point out differences between it and your class below.</p>\n<h1>Use <code>std::size_t</code> for sizes consistently</h1>\n<p>Use <code>std::size_t</code> instead of <code>uint32</code> for <code>range_size</code>. It is the proper type to store sizes. Another possible alternative is to use <code>std::vector&lt;T&gt;::size_type</code>, so you match exactly what <code>std::vector</code> uses to store sizes.</p>\n<h1>Don't use an initializer list for begin/end pairs</h1>\n<p>The constructor that takes an initializer list does not make sense. If you want a constructor that takes a begin and end iterator pair, just make that explicit:</p>\n<pre><code>ConstVectorSubrange(typename std::vector&lt;T&gt;::const_iterator start, typename std::vector&lt;T&gt;::const_iterator end)\n : start(start)\n , range_size(end - start)\n{ }\n</code></pre>\n<p>With an initializer list, you can pass any number of iterators to the constructor, including an empty initializer list.</p>\n<h1>Add <code>begin()</code> and <code>end()</code> member functions</h1>\n<p>You only implemented <code>cbegin()</code> and <code>cend()</code>, but this is not enough to make range-<code>for</code> work. Add <code>begin()</code> and <code>end()</code> member functions. Note that these should also be <code>const</code> functions of course.</p>\n<p>You can even consider removing <code>cbegin()</code> and <code>cend()</code>; they don't offer any advantage over <code>begin()</code> and <code>end()</code> for your class. Note that <code>std::span</code> also doesn't implement <code>cbegin()</code> and <code>cend()</code>.</p>\n<h1>Be consistent manipulating iterators</h1>\n<p>You used <code>std::distance()</code> to calculate the distance between the start and end iterator passed to the second constructor, but then used arithmetic operators to advance the iterators to a given index or to the end. I would either use arithmetic operators everywhere, or use <code>std::distance</code> <em>and</em> <code>std::next</code> everywhere to manipulate the iterators. The latter is preferred if you want to make your class more generic and have it work for other container types as well.</p>\n<h1>Missing member functions</h1>\n<p>Intertestingly there is a <code>back()</code> function, but no <code>front()</code>? Also consider implementing all the member functions of <code>std::vector</code> where possible, like <code>at()</code>, <code>data()</code>, <code>empty()</code> and <code>rbegin()</code>/<code>rend()</code>. This ensures your subrange can be used as a drop-in replacement for a <code>std::vector</code> as much as possible.</p>\n<p>It might also be interesting to add the extra member functions <code>std::span</code> adds, like <code>first()</code>, <code>last()</code> and <code>subspan()</code>.</p>\n<h1>Making <code>T</code> deducible</h1>\n<p>A big problem with your class is that the compiler isn't able to deduce <code>T</code> from the arguments passed to the constructors, due to the <a href=\"https://en.cppreference.com/w/cpp/language/dependent_name\" rel=\"nofollow noreferrer\">dependent type names</a> being used. There are some ways to fix this. One is to provide <a href=\"https://en.cppreference.com/w/cpp/language/class_template_argument_deduction\" rel=\"nofollow noreferrer\">deduction guides</a>, but this requires C++17. Another way is not to make your class templated on the value type <code>T</code>, but rather on the iterator type. This will also greatly simplify your code, and at the same time make it work for other containers besides <code>std::vector</code>:</p>\n<pre><code>template&lt;typename Iterator&gt;\nclass ConstSubrange {\npublic:\n using T = std::remove_reference_t&lt;std::iter_reference_t&lt;Iterator&gt;&gt;;\n\n ConstSubrange(Iterator start, std::size_t size)\n : start(start), range_size(size) {}\n\n ConstSubrange(Iterator start, Iterator end)\n : start(start), size(std::distance(start, end)) {}\n\n const T&amp; operator[](std::size_t index) const {\n return *std::next(start, index);\n }\n\n const Iterator begin(void) const {\n return start;\n }\n\n ...\nprivate:\n const Iterator start;\n const std::size_t range_size;\n};\n</code></pre>\n<h1>Safety</h1>\n<blockquote>\n<p>Especially considering the iterators might be invalidated after the creation of this object, is there a way to make it safer?</p>\n</blockquote>\n<p>Unfortunately, it's not possible to make a class like yours that provides a &quot;view&quot; on another container and have it protect you against invalidation; C++ just doesn't keep track of dependent lifetimes. Note that even a regular iterator doesn't provide this safety. Either you live with it, or make expensive copies of subranges, or use a programming language that uses garbage collection or has a borrow checker.</p>\n<p>In a way your class is also too strict; it's perfectly fine to have it store regular iterators instead of <code>const_iterator</code>s; this will allow you to modify a subrange of a vector.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T17:20:55.013", "Id": "533630", "Score": "0", "body": "Initializer list is there or a kind of syntactic sugar, aiming to cover `{vec.begin(),vec.end()}`; Is there anything else I can do it with that? I get that it doesn't make any sense, maybe I am missing something." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T17:22:11.743", "Id": "533632", "Score": "0", "body": "should I implement `.begin()` and `.end()` despite the class is supposed to have read-only access to the vector span it was constructed with? IN my case the strictness is for a reason, but for general usage, I'd understand that implementing `begin()` and `end()` would be better.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T19:04:50.940", "Id": "533638", "Score": "1", "body": "instead of `std::advance`, I think `std::next` is appropriate, in case you were referring to the `back()` function. I checked [this question](https://stackoverflow.com/questions/15017065/whats-the-difference-between-stdadvance-and-stdnext) on SO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T19:13:24.027", "Id": "533639", "Score": "0", "body": "I don't understand why can't the compiler deduce `T` from the constructors; Why is that a problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T19:14:07.710", "Id": "533640", "Score": "0", "body": "I appreciate the feedback and learnt from it a lot, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T22:30:13.697", "Id": "533651", "Score": "2", "body": "My suggestion to just use two iterator parameters also allows you to use `{vec.begin(), vec.end()}`. You should always implement `begin()` and `end()`, and make those functions `const` to ensure they also work with a `const` span, and having them return `const` iterators is also perfectly fine. The problem with deduction is that `vector<T>::const_iterator` is not a type but a type *alias*; the actual type of the iterator you pass in is something different (for libstdc++, it's a `__gnu_cxx::__normal_iterator<T*, std::vector<T, std::allocator<T>>>`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T17:52:13.470", "Id": "533880", "Score": "1", "body": "Template argument deduction is not bothered by aliases; it will deduce what you call a `std::string` just fine even though it's really a `std::basic_string< ... >`. The issue with not being able to deduce is because of a *dependent type* and it doesn't know the relationship between the _Iterator_ type and `T` which is used as a template argument for the container and iterator. That's what deduction guides will tell it; e.g. \"look at the Iterator's element type in this case\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T08:09:42.843", "Id": "534063", "Score": "0", "body": "Thank you for the feedback! I'll try to improve it, and since there are many changes I'll post the updated code. Unfortunately `std::iter_reference_t` is c++20 only, and that is a standard I feel that would make the code lose the support of older compilers.. I'm not sure how widely supported is the C++ standard..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T10:06:22.637", "Id": "534066", "Score": "0", "body": "@DavidTóth [`std::iter_reference_t`](https://en.cppreference.com/w/cpp/iterator/iter_t) is equal to `decltype(*std::declval<T&>())`, so you could use that. In general, if you want to use a newer C++ feature but want backwards compatibility, check if the [feature exists](https://en.cppreference.com/w/cpp/feature_test), if not provide your own drop-in replacement." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T16:14:37.133", "Id": "270272", "ParentId": "270271", "Score": "6" } }, { "body": "<p>You are asking how you can guard against invalid iterators; I assume you are most concerned about iterators that have become invalid after the vector had to re-allocate when it outgrew its capacity.</p>\n<p>One solution is to store an index instead of an iterator; as long as the vector doesn't shrink the range will be valid, and its validity can be trivially checked by comparing to the vector's size.</p>\n<p>This is only doable as long as your range class targets exclusively &quot;indexable&quot; containers like vectors (and not maps etc.). Downside: Because you only have an index you'll then also need an additional constructor parameter, a reference of the vector.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T11:00:31.970", "Id": "270287", "ParentId": "270271", "Score": "3" } } ]
{ "AcceptedAnswerId": "270272", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T14:49:05.223", "Id": "270271", "Score": "4", "Tags": [ "c++11", "iterator", "vectors" ], "Title": "Custom implementation to provide an immutable range of a vector without copying it" }
270271
<p>Given 2 values and an array, I must return the minimal distance between the indices of both values, as efficiently as I can in terms of run time and space.</p> <p>This is my solution:</p> <pre><code> public static int minDist (int[] a, int x, int y) { int index_one = a[0]; int index_two = a[0]; for(int i = 0 ; i &lt; a.length ; i++) if(a[i] == x) index_one = i; else if(a[i] == y) index_two = i; return(Math.abs(index_one - index_two)); } </code></pre> <p>I'm not sure it works, especially for extreme cases, but I thought the best way is to run the loop one time and find the index of both numbers.</p> <p>Can I make it more efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T18:54:58.353", "Id": "533637", "Score": "4", "body": "The code finds _some_ distance between `x` and `y`. It is not necessarily minimal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T07:47:38.760", "Id": "533665", "Score": "4", "body": "If you are unsure how well it works, perhaps you should include your unit tests in the question, so it's clear how much of it is known to work, and how much is uncertain. And is that the real layout of your code? Consider re-indenting before asking for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:30:58.643", "Id": "533697", "Score": "1", "body": "I don't think this code works even for the straightforward cases. I'm pretty sure you've fallen prey to the \"no braces = one line\" gotcha. I think you think that the `return` only triggers when the Y value is found. This code will always return `0` because it will always hit the `return` on the first iteration. CodeReview expects that posted code _works_ as intended, which this doesn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T06:22:39.533", "Id": "533755", "Score": "1", "body": "@Flater, the indentation is misleading, as I mentioned. The `return` is after the loop, so it will return the difference between the _last_ X and Y values, by my reasoning. Still not the _least_ difference, and completely weird (meaningless) result if either is not found." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T08:57:08.763", "Id": "533769", "Score": "0", "body": "@TobySpeight: Very good catch, seems like I fell pray to the same classic blunder because I missed it on the `for`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T09:47:13.093", "Id": "533774", "Score": "0", "body": "I think the OP is conflating Java and Python, among other major issues in their thinking." } ]
[ { "body": "<p>This code does not do what you want it to do, there is no check for the <em>minimum</em> distance. I'm not going to review code that does not exist. However, I will review the rest of the code.</p>\n<h2>Naming conventions</h2>\n<ul>\n<li>Variable names should be descriptive. <code>int[] a</code> does not pass that requirement. <code>numbers</code>, <code>values</code> or even just <code>arr</code> would've been better.\n<ul>\n<li>Note that <code>x</code> and <code>y</code> <em>are</em> acceptable here, because the context of the method makes it clear that two numbers are needed, and there is no clear descriptive name available for these numbers.</li>\n</ul>\n</li>\n<li>Try to avoid abbreviations and shortenings in method names. <code>minDist</code> should have been <code>GetMinimumDistance</code>.</li>\n<li>Why use <code>x</code>/<code>y</code> and then use <code>index_one</code>/<code>index_two</code>? Since the index variables specifically refer to the <code>x</code>/<code>y</code> values, <code>index_X</code> and <code>index_Y</code> would've been better.</li>\n</ul>\n<h2>Unbraced blocks</h2>\n<p>The major downfall of this code is the lack of braces. While the compiler does allow it, and IMHO there are <em>some</em> cases where a brace-less block is acceptable, this is not one of those cases. You've chained three brace-less blocks (<code>for</code>, <code>if</code> and <code>if</code>), which I consider to <em>never</em> be a valid case, as it starts becoming more of a decoding challenge for the reader than a coding challenge for the writer.</p>\n<p>Your indentation on the <code>return</code> further misleads the reader, as it gets indented together with the <code>else</code> body. Not only does this suggest to a reader that the <code>return</code> happens inside the <code>else</code>, it also suggests that <em>you think it does</em>.</p>\n<p>Rewritten:</p>\n<pre><code>for(int i = 0 ; i &lt; a.length ; i++) { \n if(a[i] == x) {\n index_one = i;\n }\n else if(a[i] == y) {\n index_two = i;\n }\n}\nreturn Math.abs(index_one - index_two);\n</code></pre>\n<p>This syntax makes the intended flow much clearer to be parsed by a reader.</p>\n<h2>Mixing values and indices</h2>\n<pre><code>int index_one = a[0];\nint index_two = a[0];\n</code></pre>\n<p>I understand that you wanted your variables to have a default value, but there is a difference between an array <em>element</em> and an array <em>index</em>. While in this case both are numeric in nature, they should rarely if ever cross-contaminate.</p>\n<p>Since these variables store indices, it makes no sense to give them the default value of the first <strong>element</strong> of the array.</p>\n<p>I assume you wanted to do this:</p>\n<pre><code>int index_one = 0;\nint index_two = 0;\n</code></pre>\n<p>However, I also disagree with choosing a valid index value here. The problem is that when you only find one (e.g. X) and not the other (e.g. Y), that you then end up returning the index of the found number, not the distance between the two.</p>\n<p>That return value <em>appears</em> to be valid (to the caller) but is totally nonsensical and does not indicate distance whatsoever.</p>\n<p>A more conventional approach here would be to return <code>-1</code> in all cases where a distance cannot be computed (i.e. at least one of the items was not found). This is similar to the <code>indexOf</code> method, which returns <code>-1</code> when the searched for element cannot be found.</p>\n<p><code>-1</code> is a great return code here, because it cannot possible be a correct distance value, since distances are inherently positive numerical values.</p>\n<p>However, now we get back to you using <code>0</code> as the default value for your index variables. Because of this, it is impossible to know whether the algorithm actually found a match (on index 0) or not (and 0 is still the default value). This is no good, because you make it impossible to know the outcome of your own algorithm. It literally defeats its own purpose.</p>\n<p>We can apply the same <code>-1</code> trick here. <code>-1</code> is a better default value, because it clearly indicates that nothing has been found. If, after the <code>for</code>, either index variable is still set to <code>-1</code>, we know for a fact that the corresponding number was not found in the array, and therefore we immediately return <code>-1</code> to indicate that no distance could be calculated.</p>\n<hr />\n<p>Taking all the above review into account, a reworked version of your code would be:</p>\n<pre><code>public static int GetMinimumDistance(int[] values, int x, int y) {\n int index_X = -1;\n int index_Y = -1;\n\n for(int i = 0 ; i &lt; values.length ; i++) { \n if(values[i] == x) {\n index_X = i;\n }\n else if(values[i] == y) {\n index_Y = i;\n }\n }\n\n if(index_X == -1 || index_Y == -1) {\n return -1;\n }\n\n return Math.abs(index_X - index_Y); \n} \n</code></pre>\n<p><em>Just to reiterate, I did not add nor review any &quot;minimum distance&quot; logic, as this was missing from your version as well.</em></p>\n<hr />\n<p>As an aside, there are <a href=\"//stackoverflow.com/q/6171663\">existing ways to find the index of an element in an array</a>. You might want to look into those. As a C# dev I'm surprised that Java does not have a native (and elegant) way of doing this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T09:33:02.533", "Id": "270321", "ParentId": "270273", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T17:14:09.923", "Id": "270273", "Score": "0", "Tags": [ "java", "performance", "array" ], "Title": "Find the minimal distance between two values in an array" }
270273
<p>There are many template engines but my question is: Why do they still exist? Can we not achieve the same job with readily available JavaScript Template Literals?</p> <p>So influenced from <a href="https://2ality.com/2015/01/template-strings-html.html" rel="nofollow noreferrer">this blogpost</a>, I have come up with something as follows. Do you think this is reasonable in daily JavaScript?</p> <p>The following code is pure JavaScript. Lets start with a proper data.</p> <pre><code>var data = { labels: ['ID','Name'] , rows : [ {&quot;id&quot;: &quot;1&quot;, 'name': &quot;richard&quot;} , {&quot;id&quot;: &quot;2&quot;, 'name': &quot;santos&quot;} ] }; </code></pre> <p>Now let's define a <code>tableTemplate</code> function which takes the <code>data</code> and gives us an HTML table.</p> <pre><code>function tableTemplate(data){ return ` &lt;table&gt; &lt;tr&gt; ${data.labels.map(label =&gt; html` &lt;th&gt;&amp;${label}&lt;/th&gt;`).join(&quot;&quot;)} &lt;/tr&gt;${data.rows.map(row =&gt; html` &lt;tr&gt; &lt;td&gt;&amp;${row.id}&lt;/td&gt; &lt;td&gt;&amp;${row.name}&lt;/td&gt; &lt;/tr&gt;`).join(&quot;&quot;)} &lt;/table&gt;`; } </code></pre> <p>So what is this <code>html`</code> thingy and also that <code>&amp;$</code>?</p> <ul> <li>First of all <code>html`</code> is just a generic <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates" rel="nofollow noreferrer">tag function</a> that we define only once and without modifying it, we can use it for all of our template functions.</li> <li><code>&amp;$</code> on the other hand is simple. <code>&amp;</code> is just a simple string character and the second one is the escaping <code>$</code> character for variables in template strings such as <code>${x}</code>. We can use a tag function to validate our HTML code by escaping invalid HTML characters like <code>&amp;</code>, <code>&gt;</code>, <code>&lt;</code>, <code>&quot;</code>, <code>'</code> or <code>`</code>. The version I give below looks a little convoluted but it's really simple and very useful. It basically escapes invalid HTML characters and provides a &quot;raw&quot; version of the template string.</li> </ul> <p>Please follow above links for further information. Here it is:</p> <pre><code>function html(lits,...vars){ var esc = { &quot;&amp;&quot;: &quot;&amp;amp;&quot; , &quot;&gt;&quot;: &quot;&amp;gt;&quot; , &quot;&lt;&quot;: &quot;&amp;lt;&quot; , '&quot;': &quot;&amp;quot;&quot; , &quot;'&quot;: &quot;&amp;#39;&quot; , &quot;`&quot;: &quot;&amp;#96;&quot; }; return lits.raw .reduce( (res,lit,i) =&gt; (res += lit.endsWith(&quot;&amp;&quot;) ? lit.slice(0,-1) + [...vars[i].toString()].reduce((s,c) =&gt; s += esc[c] || c, &quot;&quot;) : lit + (vars[i] || &quot;&quot;)) , &quot;&quot; ); } </code></pre> <p>Now, it's time to put everything together for a working sample. Let's also add <code>&lt;thead&gt;</code> and <code>&lt;tbody&gt;</code> tags and some CSS this time.</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 html(lits,...vars){ var esc = { "&amp;": "&amp;amp;" , "&gt;": "&amp;gt;" , "&lt;": "&amp;lt;" , '"': "&amp;quot;" , "'": "&amp;#39;" , "`": "&amp;#96;" }; return lits.raw .reduce( (res,lit,i) =&gt; (res += lit.endsWith("&amp;") ? lit.slice(0,-1) + [...vars[i].toString()].reduce((s,c) =&gt; s += esc[c] || c, "") : lit + (vars[i] || "")) , "" ); } function tableTemplate(data){ return ` &lt;table&gt; &lt;thead&gt; &lt;tr&gt;${data.labels.map(label =&gt; html` &lt;th&gt;&amp;${label}&lt;/th&gt;`).join("")} &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;${data.rows.map(row =&gt; html` &lt;tr&gt; &lt;td&gt;&amp;${row.id}&lt;/td&gt; &lt;td&gt;&amp;${row.name}&lt;/td&gt; &lt;/tr&gt;`).join("")} &lt;/tbody&gt; &lt;/table&gt;`; } var data = { labels: ['ID','Name'] , rows : [ {"id": 1, 'name': "richard"} , {"id": 2, 'name': "santos"} , {"id": 3, 'name': "&lt;ömer &amp; `x`&gt;"} ] }; document.write(tableTemplate(data));</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>table { background-color: LightPink; border : 0.2em solid #00493E; border-radius : 0.4em; padding : 0.2em } thead { background-color: #00493E; color : #E6FFB6 } tbody { background-color: #E6FFB6; color : #00493E }</code></pre> </div> </div> </p> <p>Obviously you can now insert <code>&lt;style&gt;</code> tag or <code>class=&quot;whatever&quot;</code> attribute into your quasi-HTML template literal in the <code>tableTemplate</code> function just the way you would normally do in an HTML text file.</p> <p>Also please note that if you <code>console.log</code> the resulting HTML text string, thanks to the raw conversion, it would beautifully display (according to your indenting in the <code>tableTemplate</code> function) just like below:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;ID&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;richard&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt;santos&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;317&lt;/td&gt; &lt;td&gt;&amp;lt;ömer &amp;amp; &amp;#39;x&amp;#39;&amp;gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T20:07:45.857", "Id": "533643", "Score": "0", "body": "What does this do? The table looks nothing like `data`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T20:59:00.320", "Id": "533645", "Score": "0", "body": "@Blindman67 Wow i am dealing with a very interesting site related bug here. I can swear that the `tableTemplate` function in the working sandbox is exactly the same one as shown in the second snippet. When i try to edit it just turns back into how i had written it and works just fine until i save it and it shows again that silly hash code `<th>{cbe533db-4533-4fed-934e-f25c95923264}{row.name}</td>`. What's happening..? Perhaps the `$$` is colliding with some parsing library behind the curtain..?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T21:08:38.560", "Id": "533648", "Score": "0", "body": "@Blindman67 Replaced `$$` with `&$` in my code and the sandbox bug is resolved. So.. i guess somebody has to fix something. From this bug only i can conclude that the Stackoverflow and Codereview sandboxes are of different sources or versions of the same source since my code's original form works just fine @ SO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T03:26:26.333", "Id": "533661", "Score": "0", "body": "I just tried adding your code with `$$` and it worked fine,. Most likely something your end (extension or the like) inserting the GUID" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T09:30:25.850", "Id": "533772", "Score": "0", "body": "@Blindman67 I don't think so, as you mention in your first comment it doesn't work fine at your end too. The thing is, when you edit the question and scroll down and click on `edit the above snippet` link and replace `&$`s with `$$`s in the sandbox everything still works just fine but only after you save it with `$$` then things show up awry in the question." } ]
[ { "body": "<p>A short review;</p>\n<p><em>Do you think this is reasonable in daily JavaScript?</em></p>\n<p>Probably not, for a few reasons</p>\n<ul>\n<li><p>You need a function per record type since this wires metadata and styling so tightly</p>\n</li>\n<li><p>There is a ton of HTML tooling out there, none of it will work with embedded html</p>\n</li>\n<li><p>The <code>html</code> function you provide is compacter but less readable than the one in the blog</p>\n</li>\n<li><p>The escaping code seems bare, I prefer to use</p>\n<pre><code> function escapeHtml(html){\n var text = document.createTextNode(html);\n var p = document.createElement('p');\n p.appendChild(text);\n return p.innerHTML;\n }\n</code></pre>\n</li>\n<li><p>If I had to write a templating routine myself I would have gone with</p>\n<pre><code> &lt;table&gt;\n &lt;head&gt;\n &lt;tr id=&quot;id&quot;&gt;&lt;/tr&gt;\n &lt;tr id=&quot;name&quot;&gt;&lt;/tr&gt;\n &lt;/thead&gt;\n &lt;body&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n</code></pre>\n</li>\n</ul>\n<p>and call something like</p>\n<pre><code> tableTemplate(template, {&quot;id&quot;:&quot;ID&quot;,&quot;name&quot;:&quot;Name&quot;}, rows);\n</code></pre>\n<p>Which would have mapped the row labels to the proper id, and then put the data in the proper columns based off the location of the corresponding header id.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T12:42:51.527", "Id": "270326", "ParentId": "270275", "Score": "2" } }, { "body": "<blockquote>\n<p>There are many template engines but my question is: Why do they still exist? Can we not achieve the same job with readily available JavaScript Template Literals?</p>\n</blockquote>\n<p>Sure, that seems like it would work ok for smaller projects, especially if you remember to keep to the <a href=\"https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html\" rel=\"nofollow noreferrer\">string encoding guidelines to prevent XSS attacks</a>. From my quick glance over your function, I don't see any security issues with how you're encoding strings.</p>\n<p>Many templating libraries were popularized before template literals existed. Had template literals existed earlier, I wouldn't be surprised if these libraries would have been made to support them from the start, though, perhaps they continue to not support them because they like keeping the HTML outside of your business logic.</p>\n<hr />\n<p>I'll go ahead and point out some potential design considerations you can think about.</p>\n<p>It's pretty easy to accidentally forget to precede an interpolated value with an &quot;&amp;&quot; character, which could cause the interface to be buggy, or worse, open up XSS issues. One option would be to make string-escaping the default behavior and require putting a special character before an interpolated value to explicitly state that you trust the interpolated content, and are ok with it getting inserted into the template literal untouched.</p>\n<p>Another option would be to have the interpolated values take object literals, which explains what kind of encoding you want to be performed. This could help make things more readable, especially if you want to support other forms of encoding in the future. For example:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>html`\n &lt;div id=&quot;${{ attr: 'All attr-unsafe characters will be encoded' }}&quot;&gt;\n &lt;p&gt;${{ content: 'All content-unsafe characters will be encoded' }}&lt;/p&gt;\n ${{ raw: 'This string will be added, unchanged' }}\n &lt;/div&gt;\n`\n</code></pre>\n<p>I'm not saying you should or should not switch to one of these options, just pointing out some alternative options to consider.</p>\n<p>One more option (this one's my favorite), is to not ever use template literals. For small projects, I like to use this very simple helper function:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function el(tagName, attrs = {}, children = []) {\n const newElement = document.createElement(tagName)\n for (const [key, value] of Object.entries(attrs)) {\n newElement.setAttribute(key, value)\n }\n newElement.append(...children)\n return newElement\n}\n</code></pre>\n<p>This allows you to use function calls to construct your HTML content. Because it's using native browser APIs, you won't have to worry about hand-writing escaping logic either, since the browser will automatically escape your data (even still, don't do something stupid like putting untrusted data into a script tag).</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function el(tagName, attrs = {}, children = []) {\n const newElement = document.createElement(tagName)\n for (const [key, value] of Object.entries(attrs)) {\n newElement.setAttribute(key, value)\n }\n newElement.append(...children)\n return newElement\n}\n\nconst renderTable = data =&gt;\n el('table', { id: 'my-table' }, [\n el('thead', {}, [\n el('tr', {}, [\n ...data.labels.map(renderTableHeader),\n ]),\n ]),\n el('tbody', {}, [\n ...data.rows.map(renderRow)\n ]),\n ]);\n\nconst renderTableHeader = label =&gt;\n el('th', {}, [label])\n \nconst renderRow = ({ id, name }) =&gt;\n el('tr', {}, [\n el('td', {}, [id]),\n el('td', {}, [name]),\n ])\n\nvar data = { labels: ['ID','Name']\n , rows : [ {\"id\": 1, 'name': \"richard\"}\n , {\"id\": 2, 'name': \"santos\"}\n , {\"id\": 3, 'name': \"&lt;ömer &amp; `x`&gt;\"}\n ]\n };\n\ndocument.getElementById('main')\n .appendChild(renderTable(data))</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#my-table {\n background-color: LightPink;\n border : 0.2em solid #00493E;\n border-radius : 0.4em;\n padding : 0.2em\n }\nthead {\n background-color: #00493E;\n color : #E6FFB6\n }\ntbody {\n background-color: #E6FFB6;\n color : #00493E\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"main\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T12:26:54.927", "Id": "533912", "Score": "0", "body": "Thank you for your nice reply. I agree mostly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T03:34:40.110", "Id": "270374", "ParentId": "270275", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T18:04:09.457", "Id": "270275", "Score": "2", "Tags": [ "javascript", "template" ], "Title": "Using JS Template Literals as for a simple Templating Engine" }
270275
<pre><code>/// #include &lt;stdio.h&gt; void ConvertNumberToBinary(int Number, int *Array) { for(int I = 0; I &lt; 32; ++I) { int ZeroOrOne = Number%2; if(ZeroOrOne &lt; 0) { ZeroOrOne = 1; } *(Array + I) = ZeroOrOne; Number = (Number &gt;&gt; 1); } } int main() { int Number = 5; int NumberInBinary[32] = {}; ConvertNumberToBinary(Number, NumberInBinary); return(0); } /// </code></pre> <p>A way to convert a number to binary is to use the mod operator, this thing -&gt; % will give you the remainder of a divide for whole numbers. For example (4%3) will give you a remainder of 1. (3 goes into 4 one time, there is a remainder of 1 since 1 can't be divided by 3)</p> <p>What's really useful about mod in solving this problem is it can effectively tell you the least-significant bit of any number in binary. The least significant bit representing 2^0 or 1 when turned on.</p> <p>In order to do this all you have to do is divide any number by 2 and the remainder of that divide will either give you ZeroOrOne which maps directly to the least significant bit of any binary number.</p> <pre><code>I.e 000011001 ^ Any number Mod by 2 (Number%2) will tell you the value for this bit </code></pre> <p>So in the code that's exactly what happens, we pass in a Number to the &quot;ConvertNumberToBinary&quot; function and once we start looping through our array of numbers, we take the Number we passed in, we Mod it by 2, and store that remainder in the ZeroOrOne variable, the we write to the array using that variable.</p> <p>A second thing we do is we take the number and shift it down by one to remove the least-significant bit so we can see the data for the next bit.</p> <pre><code>Here's the steps viewing the number 5 in binary 0101 ^ This Number%2 will be 1, we store that in the array, then we shift 0010 --- 1 &lt; This 1 has been shifted out ^ We now mod this by 2 and check its value, it is zero, we store zero into the array then shift 0001 --- 0 &lt; This 0 has been shifted out ^ We mod by two again and get 1, we store that in the array, then we shift. 0000 --- 1 &lt; This 1 has been shifted out --- Repeat until it's been done 32 times --- Reach the end of the loop then break out of the function and the array will have the result in binary (it will be in little endian though - least significant bit will be the first array element) </code></pre> <p>And that's everything so far, two things to mention though, the function only works for arrays greater than 32 elements, otherwise it will break.</p> <p>And the other thing is this code</p> <pre><code>if(ZeroOrOne &lt; 0) { ZeroOrOne = 1; } </code></pre> <p>If you pass in a negative number and mod it by two there will be a remainder, but the remainder will be -1 which isn't a binary value, so I just set ZeroOrOne to 1 if it was negative</p>
[]
[ { "body": "<h1>Formatting conventions</h1>\n<p>It is your program and you are free to format it any way you want to, but sticking to conventions makes it easier for others to read.</p>\n<p>I personally prefer my function definitions and <code>for</code> loops on one line unless they are very long. Most people use either camelCase or snake-case with variables starting with a lower case letter.</p>\n<h1>ZeroOrOne</h1>\n<p>If you used an <code>unsigned int</code> for <code>Number</code> then you would not have to worry about it being negative and simplified it to the following:</p>\n<pre><code>*(Array + I) = Number % 2;\n</code></pre>\n<h1>std::bitset</h1>\n<p>Since C++11 we can use <code>std::bitset</code> do all of this for us very neatly like the following:</p>\n<pre><code>#include &lt;bitset&gt;\n\nint main()\n{\n std::bitset&lt;32&gt; bs(5);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T22:32:36.303", "Id": "533652", "Score": "0", "body": "Thanks for the feedback, I'll keep those things in mind if I create another one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T22:32:58.403", "Id": "533653", "Score": "0", "body": "I'm curious why you're recommending division by 2 as \"showing intention\", when the intention is to move to the next bit, not so much to halve the number" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T22:44:47.297", "Id": "533655", "Score": "0", "body": "@harold, I'm thinking of a `base` like in the following: [TIO](https://tio.run/##XU5LCoMwEN3PKQZLQTFSa1so/k7SjcYogZqIid0Uz24TA4p9m5m8z7zQYYg6SpflxAV9Tw3DvOZaMV3CznCp9MiqvgT4SN5gK6U/CcU7wRrkQqOYeoIHpq4U@6OonIQO4Ato0MoRjzc4FhhnZuTOadYwDFazi1go3aSpkTXmuW3F89pkX95LeNlmtNqlWEVHzjADgC3qKy78/R/SfxBMCD4DZzxUeNGO7b7NJLc7wWtM8GZi87L8AA), but I get what you are saying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T22:46:50.173", "Id": "533656", "Score": "0", "body": "OK, fair enough" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T22:07:59.117", "Id": "270279", "ParentId": "270278", "Score": "1" } }, { "body": "<p>Don't use raw pointers like this, especially when they're not accompanied by a size. It's a recipe for disaster.</p>\n<p>Instead of going the arithmetic route and dividing by two repeatedly you can make use of the property of the internal representation of two's complement. I find this more direct, elegant and easier to read.</p>\n<p>Don't limit yourself to ints, we have a wonderful template system that can make choose like this more generic with ease.</p>\n<p>Your code gives the wrong output for negative numbers, it returns a positive number. This is confusing, I recommend you either return error on a negative input, forbid negative inputs by taking only unsigned, output the two's complement or a negative sign is returned somehow.</p>\n<p>The final code would be (prohibiting negative numbers by using unsigned in this case):</p>\n<pre><code>template&lt;class T&gt;\nvoid dec2bin_lsb_first(unsigned T v, std::vector&lt;char&gt;&amp; output){\n for(int i=0; i &lt; std::numeric_limits&lt;unsigned T&gt;::digits(); i++){\n output.emplace_back(v&amp;1);\n v &gt;&gt;= 1;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T15:21:33.270", "Id": "533710", "Score": "0", "body": "\"Your code gives the wrong output for negative numbers, it returns a positive number.\" Hmm I tested it with a debugger and it still works fine? I just noticed though that if you do a (divide by 2) instead of a (bit-shift >> by 1) to move the bits down for a negative number then It will produce the positive binary representation of that number in the array. In the original post though, I'm not dividing negative numbers to move bits down so Idk how you got positive binary numbers in the array when passing negative numbers to the function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T18:19:41.563", "Id": "533815", "Score": "0", "body": "What I meant is, getting a positive result of a negative input to a conversion is surprising and seemingly wrong." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T02:56:29.123", "Id": "270283", "ParentId": "270278", "Score": "2" } }, { "body": "<p>I would update Emily L's answer in the following ways:</p>\n<ul>\n<li>return values should be returned, not using &quot;out&quot; parameters.</li>\n<li>It is not &quot;decimal to binary&quot;. It is an integer in internal form, which is in no way &quot;decimal&quot;.</li>\n<li>use <code>uint8_t</code>, or if using a <code>char</code> actually store <code>'0'</code> and <code>'1'</code> rather than <code>0</code> and <code>1</code>.</li>\n<li>prefer prefix increment.</li>\n</ul>\n<p>You don't need to explain to us how formatting a number in some base works. Though, your explanation does help us know your level of understanding at this point.</p>\n<p>To clarify the second point above: you are not &quot;converting&quot; a number to binary. You are <em>formatting</em> a number into a binary representation. Normally this is done to produce a string, not an array of integers. The native number is an abstraction, not a text string in any base. Though, you can be aware that the internal representation in the CPU is in fact binary: you are doing this with the use of <code>&gt;&gt;</code> instead of <code>/2</code>, though you are staying abstract with <code>%2</code>.</p>\n<p>It might be instructive to have your function format a number as <em>any</em> base. Then you will stick to the abstraction of the native number as &quot;an integer&quot; not a group of bits, and it provides a rationale as to why you return an array of small numbers rather than a string: another function will assign character representation to the digits, taking care of what to do with bases &gt; 10, or Chinese digits etc.</p>\n<p>The function would look like this:</p>\n<pre><code>template &lt;typename T&gt;\nstd::vector&lt;uint8_t&gt; express_as_base (T number, uint8_t base)\n{\n std::vector&lt;uint8_t&gt; result;\n if (number &lt; 0) {\n number= -number;\n result.push_back(255); // special flag indicates negative\n }\n while (number) {\n const auto digit= number % base;\n number /= base;\n result.push_back (digit);\n }\n return result;\n}\n</code></pre>\n<hr />\n<p>More note on your original code:<br />\n<code> return(0);</code><br />\nDon't put extra parens around your return value. <code>return</code> is not a function call! Besides being idiomatic (different things should look different), habitually using these extra parens can actually mean something different as of C++11. It will suppress automatically using <code>move</code> when returning a suitable local value, and for some kinds of templates, changes the deduced value category for the return type.</p>\n<p>You never use anything from <code>&lt;stdio.h&gt;</code>. And if you were, you should be using <code>&lt;cstdio&gt;</code> instead. And you should really be using the C++ library functions, not the old C library.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T16:22:09.710", "Id": "533716", "Score": "0", "body": "\"You never use anything from <stdio.h>.\" Oh lol, I thought you needed stdio.h to define main(). I never asked myself why that would be correct so out of habit I would include stdio.h whenever I write main(). Same with windows.h and WinMain()." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T15:21:04.927", "Id": "270297", "ParentId": "270278", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T20:49:48.430", "Id": "270278", "Score": "0", "Tags": [ "c++", "bitwise", "binary" ], "Title": "Converting whole numbers to binary in C/C++" }
270278
<h3>The feature</h3> <p>Here is a Grid class representing a 2d grid.<br /> The class will get templated once it reach a satisfactory state.<br /> At this time the cells are <code>int</code> values.</p> <p>This Grid class allow for iteration by rows using simple range-for syntax.</p> <pre><code> Grid grid(8, 8); for (auto&amp;&amp; row_it : grid.Rows()) { for (auto&amp;&amp; cell : row_it) std::cout &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; cell &lt;&lt; ','; std::cout &lt;&lt; '\n'; } </code></pre> <h3>The retrospective</h3> <p>It works well, but it is my first time creating custom iterators and I do not think that its is nicely done.</p> <p>More in particular:</p> <ul> <li>Are the classes <code>GridRows</code>, <code>RowsIterator</code> and <code>RowIterator</code> really needed?</li> <li>The range-for will automatically call <code>operator*</code> on the type returned from begin(), which seems to force the existence of <code>RowIterator</code> instead of returning directly an int* from <code>RowsIterator::begin</code></li> <li>How best to minimize and simplify?</li> </ul> <h3>Standard library compatibility</h3> <p>According to this article, custom iterators should include the following properties: <a href="https://www.internalpointers.com/post/writing-custom-iterators-modern-cpp" rel="nofollow noreferrer">https://www.internalpointers.com/post/writing-custom-iterators-modern-cpp</a></p> <ul> <li>iterator_category</li> <li>difference_type</li> <li>value_type</li> <li>pointer</li> <li>reference</li> </ul> <h3>The complete code</h3> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; struct RowIterator { int* _it, * _end; RowIterator(int* begin, int* end) : _it{ begin }, _end{ end } {} int&amp; operator*() { return *_it; } int* operator-&gt;() { return _it; } RowIterator&amp; operator++() { ++_it; return *this; } RowIterator operator++(int) { auto self = *this; ++* this; return *this; } friend bool operator==(RowIterator lhs, RowIterator rhs) { return lhs._it == rhs._it; } friend bool operator!=(RowIterator lhs, RowIterator rhs) { return lhs._it != rhs._it; } int* begin() { return _it; } int* end() { return _end; } }; struct RowsIterator { int* _it, * _end; int _row_length; RowIterator _row_begin, _row_end; RowsIterator(int* begin, int row_length) : _it{ begin }, _end{ begin + row_length }, _row_length{ row_length }, _row_begin{ _it, _end }, _row_end{ _end, _end } {} RowIterator&amp; operator*() { return _row_begin; } RowIterator* operator-&gt;() { return &amp;_row_begin; } RowsIterator&amp; operator++() { _it += _row_length; _end += _row_length; _row_begin = { _it, _end }; _row_end = { _end, _end }; return *this; } RowsIterator operator++(int) { auto self = *this; ++* this; return *this; } friend bool operator==(RowsIterator lhs, RowsIterator rhs) { return lhs._it == rhs._it; } friend bool operator!=(RowsIterator lhs, RowsIterator rhs) { return lhs._it != rhs._it; } RowIterator begin() const { return _row_begin; } RowIterator end() const { return _row_end; } }; struct GridRows { RowsIterator _begin, _end; GridRows(int* begin, int* end, int row_length) : _begin{ begin, row_length }, _end{ end, row_length } {} RowsIterator begin() { return _begin; } RowsIterator end() { return _end; } }; struct Grid { Grid(int width, int height) : _width{ width }, _height{ height } { size_t size = width * height; _begin = new int[size]; _end = _begin + size; InitializeValues(); } ~Grid() { if (_begin) { delete[] _begin; _begin = nullptr; _end = nullptr; } } void InitializeValues() { for (int i = 0; auto &amp;&amp; it : *this) it = ++i; } int* begin() const { return _begin; } int* end() const { return _end; } GridRows Rows() const { return GridRows{ _begin, _end, _width }; } int* _begin, * _end; int _width, _height; }; void IterateWithFor(const Grid&amp; grid) { std::cout &lt;&lt; &quot;Iterate though all rows cells\n&quot;; auto&amp;&amp; rows = grid.Rows(); for (auto&amp;&amp; row_it = rows.begin(); row_it != rows.end(); ++row_it) { for (auto&amp;&amp; cell = row_it.begin(); cell != row_it.end(); ++cell) { std::cout &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; *cell &lt;&lt; ','; } std::cout &lt;&lt; '\n'; } std::cout &lt;&lt; '\n'; } void IterateWithRangeFor(const Grid&amp; grid) { std::cout &lt;&lt; &quot;Iterate though all rows cells\n&quot;; for (auto&amp;&amp; row_it : grid.Rows()) { for (auto&amp;&amp; cell : row_it) std::cout &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; cell &lt;&lt; ','; std::cout &lt;&lt; '\n'; } std::cout &lt;&lt; '\n'; } int main() { Grid grid(8, 8); IterateWithFor(grid); IterateWithRangeFor(grid); return 0; } </code></pre> <h3>Thank you</h3> <p>Thank you very much for your time and valuable feedback.</p>
[]
[ { "body": "<blockquote>\n<pre><code>RowIterator operator++(int)\n{\n auto self = *this;\n ++* this;\n return *this;\n}\n</code></pre>\n</blockquote>\n<p>We should be returning the previous value (<code>self</code>), rather than <code>*this</code>.</p>\n<hr />\n<p><code>Grid</code> owns storage using a raw pointer, so needs copy/move constructor and assignment operations. Or better, use a <code>std::vector</code> instead of <code>int*</code> to take care of that automatically.</p>\n<hr />\n<p>Use <code>std::size_t</code> for width and height, rather than <code>int</code>. That way, we don't need to check that they are not negative.</p>\n<hr />\n<p>The iterators are missing the necessary type names to be used with standard algorithms. You even mention that in the question, so fix that immediately.</p>\n<hr />\n<p>Iterator's <code>operator==</code> can be defined <code>= default</code>, and that will also default <code>!=</code>.</p>\n<hr />\n<blockquote>\n<pre><code>RowIterator begin() const\n{\n return _row_begin;\n}\n</code></pre>\n</blockquote>\n<p>That's dangerous - we should be returning a const-iterator when the object is const. Also consider implementing the other (const/reverse) begin/end functions.</p>\n<hr />\n<blockquote>\n<pre><code>~Grid()\n{\n if (_begin) …\n}\n</code></pre>\n</blockquote>\n<p>I don't see any way that <code>_begin</code> could be false here.</p>\n<hr />\n<blockquote>\n<pre><code>int* begin() const { return _begin; }\nint* end() const { return _end; }\n</code></pre>\n</blockquote>\n<p>Again, we need to sort out the const-correctness here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T03:56:04.150", "Id": "533892", "Score": "0", "body": "Thank you, I am still working on simplifying it and its taking some time. I will post a new version when its ready. Your comments have been integrated." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T08:24:22.837", "Id": "270284", "ParentId": "270281", "Score": "1" } } ]
{ "AcceptedAnswerId": "270284", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T00:46:01.483", "Id": "270281", "Score": "2", "Tags": [ "c++", "array", "iterator", "c++20" ], "Title": "2d Grid - Iterating by Rows / Cells" }
270281
<p>At the moment, it is simply massive. I already reduced the size by about a hundred lines but it still seems way too big... Would appreciate some help :)</p> <pre><code>using System; class Program { static int turns = 1; static int player = 2; static char[] board = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' }; static char playerSignature = 'X'; private static void Introduction() { Console.WriteLine(&quot;This is a simple TicTacToe game. Enter y if you have played before and n if you are new to this.&quot;); string input1 = &quot; &quot;; while (input1 != &quot;y&quot; || input1 != &quot;n&quot;) { input1 = Console.ReadLine(); switch (input1) { case &quot;y&quot;: Console.WriteLine(&quot;Alright, let's get started, you are X, your friend is O.&quot;); DrawBoard(board); break; case &quot;n&quot;: Console.WriteLine(&quot;TicTacToeRules:&quot;); Console.WriteLine(&quot;1. The game is played on a grid that's 3 squares by 3 squares.&quot;); Console.WriteLine(&quot;2. You are X, your friend is O. Players take turns putting their marks in empty squares.&quot;); Console.WriteLine(&quot;3. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.&quot;); Console.WriteLine(&quot;4. When all 9 squares are full, the game is over.&quot;); Console.WriteLine(&quot;If you have read the rules, press any key to continue.&quot;); Console.ReadKey(); Console.Clear(); DrawBoard(board); break; default: Console.WriteLine(&quot;Please enter y/n.&quot;); break; } } } private static void DrawBoard(char[] board) { string row = &quot;| {0} | {1} | {2} |&quot;; string sep = &quot;|___|___|___|&quot;; Console.WriteLine(&quot; ___ ___ ___ &quot;); Console.WriteLine(row, board[0], board[1], board[2]); Console.WriteLine(sep); Console.WriteLine(row, board[3], board[4], board[5]); Console.WriteLine(sep); Console.WriteLine(row, board[6], board[7], board[8]); Console.WriteLine(sep); } private static void Reset() { char[] reset = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' }; board = reset; DrawBoard(board); } private static void Draw() { Console.WriteLine(&quot;It's a draw!\n&quot; + &quot;Press any key to play again.&quot;); Console.ReadKey(); Reset(); } public static void Main() { Introduction(); while (true) { bool isrow = false; bool iscol = false; int row = 0; int col = 0; while (!isrow) { Console.WriteLine(&quot;Choose a row (1-3): &quot;); try { row = Convert.ToInt32(Console.ReadLine()); } catch { Console.WriteLine(&quot;Please enter a number between 1 and 3.&quot;); } if (row == 1 || row == 2 || row == 3) { isrow = true; } else { Console.WriteLine(&quot;\nInvalid row!&quot;); } } while (!iscol) { Console.WriteLine(&quot;Choose a column (1-3): &quot;); try { col = Convert.ToInt32(Console.ReadLine()); } catch { Console.WriteLine(&quot;Please enter a number between 1 and 3.&quot;); } if (col == 1 || col == 2 || col == 3) { iscol = true; } else { Console.WriteLine(&quot;\nInvalid column!&quot;); } } int[] input = { row, col }; if (player == 2) { player = 1; XorO(player, input); } else { player = 2; XorO(player, input); } DrawBoard(board); Win(); turns++; if (turns == 10 &amp;&amp; (board[0] == playerSignature &amp;&amp; board[1] == playerSignature &amp;&amp; board[2] == playerSignature &amp;&amp; board[3] == playerSignature &amp;&amp; board[4] == playerSignature &amp;&amp; board[5] == playerSignature &amp;&amp; board[6] == playerSignature &amp;&amp; board[7] == playerSignature &amp;&amp; board[8] == playerSignature)) { Draw(); } } } private static void XorO(int player, int[] input) { playerSignature = (player == 1) ? 'X' : 'O';//if player ==1 dann ps = 'X', else 'O' int index = ((input[0] - 1) * 3) + (input[1] - 1);//3 - 1 = 2 , 2*3 = 6 + 2 = 8 für 3 3 | compact layout if (board[index] == ' ') { board[index] = playerSignature; } else { Console.WriteLine(&quot;That spot is already taken! Try again!&quot;); } } private static void Win() { if ((board[6] == playerSignature &amp;&amp; board[4] == playerSignature &amp;&amp; board[2] == playerSignature || board[0] == playerSignature &amp;&amp; board[4] == playerSignature &amp;&amp; board[8] == playerSignature) || (board[0] == playerSignature &amp;&amp; board[1] == playerSignature &amp;&amp; board[2] == playerSignature || board[3] == playerSignature &amp;&amp; board[4] == playerSignature &amp;&amp; board[5] == playerSignature || board[6] == playerSignature &amp;&amp; board[7] == playerSignature &amp;&amp; board[8] == playerSignature) || (board[0] == playerSignature &amp;&amp; board[3] == playerSignature &amp;&amp; board[6] == playerSignature || board[1] == playerSignature &amp;&amp; board[4] == playerSignature &amp;&amp; board[7] == playerSignature || board[2] == playerSignature &amp;&amp; board[5] == playerSignature &amp;&amp; board[8] == playerSignature)) { if (player == 1) { Console.WriteLine(&quot;Congratulations Player 1, you win!\n&quot;); Console.WriteLine(&quot;Play again? y/n.&quot;); Playagain(); } else if (player == 2) { Console.WriteLine(&quot;Congratulations Player 2, you win!\n&quot;); Console.WriteLine(&quot;Play again y/n?&quot;); Playagain(); } } } private static void Playagain() { string input2 = &quot; &quot;; input2 = Console.ReadLine(); if (input2 == &quot;y&quot;) { Reset(); Console.Clear(); } else if (input2 == &quot;n&quot;) { Console.Clear(); Console.WriteLine(&quot;Close the window to exit the game.&quot;); Console.ReadKey(); } else { Console.WriteLine(&quot;Please enter y/n.&quot;); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T13:08:31.330", "Id": "533683", "Score": "2", "body": "There is a bug in `Introduction` method, the condition `input1 != \"y\" || input1 != \"n\"` is always true the game never start" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T13:12:21.607", "Id": "533685", "Score": "0", "body": "yes, I noticed. I fixed that by adding the following at the end of the while loop: `if(input1== \"n\" || input1 == \"y\") { break; }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T13:28:17.747", "Id": "533687", "Score": "0", "body": "@morloq, change it to `while (input1 != \"y\" && input1 != \"n\")`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T13:32:45.263", "Id": "533688", "Score": "0", "body": "why does that work better? I don't really get it sorry" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T13:33:04.520", "Id": "533689", "Score": "0", "body": "I suppose using \"break;\" isn't the best idea?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:21:16.173", "Id": "533691", "Score": "2", "body": "@morloq _\"why does that work better?\"_ A given value can never be equal to two different values at the same time. I'm thinking of a number. It could be equal to 1. It could be equal to 2. It could be equal to neither 1 nor 2. But it can **never** be equal to _both_ 1 and 2. Let's re-read your logic: `input1 != \"y\" || input1 != \"n\"` Since it's impossible for `input1` to be equal to both \"y\" and \"n\" at the same time, this means that at least one of these is always true; and when you use `||` and at least one value is `true`, then the result is always `true`. It helps to work this out on paper." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:23:29.540", "Id": "533692", "Score": "0", "body": "You can always check other TT implementations in C# : https://codereview.stackexchange.com/questions/tagged/tic-tac-toe+c%23" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:24:11.077", "Id": "533693", "Score": "1", "body": "Frame challenge: the aim of improving your code is not to shorten it. Shortening _might_ be what happens when the code gets improved, but it also might not be. Line count is not a good measure for code quality and should not be the ultimate goal of a code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:24:47.477", "Id": "533694", "Score": "0", "body": "@Flater, using break as I mentioned would be a bad idea? Or is considered bad practice as the while loop is ineffective to begin with?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:25:49.900", "Id": "533695", "Score": "1", "body": "@morloq: Your `break` is a band aid on a bad logical construct. It is better to fix the bad logical construct as opposed to relying on the band aid. Even if it works, it's very unreadable and needlessly complicates your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:29:47.140", "Id": "533696", "Score": "0", "body": "@Flater, so as input1 != \"y\" || input1 != \"n\" is always true, the loop executes endlessly right? But input1 != \"y\" || input1 != \"n\" is always false since it is impossible for input1 to cover both at the same time? So if it is always false, why doesn't it execute endlessly as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:35:28.020", "Id": "533698", "Score": "0", "body": "@morloq: You're not reading your code correctly. What you _say_ would match with `input1 == \"y\" || input1 == \"n\"`, but your code uses `!=`. To alleviate this confusion, it's better to work this out for yourself. Manually figure out what `input1 != \"y\" || input1 != \"n\"` results in when `input1` is equal to \"a\". Then work it out for `input1` equal to \"y\". Then work it out for `input1` equal to \"n\". You'll notice that it is always true. Now ask yourself for which value of `input1` you expect your logic to be `false`. Then test with that value. You will _never_ find a value that returns false." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:40:17.923", "Id": "533699", "Score": "0", "body": "sorry, I meant whether`input1 != \"y\" && input1 != \"n\"` is always false?" } ]
[ { "body": "<p>There are a couple of issues that we need to address before we can start looking at ways to simplify the code.</p>\n<p>As already mentioned in the comments, you should modify the following line in <code>Introduction</code> to prevent an infinite loop:</p>\n<pre><code>while (input1 != &quot;y&quot; &amp;&amp; input1 != &quot;n&quot;)\n</code></pre>\n<p>There is another problem with <code>XorO</code>. This checks if the space is empty but the program does not do anything with this information and just continues. I would suggest that you modify it to the following:</p>\n<pre><code>private static bool XorO(int player, int[] input)\n{\n playerSignature = player == 1 ? 'X' : 'O';\n int index = ((input[0] - 1) * 3) + (input[1] - 1);\n if (board[index] == ' ')\n {\n board[index] = playerSignature;\n return true;\n }\n else\n {\n Console.WriteLine(&quot;That spot is already taken! Try again!&quot;);\n return false;\n }\n}\n</code></pre>\n<p>And then modify <code>Main</code> with <code>GetNumber</code> as suggested by @Ibram to the following:</p>\n<pre><code>public static void Main()\n{\n Introduction();\n while (true)\n {\n int row = GetNumber(1, 3, &quot;Choose a row (1-3): &quot;);\n int col = GetNumber(1, 3, &quot;Choose a col (1-3): &quot;);\n int[] input = { row, col };\n if (XorO(player, input) == true)\n {\n DrawBoard(board);\n // ...\n player = player == 1 ? 2 : 1;\n }\n }\n}\n</code></pre>\n<h1>void Win()</h1>\n<p>Here you could have created a variable with a smaller name just to make it a bit more readable. You are also missing some parenthesis in some of the comparisons.</p>\n<p>You also do not need separate code to write the messages for players 1 and 2:</p>\n<pre><code>private static void Win()\n{\n char sig = playerSignature;\n // rows\n if ((board[0] == sig &amp;&amp; board[1] == sig &amp;&amp; board[2] == sig) ||\n (board[3] == sig &amp;&amp; board[4] == sig &amp;&amp; board[5] == sig) ||\n (board[6] == sig &amp;&amp; board[7] == sig &amp;&amp; board[8] == sig) ||\n // columns\n (board[0] == sig &amp;&amp; board[3] == sig &amp;&amp; board[6] == sig) ||\n (board[1] == sig &amp;&amp; board[4] == sig &amp;&amp; board[7] == sig) ||\n (board[2] == sig &amp;&amp; board[5] == sig &amp;&amp; board[8] == sig) ||\n // diagonals\n (board[0] == sig &amp;&amp; board[4] == sig &amp;&amp; board[8] == sig) ||\n (board[6] == sig &amp;&amp; board[4] == sig &amp;&amp; board[2] == sig))\n {\n Console.WriteLine(&quot;Congratulations Player {0}, you win!\\n&quot;, player);\n Console.WriteLine(&quot;Play again? y/n.&quot;);\n Playagain();\n }\n}\n</code></pre>\n<h1>Program structure</h1>\n<p>Think of your <code>Main</code> function as the scaffolding of your program. I would suggest that you try to implement it around the following functions:</p>\n<pre><code>public static void PlayGame()\n{\n InitGame();\n bool done = false;\n char player = 'X';\n while (done == false)\n {\n PrintBoard();\n GetInput(player);\n UpdateBoard();\n if (CheckWin(player))\n {\n PrintWinMessage(player);\n done = true;\n }\n else if (CheckDraw())\n {\n PrintDrawMessage(player);\n done = true;\n }\n player = TogglePlayer(player);\n }\n}\n\npublic static void Main()\n{\n PrintWelcomeMessage();\n if (PromptNewUser() == true)\n PrintInstructions();\n bool newgame = true;\n while (newgame)\n {\n PlayGame();\n newgame = PromptNewGame();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:46:05.297", "Id": "533701", "Score": "0", "body": "oh I think I get it now. So lets say instead I use what you proposed ( && instead of ||), that turns false as soon as the users enters y or n right? and therefore the loop ends. so at the beginning of the while loop the condition willl be true as input1 is still empty and therefore neither n or y. But after entering something it will eventually be n or y and so the condition of the while loop will turn false and the loop ends?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:47:38.983", "Id": "533702", "Score": "0", "body": "@morloq, That is it!." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:41:12.720", "Id": "270292", "ParentId": "270285", "Score": "2" } }, { "body": "<p>The following piece has a redundant logic and violate the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY principle</a></p>\n<pre><code>bool isrow = false;\nbool iscol = false;\nint row = 0;\nint col = 0;\nwhile (!isrow)\n{\n Console.WriteLine(&quot;Choose a row (1-3): &quot;);\n try\n {\n row = Convert.ToInt32(Console.ReadLine());\n }\n catch\n {\n\n Console.WriteLine(&quot;Please enter a number between 1 and 3.&quot;);\n }\n if (row == 1 || row == 2 || row == 3)\n {\n isrow = true;\n }\n else\n {\n Console.WriteLine(&quot;\\nInvalid row!&quot;);\n }\n}\nwhile (!iscol)\n{\n Console.WriteLine(&quot;Choose a column (1-3): &quot;);\n try\n {\n col = Convert.ToInt32(Console.ReadLine());\n }\n catch\n {\n Console.WriteLine(&quot;Please enter a number between 1 and 3.&quot;);\n }\n if (col == 1 || col == 2 || col == 3)\n {\n iscol = true;\n }\n else\n {\n Console.WriteLine(&quot;\\nInvalid column!&quot;);\n }\n}\n</code></pre>\n<p>you can reduce to the following</p>\n<pre><code>int row = GetNumber(1,3, &quot;Choose a row (1-3): &quot;);\nint col = GetNumber(1,3, &quot;Choose a column (1-3): &quot;);\n</code></pre>\n<p>by introducing the following method</p>\n<pre><code>static int GetNumber(int min,int max,string message)\n{\n Console.WriteLine(message);\n int input = 0;\n while(!int.TryParse(Console.ReadLine(),out input))\n {\n Console.WriteLine($&quot;Please enter a number between {min} and {max}.&quot;);\n Console.WriteLine(message);\n }\n\n if(input &lt; min || input &gt; max)\n {\n Console.WriteLine($&quot;Invalid input, input should be between [{min},{max}]&quot;);\n return GetNumber(min, max, message);\n }\n return input;\n}\n</code></pre>\n<hr>\n<p>you represent a player turn as an integer this lead to a lot of creepy plain number in your code, plain number are not good for reading you should avoid them as possible it will be better if you represent a player as enum</p>\n<pre><code> enum Player\n {\n X_Player ,\n O_Player\n };\n</code></pre>\n<p>and define your current player of type player</p>\n<pre><code>Player Currentplayer = Player.X_Player;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T15:07:38.353", "Id": "533706", "Score": "1", "body": "_\"the board is 2D board, so to simplify the calculation you should represent it as 2D array not 1D\"_ Strongly disagree. 2D arrays may be easier to reason about in your head, but it does not make it any easier from a coding perspective. Reducing fixed-size (!) boards to a 1D array is a very common approach in game development. If you really want an easier to read coordinate system, you can wrap your array in a neat wrapper, which will be significantly more readably than a 2D array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T15:08:59.907", "Id": "533707", "Score": "1", "body": "There is a small typo in `GetNubmer`. I also do not think that recursion is the best option here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T15:54:09.217", "Id": "533712", "Score": "0", "body": "I think there are some pros and cons to using a 1 or 2-dimensional array. I would not criticize a programmer for choosing either in this instance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T21:55:52.647", "Id": "533742", "Score": "0", "body": "@Flater You are right, I just use it because I thought that tak tak to only played on 3*3 board, I remove it from the answer suggestion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T22:07:20.220", "Id": "533744", "Score": "1", "body": "@jdt yeas it was typo i already edit it .... Yes the recursion choice is not the best, Actually i was going to write super loop but get lazy to write it ! ... and it's okay to use recursion because how many times' user will make this mistake .. And the original point was to state Dry principle" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T13:52:11.667", "Id": "533863", "Score": "0", "body": "Recursion can get dangerous pretty quickly like in [this](https://tio.run/##rZA9D8IgEIb3/oqLEx1sU1fjosbJwejgXOlpSPBQoG2M8bdXaO2Hujh4CQSO9z2eO27G3IiqAheFEhnsUCK3q5y4FYpYGPiXe737WCgySmK018LiWhCyUeOABKwCjWkGSsPEX0qvGYXTzizIunXJLcz8Odqk2iBrS26dt64YDi1HYC/LDJKwy/vwhuWcDdQoDb5Jasxe8wiCrtHW/dFgbgSdoEg1cEWOk7CE3VU6SMJmJC5vrHaqwcdxDFHUdG/Tg@whPsf5zdEh/hHkrDJxvP2GUlVP) example. Not really relevant to tick-tac-toe, but something to be mindful of =)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:45:08.287", "Id": "270294", "ParentId": "270285", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T09:25:20.770", "Id": "270285", "Score": "2", "Tags": [ "c#", "tic-tac-toe" ], "Title": "How can I shorten my tic tac toe game?" }
270285
<p>I need to handle different states of a complex GUI control (such as NORMAL, DRAGGING, MARKING, ...). I came upon this idea:</p> <pre><code>void dispatch(auto const i, auto&amp;&amp; ...f) noexcept(noexcept((f(), ...))) { std::underlying_type&lt;std::remove_const_t&lt;decltype(i)&gt;&gt; j{}; ((j++ == i ? (f(), 0) : 0), ...); } </code></pre> <p>There would be an enum like this:</p> <pre><code>enum State { NORMAL, DRAGGING, MARKING }; </code></pre> <p>and I would use <code>dispatch()</code> in event handlers like so:</p> <pre><code>dispatch( state_, []{}, []{} ); </code></pre> <p>What do you think?</p> <p>EDIT: This might help to prevent nested <code>switch</code>es, which I find very hard to track.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T08:59:41.810", "Id": "533771", "Score": "0", "body": "Here's a [better](https://github.com/user1095108/generic/blob/master/dispatch.hpp) implementation." } ]
[ { "body": "<p>I don't get it.<br />\n<code>j</code> is the same type as the underlying type of <code>i</code> but without the <code>const</code>, and you could have made that clearer by using an explicit template parameter so you could leave the <code>const</code> out of the deduced type.<br />\nBut the only thing you do is increment it, and since it started at 0, <code>j++</code> just makes it <code>1</code>. So why not just initialize it to 1 instead of incrementing zero?</p>\n<p>This assumes that the type of enum used can be compared against an integer, so not the <code>class</code> style.</p>\n<p>No wait a minute... you <em>post</em> increment <code>j</code>, which means it's <code>0</code> when you do the comparison. But you don't use <code>j</code> again, so what was the point of updating it?</p>\n<p>Ah, I see... it's looped via the pack expansion of the comma operator.\nAnd you say <code>switch</code> is hard to follow???? You have three functions, and an index 0,1,2. You're doing a convoluted way to just index the list.</p>\n<p>Instead, initialize a local array of three elements using a pack expansion, then subscript that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T15:01:47.153", "Id": "533703", "Score": "0", "body": "the mechanics of doing the dispatch was not so important to me, as the idea of `dispatch()` itself. The various states and how they interact can be convoluted also. So, if you have an alternative to gigantic switches, I'd like to know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T15:10:03.993", "Id": "533708", "Score": "0", "body": "actually, it could be argued, that `dispatch()` should return a value, but that's just an implementation detail; I wanted to illustrate the general idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T16:00:11.557", "Id": "533713", "Score": "0", "body": "In my designs (long time ago), such _states_ are dynamically defined and handle any kind of modal or contextual behavior of the UI, not just universal things planned by the framework. A whole bundle of callbacks (e.g. all the mouse-related functions) are defined together, and to go into such a state, this handler is added to the front of the handler list. You don't have all the code for different states in one place like in the above design; they are truly independent and extensible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T16:13:21.820", "Id": "533715", "Score": "0", "body": "Maybe you can give an example or something." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T17:06:24.030", "Id": "533718", "Score": "0", "body": "also, nothing prevents you from invoking `dispatch()` in different places." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:58:08.343", "Id": "270296", "ParentId": "270289", "Score": "2" } }, { "body": "<p>You can avoid the complex declaration of <code>j</code> by just post-decrementing <code>i</code>:</p>\n<pre><code>void dispatch(auto i, auto&amp;&amp; ...f) noexcept(noexcept((f(), ...)))\n{\n ((!i-- ? (f(), 0) : 0), ...);\n}\n</code></pre>\n<p>But as JDługosz already pointed out, this is a very convoluted way of dispatching. Also, the compiler is generating quite bad code, equivalent to:</p>\n<pre><code>if (i++ == j)\n f[0]();\nif (i++ == j)\n f[1]();\n...\n</code></pre>\n<p>Why not keep it simple?</p>\n<pre><code>std::array&lt;std::function&lt;void()&gt;, 3&gt; functions{\n []{...},\n []{...},\n []{...}\n};\n\n...\n\nfunctions[state_](); // call the given function\n</code></pre>\n<p>Of course, you want to add some bounds checking there. Your version would also have benefited from a check that <code>i &gt;= 0 &amp;&amp; i &lt; sizeof...(f)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T17:15:52.240", "Id": "533722", "Score": "1", "body": "very nice, but I may be unable to decrement `i`, as it may be an enum." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T17:20:05.630", "Id": "533724", "Score": "0", "body": "also my implementation is not the best, an indices-based implementation would be better, but it was just an illustration. Indices would do no math. Also, in a gui, efficiency does not matter that much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T17:24:14.877", "Id": "533725", "Score": "0", "body": "also, I usually try to avoid `std::function`, if I can." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T19:06:43.173", "Id": "533734", "Score": "0", "body": "Re `std::function`: I thought the use of `auto` rather than a `typename T...` explicit declaration meant there was only one type. But I'm not familiar with the new syntax, being stuck on old compilers for \"real work\". I suppose that's not the case, or you would not be able to pass different lambdas. So, the array issue has the problem of getting a common type. For this case, you can use the plain function pointer since it's a stateless lambda: `void(*)()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T22:41:42.390", "Id": "533749", "Score": "0", "body": "Ah yes, no `std::function` is needed in that case. Also, you can use a normal array instead of `std::array` I guess, which also helps it deduce the size automatically." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T08:59:09.633", "Id": "533770", "Score": "0", "body": "in my asm analysis, an [indices implementation](https://github.com/user1095108/generic/blob/master/dispatch.hpp) trumps an array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T09:38:12.483", "Id": "533773", "Score": "0", "body": "@user1095108 Did you provide it with a constant value for `i`? If so, the compiler will be able to optimize the parameter pack expansion away. However, if it doesn't know what value `i` has at compile-time, things are different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T11:34:06.030", "Id": "533779", "Score": "0", "body": "yes, it works very well, but the state code still doesn't look pretty." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T17:09:54.193", "Id": "270300", "ParentId": "270289", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T13:42:35.953", "Id": "270289", "Score": "0", "Tags": [ "c++", "gui" ], "Title": "handling different states of a complex gui control" }
270289
<p>This is a simple Python 3 program that verifies whether a string is a valid IPv6 address or not, parses IPv6 address to its hexadecimal and decimal values, and converts an integer to IPv6 format.</p> <p>I am writing a webscraper, and to reduce network IO bound time complexity I need to programmatically lookup DNS records of target addresses and change hosts file accordingly due to DNS poisoning by GFW.</p> <p>I use this API: 'https://www.robtex.com/dns-lookup/{website}' to get the addresses using XPaths, and the scraped results contains both IPv4 and IPv6 addresses, I would like to differentiate between IPv4 and IPv6 addresses and validate them separately.</p> <p>For IPv4 addresses I have written this simple regex:</p> <pre><code>'^((25[0-5]|2[0-4]\d|1?[1-9]\d?|0)\.){3}(25[0-5]|2[0-4]\d|1?[1-9]\d?|0)$' </code></pre> <p>It does the validation in one step, but IPv6 is another thing, and after trying and failing to solve this using regex many times I gave up, I have searched for a regex to validate IPv6 and after I realized the regexes that work perfectly are way to long I changed my approach.</p> <p>An IPv6 address is an integer between 0 and 2 ^ 128 (340282366920938463463374607431768211456) represented as 32 hexadecimal digits, formatted as 8 fields of 4 hex digits separated by 7 colons.</p> <p>If not for the shortening rules IPv6 addresses can easily be validated by regexes.</p> <p>There are two shortening rules that are used together, the first rule trims leading zeros in each field.</p> <p>Now with only the first rule applied IPv6 can still be verified using this regex:</p> <pre><code>'^([\da-fA-F]{1,4}\:){7}([\da-fA-F]{1,4})$' </code></pre> <p>But there is the second rule, that omits continuous zero fields for once and uses <code>'::'</code> in its place, for example,</p> <pre><code>0:0:0:0:0:0:0:0 -&gt; :: 0:0:0:0:0:0:0:1 –&gt; ::1 fe80:0:0:0:0:0:0:1 –&gt; fe80::1 fe80:0:0:0:0:1:0:1 -&gt; fe80::1:0:1 </code></pre> <p>Because of the second rule, each of the eight places where the omitted fields can be requires at least one regex, so that is at least 8 regexes in total...</p> <p>So I have written my own code, and here it is:</p> <pre class="lang-py prettyprint-override"><code>import re from ipaddress import ip_address, IPv6Address from typing import Iterable COLONS = {':', '::'} DIGITS = frozenset('0123456789ABCDEFabcdef') MAX_IPV6 = 2**128 - 1 ALL_ZEROS = '0:'*7 + '0' LEADING = re.compile('^(0:)+') TRAILING = re.compile('(:0)+$') MIDDLE = re.compile('(:0)+') def is_ipv6(ip: str) -&gt; bool: if not isinstance(ip, str): raise TypeError('Argument must be an instance of str') if not ip or len(ip) &gt; 39: return False first = True digits = 0 colons = 0 fields = 0 compressed = False for i in ip: if i == ':': digits = 0 first = False colons += 1 if colons == 2: if not compressed: compressed = True else: return False elif colons &gt; 2: return False else: if i not in DIGITS: return False digits += 1 if digits &gt; 4: return False if colons or first: first = False colons = 0 fields += 1 if fields &gt; 8 - compressed: return False if (fields == 8 and colons != 1) or compressed: return True return False def split_ipv6(ip: str) -&gt; Iterable[str]: if not isinstance(ip, str): raise TypeError('Argument must be an instance of str') buffer = '' chunks = [] digits = 0 colons = 0 fields = 0 compressed = False for i in ip: tail = True if i == ':': if digits: chunks.append(buffer) digits = 0 colons += 1 if colons == 2: if not compressed: compressed = True tail = False else: return False if colons &gt; 2: return False else: if i not in DIGITS: return False digits += 1 if digits &gt; 4: return False if colons or not buffer: if colons: chunks.append(':' * colons) colons = 0 fields += 1 buffer = i if fields &gt; 8 - compressed: return False else: buffer += i if tail: chunks.append(buffer) else: chunks.append('::') if (fields == 8 and colons != 1) or compressed: return chunks return False def parse_ipv6(ip: str) -&gt; dict: segments = split_ipv6(ip) if not segments: raise ValueError('Argument is not a valid IPv6 address') compressed = False empty_fields = None if '::' in segments: fields = ['0'] * 8 compressed = True cut = segments.index('::') left = [i for i in segments[:cut] if i not in COLONS] right = [i for i in segments[cut+1:] if i not in COLONS] fields[8-len(right):] = right fields[:len(left)] = left empty_fields = [i for i, f in enumerate(fields) if f == '0'] else: fields = [c for c in segments if c not in COLONS] digits = [int(f, 16) for f in fields] # decimal = sum(d * 65536 ** i for i, d in enumerate(digits[::-1])) hexadecimal = '0x' + ''.join(i.zfill(4) for i in fields) decimal = int(hexadecimal, 16) parsed = { 'segments': segments, 'fields': fields, 'digits': digits, 'hexadecimal': hexadecimal, 'decimal': decimal, 'compressed': compressed, 'empty fields': empty_fields } return parsed def trim_left(s: str) -&gt; str: return s[:-1].lstrip('0') + s[-1] def to_ipv6(n: int, compress=True) -&gt; str: if not isinstance(n, int): raise TypeError('Argument should be an instance of int') if not 0 &lt;= n &lt;= MAX_IPV6: raise ValueError('Argument is not in the valid range that IPv6 can represent') hexa = hex(n).removeprefix('0x').zfill(32) ipv6 = ':'.join(hexa[i:i+4] for i in range(0, 32, 4)) if compress: ipv6 = ':'.join(trim_left(i) for i in ipv6.split(':')) if ipv6 == ALL_ZEROS: return '::' elif LEADING.match(ipv6): return LEADING.sub('::', ipv6) elif TRAILING.search(ipv6): return TRAILING.sub('::', ipv6) ipv6 = MIDDLE.sub(':', ipv6, 1) return ipv6 if __name__ == '__main__': test_cases = [ (42540766411282592856904265327123268393, '2001:db8::ff00:42:8329'), (42540766411282592875278671431329809193, '2001:db8::ff00:0:42:8329'), (0, '::'), (1, '::1'), (5192296858534827628530496329220096, '1::'), (338288524927261089654018896841347694593, 'fe80::1'), (160289081533862935099527363545323831451, '7896:8ddf:4b26:f07f:a4cd:65de:ee90:809b'), (264029623924138153874706093713361856950, 'c6a2:4182:24b2:20f3:2d00:d2bb:3619:e9b6'), (155302777326544552126794348175886719955, '74d6:3a18:151d:948f:d13e:4d87:4fed:1bd3'), (152846031713612901234538066636429037612, '72fd:132e:fe1d:d05c:27d0:6001:a05f:902c'), (21824427460045008308753734783456952407, '106b:3b59:a20b:25dc:61b9:698e:d1e:c057'), (267115622348742355941753354636068900005, 'c8f4:98fa:50b3:e935:2bc9:25b0:593b:cca5'), (16777215, '::ff:ffff'), (3232235777, '::c0a8:101'), (4294967295, '::ffff:ffff'), (2155905152, '::8080:8080'), (18446744073709551615, '::ffff:ffff:ffff:ffff'), (18446744073709551616, '::1:0:0:0:0') ] for number, ip in test_cases: assert to_ipv6(number) == ip assert parse_ipv6(ip)['decimal'] == number </code></pre> <p>As you can see, the first function validates input and splits the input into chunks, in the same loop, I could have used a regex to split the input but that isn't much faster than the manual approach and I figure if I use regex I need at least another for loop to validate the result, in this approach I can save the cost of one loop and do early returns if the input is invalid.</p> <p>And about the two other functions after I have written the first I just couldn't help myself.</p> <p>All functions are working properly and there's exactly 0 chance that there are bugs introduced by me, everything returns what I assume to be correct, that is, addresses like <code>'1::'</code> are treated by the functions to be valid, I don't know if such syntax exists but I assume it does.</p> <p>How can my code be improved?</p> <hr /> <h2>Update</h2> <p>I have written a new function that does only the validation and therefore is much faster.</p> <p>And why did I write these functions in the first place? Why I don't just use <code>ipaddress</code> library?</p> <p>Well, I am reinventing the wheel and I have good reasons to do it.</p> <p>The library code is not perfect, for one thing, I need to validate IPv6 addresses, and yes this means the strings might be invalid, and if the string is not a valid IP address, <code>ipaddress.ip_address</code> raises <code>ValueError</code> so I have to use try catch clauses...</p> <pre><code>In [690]: ipaddress.ip_address('100') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-690-10b17acc39c6&gt; in &lt;module&gt; ----&gt; 1 ipaddress.ip_address('100') C:\Program Files\Python39\lib\ipaddress.py in ip_address(address) 51 pass 52 ---&gt; 53 raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % 54 address) 55 ValueError: '100' does not appear to be an IPv4 or IPv6 address </code></pre> <p>And it validates both IPv4 and IPv6 addresses so I have to use <code>isinstance</code> checks...</p> <p>My custom function only validates IPv6 addresses and doesn't raise exceptions, so there is not any extra step needed.</p> <p>Secondly it is much slower than my functions:</p> <pre><code>Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.28.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: ...: if compress: ...: ipv6 = ':'.join(trim_left(i) for i in ipv6.split(':')) ...: if ipv6 == ALL_ZEROS: ...: return '::' ...: ...: elif LEADING.match(ipv6): ...: return LEADING.sub('::', ipv6) ...: ...: elif TRAILING.search(ipv6): ...: return TRAILING.sub('::', ipv6) ...: ...: ipv6 = MIDDLE.sub(':', ipv6, 1) ...: ...: return ipv6 ...: ...: ...: def ipaddress_test(s): ...: try: ...: return isinstance(ip_address(s), IPv6Address) ...: except ValueError: ...: return False ...: ...: if __name__ == '__main__': ...: test_cases = [ ...: (42540766411282592856904265327123268393, '2001:db8::ff00:42:8329'), ...: (42540766411282592875278671431329809193, '2001:db8::ff00:0:42:8329'), ...: (0, '::'), ...: (1, '::1'), ...: (5192296858534827628530496329220096, '1::'), ...: (338288524927261089654018896841347694593, 'fe80::1'), ...: (160289081533862935099527363545323831451, '7896:8ddf:4b26:f07f:a4cd:65de:ee90:809b'), ...: (264029623924138153874706093713361856950, 'c6a2:4182:24b2:20f3:2d00:d2bb:3619:e9b6'), ...: (155302777326544552126794348175886719955, '74d6:3a18:151d:948f:d13e:4d87:4fed:1bd3'), ...: (152846031713612901234538066636429037612, '72fd:132e:fe1d:d05c:27d0:6001:a05f:902c'), ...: (21824427460045008308753734783456952407, '106b:3b59:a20b:25dc:61b9:698e:d1e:c057'), ...: (267115622348742355941753354636068900005, 'c8f4:98fa:50b3:e935:2bc9:25b0:593b:cca5'), ...: (16777215, '::ff:ffff'), ...: (3232235777, '::c0a8:101'), ...: (4294967295, '::ffff:ffff'), ...: (2155905152, '::8080:8080'), ...: (18446744073709551615, '::ffff:ffff:ffff:ffff'), ...: (18446744073709551616, '::1:0:0:0:0') ...: ] ...: for number, ip in test_cases: ...: assert to_ipv6(number) == ip ...: assert parse_ipv6(ip)['decimal'] == number In [2]: ip_address('2001:0db8:0000:0000:ff00:0000:0042:8329') Out[2]: IPv6Address('2001:db8::ff00:0:42:8329') In [3]: type(ip_address('2001:0db8:0000:0000:ff00:0000:0042:8329')) == IPv6Address Out[3]: True In [4]: %timeit ipaddress_test('2001:0db8:0000:0000:ff00:0000:0042:8329') 12.2 µs ± 685 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [5]: %timeit is_ipv6('2001:0db8:0000:0000:ff00:0000:0042:8329') 6.01 µs ± 557 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [6]: %timeit ipaddress_test('2001:0db8:0000:0000:ff00:0000:0042:8329') 12.3 µs ± 657 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [7]: %timeit parse_ipv6('2001:0db8:0000:0000:ff00:0000:0042:8329') 15.2 µs ± 302 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [8]: %timeit parse_ipv6('2001:db8::ff00:0:42:8329') 14.6 µs ± 629 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [9]: %timeit is_ipv6('2001:db8::ff00:0:42:8329') 4.02 µs ± 561 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [10]: %timeit ipaddress_test('2001:db8::ff00:0:42:8329') 10.4 µs ± 204 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [11]: %%timeit ...: for number, ip in test_cases: ...: assert is_ipv6(ip) == True 62.5 µs ± 5.24 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [12]: %%timeit ...: for number, ip in test_cases: ...: assert ipaddress_test(ip) == True 169 µs ± 4.58 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [13]: is_ipv6('f:'*7) Out[13]: False In [14]: is_ipv6('f:'*8) Out[14]: False In [15]: is_ipv6('f:'*9) Out[15]: False In [16]: is_ipv6('f:'*7+':') Out[16]: True In [17]: is_ipv6('f:'*7+'f') Out[17]: True In [18]: %timeit is_ipv6('f:'*7) 2.57 µs ± 392 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [19]: %timeit is_ipv6('f:'*8) 2.9 µs ± 468 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [20]: %timeit is_ipv6('f:'*9) 3.06 µs ± 368 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [21]: %timeit is_ipv6('f:'*7+':') 2.76 µs ± 468 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [22]: ipaddress_test('f:'*7) Out[22]: False In [23]: ipaddress_test('f:'*8) Out[23]: False In [24]: ipaddress_test('f:'*9) Out[24]: False In [25]: ipaddress_test('f:'*7+'f') Out[25]: True In [26]: %timeit ipaddress_test('f:'*7) 5.88 µs ± 684 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [27]: %timeit ipaddress_test('f:'*8) 5.87 µs ± 753 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [28]: %timeit ipaddress_test('f:'*9) 5.14 µs ± 770 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [29]: %timeit ipaddress_test('f:'*7+'f') 11.1 µs ± 400 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [30]: ipaddress_test('f::') Out[30]: True In [31]: ipaddress_test('::f') Out[31]: True In [32]: ipaddress_test('f::f') Out[32]: True In [33]: ipaddress_test('f:::f') Out[33]: False In [34]: %timeit ipaddress_test('f::') 5.53 µs ± 639 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [35]: %timeit ipaddress_test('::f') 5.54 µs ± 552 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [36]: %timeit ipaddress_test('f:::f') 5.25 µs ± 581 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [37]: %timeit ipaddress_test('100') 4.52 µs ± 591 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [38]: is_ipv6('100') Out[38]: False In [39]: %timeit is_ipv6('100') 747 ns ± 34.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [40]: %timeit is_ipv6('f::') 741 ns ± 60.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [41]: %timeit is_ipv6('::f') 735 ns ± 43 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [42]: %timeit is_ipv6('f:::f') 864 ns ± 49.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [43]: %timeit is_ipv6('windows') 278 ns ± 38.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [44]: %timeit ipaddress_test('windows') 4.62 µs ± 749 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [45]: </code></pre> <p>As you can see the library code is nowhere near the speed of my functions and in particular my custom functions spots invalid inputs much much faster than the library code...</p> <p>Have I made myself clear?</p> <hr /> <p>Again, <code>IPv6Address</code> is not fast enough:</p> <pre><code>In [107]: from ipaddress import AddressValueError In [108]: IPv6Address('100') --------------------------------------------------------------------------- AddressValueError Traceback (most recent call last) &lt;ipython-input-108-46a502d0274c&gt; in &lt;module&gt; ----&gt; 1 IPv6Address('100') C:\Program Files\Python39\lib\ipaddress.py in __init__(self, address) 1916 addr_str, self._scope_id = self._split_scope_id(addr_str) 1917 -&gt; 1918 self._ip = self._ip_int_from_string(addr_str) 1919 1920 def __str__(self): C:\Program Files\Python39\lib\ipaddress.py in _ip_int_from_string(cls, ip_str) 1629 if len(parts) &lt; _min_parts: 1630 msg = &quot;At least %d parts expected in %r&quot; % (_min_parts, ip_str) -&gt; 1631 raise AddressValueError(msg) 1632 1633 # If the address has an IPv4-style suffix, convert it to hexadecimal. AddressValueError: At least 3 parts expected in '100' In [109]: def IPv6Address_test(s): ...: try: ...: IPv6Address(s) ...: return True ...: except AddressValueError: ...: return False In [110]: %timeit IPv6Address_test('100') 2.13 µs ± 33.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [111]: IPv6Address_test('100::') Out[111]: True In [112]: IPv6Address_test('255.255.255.255') Out[112]: False In [113]: valid_long = [ ...: '2001:0db8:0000:0000:ff00:0000:0042:8329', ...: '2001:db8::ff00:0:42:8329', ...: 'f:'*7+':', ...: 'f:'*7+'f', ...: '7896:8ddf:4b26:f07f:a4cd:65de:ee90:809b', ...: 'c6a2:4182:24b2:20f3:2d00:d2bb:3619:e9b6', ...: '74d6:3a18:151d:948f:d13e:4d87:4fed:1bd3', ...: '72fd:132e:fe1d:d05c:27d0:6001:a05f:902c', ...: '106b:3b59:a20b:25dc:61b9:698e:d1e:c057', ...: 'c8f4:98fa:50b3:e935:2bc9:25b0:593b:cca5', ...: '2001:db8::ff00:42:8329', ...: '2001:db8::ff00:0:42:8329' ...: ] In [114]: valid_short = [ ...: '::', ...: '::1', ...: '1::', ...: 'fe80::1', ...: '::ff:ffff', ...: '::c0a8:101', ...: '::ffff:ffff', ...: '::8080:8080', ...: '::ffff:ffff:ffff:ffff', ...: '::1:0:0:0:0', ...: 'f::', ...: '::f', ...: 'f::f' ...: ] In [115]: invalid = [ ...: '100', ...: 'windows', ...: 'intelligence', ...: 'this is not an IPv6 address', ...: 'esperanza', ...: 'hispana', ...: 'esperanta', ...: '255.255.255.255', ...: '192.168.1.1', ...: '127.0.0.1', ...: '151.101.129.69', ...: 'f:::f', ...: 'f:'*7, ...: 'f:'*8, ...: 'f:'*9 ...: ] In [116]: %timeit for i in valid_long: assert is_ipv6(i) == True 65 µs ± 7.37 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [117]: %timeit for i in valid_long: assert IPv6Address_test(i) == True 122 µs ± 5.68 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [118]: %timeit for i in valid_short: assert is_ipv6(i) == True 19.8 µs ± 485 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [119]: %timeit for i in valid_short: assert IPv6Address_test(i) == True 59.4 µs ± 6.72 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [120]: %timeit for i in invalid: assert is_ipv6(i) == False 16.6 µs ± 650 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [121]: %timeit for i in invalid: assert IPv6Address_test(i) == False 38.3 µs ± 7.13 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [122]: %timeit is_ipv6('::') 526 ns ± 25.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [123]: is_ipv6('::') Out[123]: True In [124]: %timeit is_ipv6('::1') 739 ns ± 41.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [125]: %timeit is_ipv6('1::') 741 ns ± 33.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [126]: %timeit is_ipv6('100') 761 ns ± 43.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [127]: %timeit IPv6Address_test('::') 2.65 µs ± 468 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [128]: %timeit IPv6Address_test('::1') 3.38 µs ± 687 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [129]: %timeit IPv6Address_test('1::') 3.4 µs ± 684 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [130]: %timeit IPv6Address_test('100') 2.13 µs ± 41.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [131]: %timeit IPv6Address_test('g') 2.11 µs ± 29 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [132]: %timeit is_ipv6('g') 289 ns ± 54.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [133]: <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T16:45:45.850", "Id": "533717", "Score": "1", "body": "Have you considered using [ipaddress](https://docs.python.org/3/library/ipaddress.html)? In particular, the [conversion integer and string](https://docs.python.org/3/library/ipaddress.html#conversion-to-strings-and-integers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T17:17:21.560", "Id": "533723", "Score": "1", "body": "I agree with Marc that using the library ipaddress`es is the way to go. If you want to have a look at a working regex parser it looks like this https://regex101.com/r/cT0hV4/5 _shudders_." } ]
[ { "body": "<blockquote>\n<p>I have written this simple regex</p>\n</blockquote>\n<p>Ish. You haven't written it in a very simple way. Write it on multiple lines, add comments.</p>\n<p><code>65536 ** i</code> seems like a less obvious way of accomplishing 1 bit-shifted left by 16*i.</p>\n<p>This:</p>\n<pre><code> hexadecimal = '0x' + ''.join(i.zfill(4) for i in fields)\n decimal = int(hexadecimal, 16)\n</code></pre>\n<p>joins the fields in the string domain, but I think it would make more sense to join them in the integer domain - i.e. using bit-shift operations. Even if you did want to join them in the string domain, there's no need to prepend <code>0x</code>.</p>\n<p><code>parse_ipv6</code> currently has a weak type - a <code>dict</code> - and should prefer something like a named tuple instead.</p>\n<p>It's an odd choice to have your accepted test case values in decimal. Hexadecimal literals like <code>0xFFFF_FFFF</code> will be more obviously correct than <code>4294967295</code>.</p>\n<blockquote>\n<p>I am reinventing the wheel and I have good reasons to do it.</p>\n</blockquote>\n<p>I beg to differ, but let's dig into it:</p>\n<blockquote>\n<p>if the string is not a valid IP address, <code>ipaddress.ip_address</code> raises <code>ValueError</code> so I have to use <code>try</code>/<code>catch</code> clauses</p>\n</blockquote>\n<p>That's a feature, not a bug. Thinking about the typical consumers of an IP parsing routine, well-written code would make better use of exceptions than a boolean value, and doing an <code>except</code> is trivial if needed.</p>\n<blockquote>\n<p>And it validates both IPv4 and IPv6 addresses so I have to use <code>isinstance</code> checks...</p>\n</blockquote>\n<p>That's because you're using it wrong. You should not be calling <code>ip_address</code>, and instead should directly construct an <code>IPv6Address</code>.</p>\n<blockquote>\n<p>it is much slower than my functions</p>\n</blockquote>\n<p>First, a fair comparison would only use <code>IPv6Address()</code> instead of forcing <code>ip_address</code> to try parsing an IPv4 address with a guaranteed failure.</p>\n<p>Beyond that: whether or not fixing the above brings the routines into being performance-comparable, it's relatively rare that an application needs to validate thousands of addresses, and nearly always, correctness and maintainability matter more than performance. Your code is non-trivial, and will be a true pain to maintain as compared to using a built-in. How confident are you that your code is correct? 80%? 90%? Do you think that you can beat the stability and test coverage of the Python community? There are times where reinventing the wheel is called for, but this isn't one of them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T02:00:04.327", "Id": "270346", "ParentId": "270290", "Score": "1" } } ]
{ "AcceptedAnswerId": "270346", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:12:57.793", "Id": "270290", "Score": "1", "Tags": [ "performance", "python-3.x", "programming-challenge", "reinventing-the-wheel", "converting" ], "Title": "Python IPv6 verifier, parser and converter" }
270290
<p>This macro calculates some basic figures from a given set of data. But it runs very slow probably due to me referencing the sheet again and again. Does anyone have a better idea on how to optimize this code:</p> <pre><code>Sub Handler_Fees() Dim strFile, tarFile As String Dim Source As Workbook Dim Target As ThisWorkbook Dim ws1 As Worksheet Dim ThisCell, ThatCell, WhichCell As Range Dim t As Single Application.ScreenUpdating = False Application.DisplayStatusBar = False Application.EnableEvents = False strFile = Application.GetOpenFilename(FileFilter:=&quot;Excel Files (*.xlsx*), *.xlsx*&quot;, Title:=&quot;Choose the export from the inducement engine&quot;) Workbooks.Open (strFile) t = Timer ActiveWorkbook.ActiveSheet.Range(&quot;R3&quot;) = &quot;Price per share&quot; Range(&quot;R4&quot;).Select ActiveCell.Value = &quot;=J4/F4&quot; Selection.AutoFill Destination:=Range(&quot;R4:R&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select Set ws1 = ActiveSheet Set Source = ActiveWorkbook Set Target = ThisWorkbook ThisWorkbook.Activate Range(&quot;H2&quot;).Select ActiveCell.Formula2R1C1 = &quot;=INDEX('[&quot; &amp; Source.Name &amp; &quot;]&quot; &amp; ws1.Name &amp; &quot;'!R4C18:R38C18, MATCH(RC3&amp;RC1,'[&quot; &amp; Source.Name &amp; &quot;]&quot; &amp; ws1.Name &amp; &quot;'!R4C3:R38C3 &amp; '[&quot; &amp; Source.Name &amp; &quot;]&quot; &amp; ws1.Name &amp; &quot;'!R4C5:R38C5,0))&quot; Selection.AutoFill Destination:=Range(&quot;H2:H&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select Target.ActiveSheet.Range(&quot;G1&quot;) = &quot;Corrected Quantity&quot; Range(&quot;G2&quot;).Select ActiveCell.Formula = &quot;=D2/(10^E2)&quot; Selection.AutoFill Destination:=Range(&quot;G2:G&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select Target.ActiveSheet.Range(&quot;H1&quot;) = &quot;Price per share&quot; Target.ActiveSheet.Range(&quot;I1&quot;) = &quot;Assessment&quot; Range(&quot;I2&quot;).Select ActiveCell.Formula = &quot;=G2*H2&quot; Selection.AutoFill Destination:=Range(&quot;I2:I&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select Target.ActiveSheet.Range(&quot;J1&quot;) = &quot;Portfolio commission percentage&quot; Range(&quot;J2&quot;).Select ActiveCell.Formula2R1C1 = &quot;=VLOOKUP(RC3,'[&quot; &amp; Source.Name &amp; &quot;]&quot; &amp; ws1.Name &amp; &quot;'!R4C3:R38C11,9,0)&quot; Selection.AutoFill Destination:=Range(&quot;J2:J&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select Target.ActiveSheet.Range(&quot;K1&quot;) = &quot;Trailer Fees&quot; Range(&quot;K2&quot;).Select ActiveCell.Value = &quot;=((I2/100)*J2)/365&quot; Selection.AutoFill Destination:=Range(&quot;K2:K&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select Range(&quot;J2&quot;).Select Selection.AutoFill Destination:=Range(&quot;J2:J&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 'Selection.Value = Format(ActiveCell, &quot;0.00&quot;) Range(&quot;K2&quot;).Select Selection.AutoFill Destination:=Range(&quot;K2:K&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 'Selection.Value = Format(ActiveCell, &quot;0.00&quot;) For Each ThisCell In Range(&quot;K2:K&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select ThisCell.Value = Application.Round(ThisCell.Value, 2) Next ThisCell Range(&quot;H2&quot;).Select Selection.AutoFill Destination:=Range(&quot;H2:H&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False For Each ThatCell In Range(&quot;H2:H&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select ThatCell.Value = Application.Round(ThatCell.Value, 2) Next ThatCell For Each WhichCell In Range(&quot;I2:I&quot; &amp; Range(&quot;E&quot; &amp; Rows.Count).End(xlUp).Row) Range(Selection, Selection.End(xlDown)).Select WhichCell.Value = Application.Round(WhichCell.Value, 2) Next WhichCell Range(&quot;A1&quot;).Select Application.ScreenUpdating = True Application.DisplayStatusBar = True Application.EnableEvents = True MsgBox Timer - t End Sub </code></pre>
[]
[ { "body": "<p>A little observation:</p>\n<p>When many variables are declared in one line it must be specified the type of each one. There are two lines in your code that doesn't accomplish this.</p>\n<pre><code>Dim strFile, tarFile As String\nDim ThisCell, ThatCell, WhichCell As Range\n</code></pre>\n<p>The correct is:</p>\n<pre><code>Dim strFile As String, tarFile As String\nDim ThisCell As Range, ThatCell As Range, WhichCell As Range\n</code></pre>\n<p>What happens if you don't do that? The variables that don't have the corresponding type are declared by default as Variant, a kind of data type more general and that occupy more memory (bytes, not much). Specifying the data type at the end of the line not means that all the variables listed will take that type. It's a little observation. I don't believe that is the cause of the lag in your code. If you can upload your file or a screenshot of the sheet from the data are being taken it's more easy to understand the context to help you. Greetings.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T15:17:38.053", "Id": "270466", "ParentId": "270291", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:14:28.657", "Id": "270291", "Score": "0", "Tags": [ "vba", "excel" ], "Title": "Macro which performs a series of operations on a given set of data" }
270291
<p>I'm using TypeScript for my Vue app and have a custom type I'm working with</p> <pre><code>type MyCustomType = { fooProperty: string, barProperty: string /* ... other fields ... */ }; </code></pre> <p>This type holds a bunch of properties acting as a &quot;composite key&quot;. So the combination of all properties must be unique.</p> <hr /> <p><strong>First approach:</strong></p> <p>The first idea coming to my mind is to simply use a <code>Set&lt;T&gt;</code></p> <pre><code>const set: Set&lt;MyCustomType&gt; = new Set&lt;MyCustomType&gt;(); set.add({ fooProperty: &quot;a&quot;, barProperty: &quot;b&quot; }); console.log(set.has({ fooProperty: &quot;a&quot;, barProperty: &quot;b&quot; })); // expected: true, actual: false </code></pre> <p>The problem is that this set is not able to compare the objects. So <code>{ fooProperty: &quot;a&quot;, barProperty: &quot;b&quot; } === { fooProperty: &quot;a&quot;, barProperty: &quot;b&quot; } // false</code> ( based on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality</a> )</p> <hr /> <p><strong>Second approach:</strong></p> <p>An internal <code>Map&lt;string, T&gt;</code> holding <code>T</code> as a stringified key might be a good idea</p> <pre><code>class TrulyUniqueSet&lt;ElementType&gt; { private readonly elements: Map&lt;string, ElementType&gt; = new Map&lt;string, ElementType&gt;(); private elementToKey(element: ElementType): string { return JSON.stringify(element); } public get size(): number { return this.elements.size; } public add(element: ElementType): TrulyUniqueSet&lt;ElementType&gt; { const elementKey: string = this.elementToKey(element); this.elements.set(elementKey, element); return this; } public clear(): void { this.elements.clear(); } public delete(element: ElementType): boolean { const elementKey: string = this.elementToKey(element); return this.elements.delete(elementKey); } public has(element: ElementType): boolean { const elementKey: string = this.elementToKey(element); return this.elements.has(elementKey); } public values(): IterableIterator&lt;ElementType&gt; { return this.elements.values(); } public forEach(callbackfn: (element: ElementType) =&gt; void): void { return this.elements.forEach((element: ElementType) =&gt; callbackfn(element)); } } </code></pre> <p>but things might get buggy if the structure of an object changes</p> <pre><code>const set: TrulyUniqueSet&lt;MyCustomType&gt; = new TrulyUniqueSet&lt;MyCustomType&gt;(); set.add({ fooProperty: &quot;a&quot;, barProperty: &quot;b&quot; }); console.log(set.has({ fooProperty: &quot;a&quot;, barProperty: &quot;b&quot; })); // expected: true, actual: true console.log(set.has({ barProperty: &quot;b&quot;, fooProperty: &quot;a&quot; })); // expected: true, actual: false </code></pre> <p>obviously because of different JSON strings.</p> <hr /> <p><strong>Third approach:</strong></p> <p>I tried to extend the <code>Set</code> by overriding the equality check</p> <pre><code>class MyCustomTypeCollection extends Set&lt;MyCustomType&gt; { private customTypesAreEqual(firstValue: MyCustomType, secondValue: MyCustomType): boolean { return firstValue.fooProperty === secondValue.fooProperty &amp;&amp; firstValue.barProperty=== secondValue.barProperty; /* add other equality checks here */ } public add(value: MyCustomType): this { if (!this.has(value)) { super.add(value); } return this; } public has(value: MyCustomType): boolean { // truly check for duplicates return Array .from(this) .some((currentValue: MyCustomType) =&gt; this.customTypesAreEqual(currentValue, value)); } public delete(value: MyCustomType): boolean { const filteredValues: MyCustomType[] = Array .from(this) .filter((currentValue: MyCustomType) =&gt; !this.customTypesAreEqual(currentValue, value)); // remove the value from the collection if(filteredValues.length &lt; this.size) { // &quot;rebuild&quot; the collection this.clear(); filteredValues.forEach(this.add); return true; } return false; } } </code></pre> <p>The usage works as expected</p> <pre><code>const set: MyCustomTypeCollection = new MyCustomTypeCollection(); set.add({ fooProperty: &quot;a&quot;, barProperty: &quot;b&quot; }); console.log(set.has({ fooProperty: &quot;a&quot;, barProperty: &quot;b&quot; })); // expected: true, actual: true console.log(set.has({ barProperty: &quot;b&quot;, fooProperty: &quot;a&quot; })); // expected: true, actual: true set.delete({ fooProperty: &quot;a&quot;, barProperty: &quot;b&quot; }); console.log(set.has({ fooProperty: &quot;a&quot;, barProperty: &quot;b&quot; })); // expected: false, actual: false console.log(set.has({ barProperty: &quot;b&quot;, fooProperty: &quot;a&quot; })); // expected: false, actual: false </code></pre> <p><strong>but</strong> the implementation looks very slow in terms of performance.</p> <hr /> <p>I think I will go with the third approach but do you have any suggestions, better ideas or code improvements?</p> <p>Thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T15:02:20.843", "Id": "533704", "Score": "0", "body": "Why not add primary keys on database table and do an INSERT IGNORE?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T15:04:55.267", "Id": "533705", "Score": "0", "body": "thanks for your comment, I updated my question :) This is a Vue app (frontend)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T23:51:22.367", "Id": "533752", "Score": "0", "body": "why not use a `Map<T,Set<T>>` with `foo` being the key for the map and `bar` in the set." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T00:04:38.373", "Id": "533753", "Score": "1", "body": "Eventually, there will be a record/tuple proposal, that would let you use composite data within sets. But you can only use immutable data (and it looks like you wanted mutability). Either way, you'd need a different solution for now, but if you're interested, [here's](https://github.com/tc39/proposal-record-tuple) the proposal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T07:04:15.390", "Id": "533758", "Score": "0", "body": "@jdt I think the OP provided just an example, there might be many more props to consider" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T07:45:09.083", "Id": "533766", "Score": "0", "body": "yes @Question3r is right. But do you guys have any improvements for my third approach implementation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T11:37:33.543", "Id": "533998", "Score": "0", "body": "Set can hold and compare objects if you ask nicely. Objects are reference types in JS. So you shouldn't add an object literal but a reference to it. i.e. Do like `var obj1 = {foo: \"this\", bar: \"that\"};` then `mySet.add(obj1);`. Now if you check for `obj1` like `mySet.has(obj1);` you get true. If you have multiple sets you can simply put them into an array and refrence them individually like `myObjArray[n]` etc..." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:45:05.857", "Id": "270293", "Score": "2", "Tags": [ "javascript", "typescript" ], "Title": "Create a collection of truly unique objects of custom type" }
270293
<p>I made a custom Binance API wrapper (<code>BinanceRestClient</code>) which uses <code>IHttpClientFactory</code> in order to prevent socket exhaustion, while also ensuring that DNS changes are respected.</p> <p>I looked at the implementation of a deprecated API wrapper (<a href="https://github.com/glitch100/BinanceDotNet/blob/master/BinanceExchange.API/Client/BinanceClient.cs#L354" rel="nofollow noreferrer">this one</a>) and I realized how clean they did it. For ex. my <code>GetBalances()</code> method is around 20 lines of code, compared to theirs (1 line of code). <a href="https://codereview.stackexchange.com/questions/124155/custom-httpclient-wrapper">This one</a> could be added as a reference too.</p> <p>I then tried to do the same by creating the <code>BinanceApiProcessor</code> class. It works. However, I think my implementation of <code>InvokeAsync&lt;T&gt;</code> is not clean. This is how we call the class:</p> <pre class="lang-cs prettyprint-override"><code>public Task&lt;AccountTradeResponse?&gt; GetMyTrades(CancellationToken ct = default) { using var apiProcessor = new BinanceApiProcessor(_httpClientFactory); const string symbol = &quot;DOGEUSDT&quot;; return apiProcessor.InvokeAsync&lt;AccountTradeResponse&gt;(HttpMethod.Get, EndpointSecurityType.UserData, &quot;/api/v3/myTrades&quot;, $&quot;symbol={symbol}&amp;recvWindow=5000&quot;, ct); } </code></pre> <p>I would like to get code review, because I know things could be made in a cleaner way.</p> <h2>API Processor class</h2> <pre class="lang-cs prettyprint-override"><code>internal class BinanceApiProcessor : IDisposable { private const string BaseAddress = &quot;https://api.binance.com&quot;; private const string ApiKey = &quot;xxx&quot;; private const string SecretKey = &quot;xxx&quot;; private readonly IHttpClientFactory _httpClientFactory; /// &lt;summary&gt; /// Whether this instance is disposed. /// &lt;/summary&gt; private bool _isDisposed; /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref=&quot;BinanceApiProcessor&quot; /&gt; class. /// &lt;/summary&gt; /// &lt;param name=&quot;httpClientFactory&quot;&gt;&lt;/param&gt; public BinanceApiProcessor(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } /// &lt;summary&gt; /// The HTTP client. /// &lt;/summary&gt; private HttpClient HttpClient { get { var client = _httpClientFactory.CreateClient(); Guard.Against.NullOrWhiteSpace(BaseAddress, nameof(BaseAddress), &quot;BaseAddress is required&quot;); client.BaseAddress = new Uri(BaseAddress); client.Timeout = new TimeSpan(0, 0, 0, 10); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;)); client.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue(&quot;UTF-8&quot;)); return client; } } /// &lt;summary&gt; /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// &lt;/summary&gt; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// &lt;summary&gt; /// Timestamp in milliseconds. /// &lt;/summary&gt; /// &lt;returns&gt;The current timestamp in milliseconds.&lt;/returns&gt; private static long GetNonce() { return DateTime.UtcNow.ToTimestamp(); } /// &lt;summary&gt; /// Creates HMAC signature for signed endpoints. /// &lt;/summary&gt; /// &lt;param name=&quot;secretKey&quot;&gt;The secret key.&lt;/param&gt; /// &lt;param name=&quot;payload&quot;&gt;URL encoded values that would usually be the query string for the request.&lt;/param&gt; /// &lt;returns&gt;A ct representing the request params.&lt;/returns&gt; private static string CreateSignature(string secretKey, string payload) { Guard.Against.NullOrWhiteSpace(secretKey, nameof(secretKey)); Guard.Against.NullOrWhiteSpace(payload, nameof(payload)); using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey)); var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)); return BitConverter.ToString(computedHash).Replace(&quot;-&quot;, &quot;&quot;).ToLowerInvariant(); } public async Task&lt;T?&gt; InvokeAsync&lt;T&gt;( HttpMethod httpMethod, EndpointSecurityType securityType, string endpoint, string? parameters = default, CancellationToken ct = default) where T : class { Guard.Against.NullOrWhiteSpace(endpoint, nameof(endpoint)); ct.ThrowIfCancellationRequested(); ThrowIfDisposed(); //============================================ // TODO: Implement a rate limiter var queryBuilder = new QueryBuilder(); foreach (var (key, value) in QueryHelpers.ParseQuery(parameters)) queryBuilder.Add(key, value.ToString()); if (securityType is EndpointSecurityType.Trade or EndpointSecurityType.UserData) { queryBuilder.Add(&quot;timestamp&quot;, GetNonce().ToString()); var queryString = queryBuilder.ToQueryString().ToString()[1..]; // ignore first character '?'. Binance requires it like so: &quot;symbol=DOGEUSDT&amp;recvWindow=5000&amp;timestamp=1637590595930&quot; var signature = CreateSignature(SecretKey, queryString); queryBuilder.Add(&quot;signature&quot;, signature); } var uri = $&quot;{endpoint}{queryBuilder.ToQueryString()}&quot;; using var httpRequestMessage = new HttpRequestMessage(httpMethod, uri); if (securityType != EndpointSecurityType.None) httpRequestMessage.Headers.Add(&quot;X-MBX-APIKEY&quot;, ApiKey); using var httpContent = new StringContent(string.Empty, Encoding.UTF8, &quot;application/x-www-form-urlencoded&quot;); if (httpMethod == HttpMethod.Post || httpMethod == HttpMethod.Put || httpMethod == HttpMethod.Delete) httpRequestMessage.Content = httpContent; //============================================ using var httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, ct).ConfigureAwait(false); // Ensures OK status httpResponseMessage.EnsureSuccessStatusCode(); // Get response string var json = await httpResponseMessage.Content.ReadAsStringAsync(ct).ConfigureAwait(false); return json.FromJson&lt;T&gt;(); } /// &lt;summary&gt; /// The standard dispose destructor. /// &lt;/summary&gt; ~BinanceApiProcessor() { Dispose(false); } /// &lt;summary&gt; /// Throw if disposed. /// &lt;/summary&gt; /// &lt;exception cref=&quot;ObjectDisposedException&quot;&gt;&lt;/exception&gt; private void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException($&quot;{nameof(BinanceApiProcessor)} has been disposed&quot;); } /// &lt;summary&gt; /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// &lt;/summary&gt; /// &lt;param name=&quot;disposing&quot;&gt;If this method is called by a user's code.&lt;/param&gt; protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { } _isDisposed = true; } } </code></pre> <h2>REST Client class</h2> <pre class="lang-cs prettyprint-override"><code>/// &lt;summary&gt; /// Binance REST implementation. /// &lt;/summary&gt; internal class BinanceRestClient : IDisposable { private const string BaseAddress = &quot;https://api.binance.com&quot;; private const string ApiKey = &quot;xxx&quot;; private const string SecretKey = &quot;xxx&quot;; private readonly IHttpClientFactory _httpClientFactory; /// &lt;summary&gt; /// Whether this instance is disposed. /// &lt;/summary&gt; private bool _isDisposed; /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref=&quot;BinanceRestClient&quot; /&gt; class. /// &lt;/summary&gt; /// &lt;param name=&quot;httpClientFactory&quot;&gt;&lt;/param&gt; public BinanceRestClient(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } /// &lt;summary&gt; /// The HTTP client. /// &lt;/summary&gt; private HttpClient HttpClient { get { var client = _httpClientFactory.CreateClient(); Guard.Against.NullOrWhiteSpace(BaseAddress, nameof(BaseAddress), &quot;BaseAddress is required&quot;); client.BaseAddress = new Uri(BaseAddress); client.Timeout = new TimeSpan(0, 0, 0, 10); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;)); client.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue(&quot;UTF-8&quot;)); return client; } } /// &lt;summary&gt; /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// &lt;/summary&gt; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// &lt;summary&gt; /// Timestamp in milliseconds. /// &lt;/summary&gt; /// &lt;returns&gt;The current timestamp in milliseconds.&lt;/returns&gt; private static long GetNonce() { return DateTime.UtcNow.ToTimestamp(); } /// &lt;summary&gt; /// Creates HMAC signature for signed endpoints. /// &lt;/summary&gt; /// &lt;param name=&quot;secretKey&quot;&gt;The secret key.&lt;/param&gt; /// &lt;param name=&quot;payload&quot;&gt;URL encoded values that would usually be the query string for the request.&lt;/param&gt; /// &lt;returns&gt;A ct representing the request params.&lt;/returns&gt; private static string CreateSignature(string secretKey, string payload) { Guard.Against.NullOrWhiteSpace(secretKey, nameof(secretKey)); Guard.Against.NullOrWhiteSpace(payload, nameof(payload)); using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey)); var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)); return BitConverter.ToString(computedHash).Replace(&quot;-&quot;, &quot;&quot;).ToLowerInvariant(); } /// &lt;summary&gt; /// Test the connectivity to the API. /// &lt;/summary&gt; public async Task&lt;EmptyResponse?&gt; TestConnectivityAsync(CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); ThrowIfDisposed(); const string endpoint = &quot;/api/v3/ping&quot;; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, endpoint); using var httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, ct).ConfigureAwait(false); // Ensures OK status httpResponseMessage.EnsureSuccessStatusCode(); // Get response string var json = await httpResponseMessage.Content.ReadAsStringAsync(ct).ConfigureAwait(false); // Deserialize return json.FromJson&lt;EmptyResponse&gt;(); } /// &lt;summary&gt; /// Gets the current server time (UTC). /// &lt;/summary&gt; /// &lt;param name=&quot;ct&quot;&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public async Task&lt;ServerTimeResponse?&gt; GetServerTimeAsync(CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); ThrowIfDisposed(); const string endpoint = &quot;/api/v3/time&quot;; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, endpoint); using var httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, ct).ConfigureAwait(false); // Ensures OK status httpResponseMessage.EnsureSuccessStatusCode(); // Get response string var json = await httpResponseMessage.Content.ReadAsStringAsync(ct).ConfigureAwait(false); return json.FromJson&lt;ServerTimeResponse&gt;(); } /// &lt;summary&gt; /// Gets current user balances. /// &lt;/summary&gt; /// &lt;param name=&quot;ct&quot;&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public async Task&lt;AccountInformationResponse?&gt; GetBalancesAsync(CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); ThrowIfDisposed(); var queryString = $&quot;timestamp={GetNonce()}&quot;; var endpoint = $&quot;/api/v3/account?{queryString}&amp;signature={CreateSignature(SecretKey, queryString)}&quot;; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, endpoint); httpRequestMessage.Headers.Add(&quot;X-MBX-APIKEY&quot;, ApiKey); using var httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, ct).ConfigureAwait(false); // Ensures OK status httpResponseMessage.EnsureSuccessStatusCode(); // Get response string var json = await httpResponseMessage.Content.ReadAsStringAsync(ct).ConfigureAwait(false); return json.FromJson&lt;AccountInformationResponse&gt;(); } public Task&lt;AccountTradeResponse?&gt; GetMyTrades(CancellationToken ct = default) { using var apiProcessor = new BinanceApiProcessor(_httpClientFactory); const string symbol = &quot;DOGEUSDT&quot;; return apiProcessor.InvokeAsync&lt;AccountTradeResponse&gt;(HttpMethod.Get, EndpointSecurityType.UserData, &quot;/api/v3/myTrades&quot;, $&quot;symbol={symbol}&amp;recvWindow=5000&quot;, ct); } /// &lt;summary&gt; /// Creates a listen key. /// &lt;/summary&gt; /// &lt;param name=&quot;ct&quot;&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public async Task&lt;UserDataStreamResponse?&gt; CreateListenKeyAsync(CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); ThrowIfDisposed(); const string endpoint = &quot;/api/v3/userDataStream&quot;; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, endpoint); httpRequestMessage.Headers.Add(&quot;X-MBX-APIKEY&quot;, ApiKey); using var httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, ct).ConfigureAwait(false); // Ensures OK status httpResponseMessage.EnsureSuccessStatusCode(); // Get response string var json = await httpResponseMessage.Content.ReadAsStringAsync(ct).ConfigureAwait(false); return json.FromJson&lt;UserDataStreamResponse&gt;(); } /// &lt;summary&gt; /// Keeps alive a listen key. /// &lt;/summary&gt; /// &lt;param name=&quot;listenKey&quot;&gt;The listen key.&lt;/param&gt; /// &lt;param name=&quot;ct&quot;&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public async Task&lt;EmptyResponse?&gt; KeepAliveListenKeyAsync(string? listenKey, CancellationToken ct = default) { Guard.Against.NullOrWhiteSpace(listenKey, nameof(listenKey)); ct.ThrowIfCancellationRequested(); ThrowIfDisposed(); var endpoint = $&quot;/api/v3/userDataStream?listenKey={listenKey}&quot;; using var httpContent = new StringContent(string.Empty, Encoding.UTF8, &quot;application/x-www-form-urlencoded&quot;); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, endpoint); httpRequestMessage.Headers.Add(&quot;X-MBX-APIKEY&quot;, ApiKey); httpRequestMessage.Content = httpContent; using var httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, ct).ConfigureAwait(false); // Ensures OK status httpResponseMessage.EnsureSuccessStatusCode(); // Get response string var json = await httpResponseMessage.Content.ReadAsStringAsync(ct).ConfigureAwait(false); return json.FromJson&lt;EmptyResponse&gt;(); } /// &lt;summary&gt; /// Deletes a listen key. /// &lt;/summary&gt; /// &lt;param name=&quot;ct&quot;&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public async Task&lt;EmptyResponse?&gt; DeleteListenKeyAsync(string? listenKey, CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); ThrowIfDisposed(); var endpoint = $&quot;/api/v3/userDataStream?listenKey={listenKey}&quot;; using var httpContent = new StringContent(string.Empty, Encoding.UTF8, &quot;application/x-www-form-urlencoded&quot;); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, endpoint); httpRequestMessage.Headers.Add(&quot;X-MBX-APIKEY&quot;, ApiKey); httpRequestMessage.Content = httpContent; using var httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, ct).ConfigureAwait(false); // Ensures OK status httpResponseMessage.EnsureSuccessStatusCode(); // Get response string var json = await httpResponseMessage.Content.ReadAsStringAsync(ct).ConfigureAwait(false); return json.FromJson&lt;EmptyResponse&gt;(); } /// &lt;summary&gt; /// The standard dispose destructor. /// &lt;/summary&gt; ~BinanceRestClient() { Dispose(false); } /// &lt;summary&gt; /// Throw if disposed. /// &lt;/summary&gt; /// &lt;exception cref=&quot;ObjectDisposedException&quot;&gt;&lt;/exception&gt; private void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException($&quot;{nameof(BinanceRestClient)} has been disposed&quot;); } /// &lt;summary&gt; /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// &lt;/summary&gt; /// &lt;param name=&quot;disposing&quot;&gt;If this method is called by a user's code.&lt;/param&gt; protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { } _isDisposed = true; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T10:31:10.043", "Id": "533775", "Score": "0", "body": "Why is `BinanceApiProcessor` implemented as disposable? I don't see any cleanup. Same applies for `BinanceRestClient`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T12:06:05.883", "Id": "533782", "Score": "0", "body": "@PeterCsala, because it's incomplete. I'm about to implement the rest of the endpoints." } ]
[ { "body": "<p><code>BinanceApiProcessor</code> and <code>BinanceRestClient</code> are the same, and they've got me confused as I thought they were separate classes, but then I got that feeling that one of them might act as base class of the other. Then, after reading both multiple times, I saw that <code>BinanceApiProcessor</code> is meant to serve as a <code>Client</code>, while the <code>BinanceRestClient</code> used as a <code>Service</code>.</p>\n<p>(I'm not good in explaination, but I'll do my best).</p>\n<p>To give a clear idea for why <code>BinanceApiProcessor</code> should be <code>Client</code> and <code>BinanceRestClient</code> should be <code>Service</code>, given the current project,\nIf we say <code>BinanceRestClient</code> then generally, it's assumed this class is already configured to call Binance API service, and it will handle the communication between endpoints to provide an easier API to interact with the external API, adding some room to the consumer for customizations. (Such as configuring authentications and authorizations, headers, calling different endpoints with different versions ..etc.) So, <code>BinanceApiProcessor</code> fits this role. However, <code>BinanceRestClient</code> is a <code>Service</code> as <code>Service</code> would consume the <code>Client</code>s internally with fixed rules, and the scope would be narrowed for a single purpose, which would add more restriction to the consumer, by using preconfigured settings and endpoints with limited usage, and closed-arguments (e.g. <code>GetServerTimeAsync</code>, <code>GetBalancesAsync</code>).</p>\n<p>A few other small notes on the current classes before we go further :</p>\n<ul>\n<li><code>HttpClient</code> settings should be configured at <code>Startup</code>.</li>\n<li><code>BaseAddress</code>, <code>ApiKey</code>, and <code>SecretKey</code> should be stored in the <code>appsettings.json</code></li>\n<li>if the API provider have multiple API versions, try to implement each one of them separately, and then use a service class to consume them as needed.</li>\n<li><code>GetNonce</code> would be better if it's an extension with a more clearer name like <code>GetUtcNowTimestamp</code>.</li>\n<li><code>CreateSignature</code> would be better if it's an extension with a more clearer name like <code>CreateHMACSHA256Hash</code>.</li>\n<li><code>InvokeAsync</code> this is too general, <code>ProcessRequest</code> or <code>SendRequest</code> or <code>GetRequestResult</code> ..et. would be more clearer.</li>\n<li>when you need to create <code>QueryString</code> use <code>QueryBuilder</code> or <code>QueryString</code> or <code>KeyValuePair</code> or <code>Dictionary</code> to have more manageable, and readable query string, and avoiding human-mistakes.</li>\n<li>use a better naming conventions, and avoid unreadable names such as <code>ct</code> which would be better if you just do <code>cancellationToken</code>.</li>\n<li>Always use <code>DRY</code> principle, along with other good coding principles. This would make your coding-life easier, and your work will always be as pretty as a child face ;).</li>\n<li>I'm not against using <code>IDisposable</code> on new implementations, however, when the class is ready to be shipped, ensure that there is an actual using of the interface, if there is no objects to dispose, then remove the <code>IDisposable</code> implementation before shipping the class for the next stage. <em>(<code>.NET Core</code> ensure to avoid disposing objects that were created by the service collection as it's handled by the DI container)</em> <a href=\"https://stackoverflow.com/questions/50912160/should-httpclient-instances-created-by-httpclientfactory-be-disposed\">read more</a>.(thanks to @PeterCsala).</li>\n</ul>\n<p><strong>My Proposal</strong> (not the best, but it will drive you there):</p>\n<p>What I think would work better in your case is to rename <code>BinanceApiProcessor</code> to <code>BinanceApiClient</code> and <code>BinanceRestClient</code> to <code>BinanceApiService</code>.</p>\n<h2><strong>BinanceApiClient</strong></h2>\n<p>The purpose of this class is to have a pre-configured instance of <code>HttpClient</code> to fit the provider rules, and add an easy interface for the consumer to interact with.</p>\n<p>Example : (shorten for brevity)</p>\n<pre><code>internal class BinanceApiClient\n{\n private readonly string _apiKey;\n private readonly string _secretKey;\n private readonly IHttpClientFactory _httpClientFactory;\n \n private HttpClient HttpClient =&gt; _httpClientFactory.CreateClient();\n \n // this should be moved into an extension or helper class\n private long UtcNowTimestamp =&gt; DateTime.UtcNow.ToTimestamp();\n\n public BinanceApiClient(IHttpClientFactory httpClientFactory, string apiKey, string secretKey) { ... }\n\n // holds the Request arguments\n internal class RequestArguments { ... }\n\n // for building and processing the request arguments\n internal class RequestArgumentsBuilder&lt;T&gt; where T : class\n {\n // to generate the Api url along with queryStrings if applicable.\n private string GetEndPointUrl(string endpoint, bool useSecuritySignature = false, IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt; parameters = null) { ... }\n \n // the underlying request processer \n private async Task&lt;T&gt; ProcessRequest&lt;T&gt;(RequestArguments arguments, CancellationToken cancellationToken = default) where T : class { ... }\n \n // exposed processor would be called whenever the consumer is done building the request.\n public async Task&lt;T&gt; Process() { ... }\n }\n\n \n // this should be moved into an extension or helper class\n private string CreateSignature(string payload) { ... }\n\n //to return the builder instance for the general usage\n internal RequestArgumentsBuilder&lt;T&gt; PrepareRequest&lt;T&gt;() where T : class { ... }\n \n //an overload of PrepareRequest&lt;T&gt; that would be configured as replacement of `InvokeAsync`\n internal RequestArgumentsBuilder&lt;T&gt; PrepareRequest&lt;T&gt;(HttpMethod httpMethod, EndpointSecurityType securityType, CancellationToken cancellationToken = default) where T : class { ... }\n\n \n}\n</code></pre>\n<h2><strong>BinanceApiService</strong></h2>\n<p>The purpose of this class is to use <code>BinanceApiClient</code> internally, and configure the api endpoints for an easier access for the consumer.</p>\n<p>Example : (shorten for brevity)</p>\n<pre><code>public class BinanceApiService\n{\n private readonly string ApiKey = /* Get the value from the appsettings.json */;\n private readonly string SecretKey = /* Get the value from the appsettings.json */;\n private const string symbol = &quot;DOGEUSDT&quot;;\n\n private BinanceApiClient _client;\n\n public BinanceApiService(IHttpClientFactory httpClientFactory)\n {\n _client = new BinanceApiClient(httpClientFactory, ApiKey, SecretKey);\n }\n\n /*\n BaseAddress has been configured at Startup with https://api.binance.com/v3/\n if multiple versions are used, then a class for each version is recommanded.\n then, recall them in this class.\n */\n \n // basic processor with no content, no parameters, no security signature, no api-key\n public async Task&lt;EmptyResponse?&gt; TestConnectivityAsync(CancellationToken cancellationToken = default)\n {\n return await _client\n .PrepareRequest&lt;EmptyResponse&gt;()\n .Method(HttpMethod.Get)\n .Endpoint(&quot;ping&quot;)\n .WithCancellationToken(cancellationToken)\n .Process();\n }\n\n // basic processor with no content, and no parameters but with security signature, and api-key\n public async Task&lt;AccountInformationResponse?&gt; GetBalancesAsync(CancellationToken cancellationToken = default)\n {\n return await _client\n .PrepareRequest&lt;AccountInformationResponse&gt;()\n .Method(HttpMethod.Get)\n .Endpoint(&quot;account&quot;)\n .UseApiKey()\n .UseSecuritySignature()\n .WithCancellationToken(cancellationToken)\n .Process();\n }\n\n // basic processor with empty content, parameters and api-key, but no security signature\n public async Task&lt;EmptyResponse?&gt; KeepAliveListenKeyAsync(string? listenKey, CancellationToken cancellationToken = default)\n {\n\n return await _client\n .PrepareRequest&lt;EmptyResponse&gt;()\n .Method(HttpMethod.Put)\n .Endpoint(&quot;userDataStream&quot;)\n .WithEmptyStringContent()\n .WithParameters(new KeyValuePair&lt;string, string&gt;[]\n {\n new KeyValuePair&lt;string, string&gt;(&quot;listenKey&quot;, listenKey)\n }) \n .UseApiKey()\n .WithCancellationToken(cancellationToken)\n .Process();\n }\n \n // this calls the `InvokeAsync` replacement.\n public async Task&lt;AccountTradeResponse?&gt; GetMyTrades(CancellationToken cancellationToken = default)\n {\n return await _client\n .PrepareRequest&lt;AccountTradeResponse&gt;(HttpMethod.Get, EndpointSecurityType.UserData, cancellationToken)\n .Endpoint(&quot;myTrades&quot;)\n .WithParameters(new KeyValuePair&lt;string, string&gt;[]\n {\n new KeyValuePair&lt;string, string&gt;(&quot;symbol&quot;, symbol),\n new KeyValuePair&lt;string, string&gt;(&quot;recvWindow&quot;, &quot;5000&quot;)\n })\n .Process();\n }\n\n}\n</code></pre>\n<p>these are just examples, hope that will give you a better view.</p>\n<p>Here is the full implementation of <code>BinanceApiClient</code></p>\n<pre><code>internal class BinanceApiClient\n{\n private readonly string _apiKey;\n private readonly string _secretKey;\n private readonly IHttpClientFactory _httpClientFactory;\n \n private HttpClient HttpClient =&gt; _httpClientFactory.CreateClient();\n private long UtcNowTimestamp =&gt; DateTime.UtcNow.ToTimestamp();\n\n public BinanceApiClient(IHttpClientFactory httpClientFactory, string apiKey, string secretKey)\n {\n _apiKey = apiKey;\n _secretKey = secretKey;\n _httpClientFactory = httpClientFactory;\n }\n\n internal class RequestArguments\n {\n public HttpMethod Method { get; set; }\n public string Endpoint { get; set; }\n public IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt; Parameters { get; set; }\n public HttpContent Content { get; set; }\n public bool UseApiKey { get; set; }\n public bool UseSecuritySignature { get; set; }\n public CancellationToken CancellationTokenValue { get; set; }\n }\n\n internal class RequestArgumentsBuilder&lt;T&gt; where T : class\n {\n private readonly RequestArguments _args;\n private readonly BinanceApiClient _client;\n internal RequestArgumentsBuilder(BinanceApiClient client)\n {\n _args = new RequestArguments();\n _client = client;\n }\n\n public RequestArgumentsBuilder&lt;T&gt; Method(HttpMethod httpMethod)\n {\n _args.Method = httpMethod;\n return this;\n }\n\n public RequestArgumentsBuilder&lt;T&gt; Endpoint(string endpoint)\n {\n Guard.Against.NullOrWhiteSpace(endpoint, nameof(endpoint));\n _args.Endpoint = endpoint;\n return this;\n }\n\n public RequestArgumentsBuilder&lt;T&gt; WithParameters(IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt; parameters)\n {\n if(parameters != null)\n _args.Parameters = parameters;\n\n return this;\n }\n\n public RequestArgumentsBuilder&lt;T&gt; WithContent(HttpContent content)\n {\n if(content != null)\n _args.Content = content;\n\n return this;\n }\n\n public RequestArgumentsBuilder&lt;T&gt; WithEmptyStringContent(bool useWhenTrue = true)\n {\n if(useWhenTrue)\n _args.Content = new StringContent(string.Empty, Encoding.UTF8, &quot;application/x-www-form-urlencoded&quot;);\n \n return this;\n }\n\n public RequestArgumentsBuilder&lt;T&gt; UseApiKey(bool useApiKey = true)\n {\n _args.UseApiKey = useApiKey; \n return this;\n }\n\n public RequestArgumentsBuilder&lt;T&gt; UseSecuritySignature(bool useSecuritySignature = true)\n {\n _args.UseSecuritySignature = useSecuritySignature;\n return this;\n }\n\n public RequestArgumentsBuilder&lt;T&gt; WithCancellationToken(CancellationToken cancellationToken)\n {\n _args.CancellationTokenValue = cancellationToken;\n\n return this;\n }\n\n public async Task&lt;T&gt; Process()\n {\n return await _client.ProcessRequest&lt;T&gt;(_args, _args.CancellationTokenValue = default);\n }\n }\n\n private string CreateSignature(string payload)\n {\n Guard.Against.NullOrWhiteSpace(_secretKey, nameof(_secretKey));\n Guard.Against.NullOrWhiteSpace(payload, nameof(payload));\n\n using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(_secretKey));\n var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));\n return BitConverter.ToString(computedHash).Replace(&quot;-&quot;, &quot;&quot;).ToLowerInvariant();\n }\n\n private string GetEndPointUrl(string endpoint, bool useSecuritySignature = false, IEnumerable&lt;KeyValuePair&lt;string, string&gt;&gt; parameters = null)\n {\n string queryString = string.Empty;\n\n List&lt;KeyValuePair&lt;string, string&gt;&gt; kvps = parameters?.ToList() ?? new List&lt;KeyValuePair&lt;string, string&gt;&gt;();\n\n QueryBuilder queryBuilder;\n\n bool hasQueryString = false;\n\n if (kvps.Count &gt; 0)\n {\n queryBuilder = new QueryBuilder(kvps);\n hasQueryString = true;\n }\n else\n {\n queryBuilder = new QueryBuilder();\n }\n\n if (useSecuritySignature)\n {\n queryBuilder.Add(&quot;timestamp&quot;, UtcNowTimestamp.ToString());\n\n var uncodedQueryString = queryBuilder.ToQueryString().ToString()[1..];\n\n var signature = CreateSignature(uncodedQueryString);\n\n queryBuilder.Add(&quot;signature&quot;, signature);\n\n hasQueryString = true;\n }\n\n if (hasQueryString)\n queryString = queryBuilder.ToQueryString().ToUriComponent();\n\n\n return $&quot;{endpoint}{queryString}&quot;;\n }\n\n private async Task&lt;T&gt; ProcessRequest&lt;T&gt;(RequestArguments arguments, CancellationToken cancellationToken = default)\n where T : class\n {\n Guard.Against.NullOrWhiteSpace(arguments.Endpoint, nameof(arguments.Endpoint));\n\n cancellationToken.ThrowIfCancellationRequested();\n\n ThrowIfDisposed();\n\n using var httpRequestMessage = new HttpRequestMessage(arguments.Method, GetEndPointUrl(arguments.Endpoint, arguments.UseSecuritySignature, arguments.Parameters));\n\n if(arguments.UseApiKey)\n httpRequestMessage.Headers.Add(&quot;X-MBX-APIKEY&quot;, _apiKey);\n\n if (arguments.Content != null)\n httpRequestMessage.Content = arguments.Content;\n\n using var httpResponseMessage = await HttpClient.SendAsync(httpRequestMessage, cancellationToken);\n\n httpResponseMessage.EnsureSuccessStatusCode();\n\n var json = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken);\n\n return json.FromJson&lt;T&gt;();\n }\n\n internal RequestArgumentsBuilder&lt;T&gt; PrepareRequest&lt;T&gt;() where T : class\n {\n return new RequestArgumentsBuilder&lt;T&gt;(this);\n }\n\n internal RequestArgumentsBuilder&lt;T&gt; PrepareRequest&lt;T&gt;(HttpMethod httpMethod, EndpointSecurityType securityType, CancellationToken cancellationToken = default) where T : class\n {\n return\n PrepareRequest&lt;T&gt;()\n .WithEmptyStringContent(httpMethod == HttpMethod.Post || httpMethod == HttpMethod.Put || httpMethod == HttpMethod.Delete)\n .UseApiKey(securityType != EndpointSecurityType.None)\n .UseSecuritySignature(securityType is EndpointSecurityType.Trade or EndpointSecurityType.UserData)\n .WithCancellationToken(cancellationToken);\n }\n\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T02:25:50.427", "Id": "533958", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/131796/discussion-on-answer-by-isr5-custom-binance-api-wrapper-around-ihttpclientfactor)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T14:24:04.400", "Id": "270327", "ParentId": "270295", "Score": "2" } } ]
{ "AcceptedAnswerId": "270327", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T14:46:11.107", "Id": "270295", "Score": "0", "Tags": [ "c#", ".net", "asp.net-core" ], "Title": "Custom Binance API wrapper around IHttpClientFactory" }
270295
<p>Added the problem link below and my implementation of it. Took me a few hours to program. I have added comments to explain my thought process. <a href="https://cs50.harvard.edu/x/2021/psets/6/dna/" rel="nofollow noreferrer">Problem Link</a> Goal - To implement a program that identifies to whom a sequence of DNA belongs.</p> <ol> <li><p>should require first command-line argument the name of a CSV file containing the STR counts for a list of individuals and sits second command-line argument the name of a text file containing the DNA sequence to identify.</p> </li> <li><p>program should print an error message if incorrect no of arguments.</p> </li> <li><p>Your program should open the CSV file and dna file and read its contents into memory.</p> </li> <li><p>first row of the CSV file will be the column names. The first column will be the word name and the remaining columns will be the STR sequences themselves.</p> </li> <li><p>Your program should open the DNA sequence and read its contents into memory.</p> </li> <li><p>For each of the STRs (from the first line of the CSV file), your program should compute the longest run of consecutive repeats of the STR in the DNA sequence to identify.</p> </li> <li><p>If the STR counts match exactly with any of the individuals in the CSV file, your program should print out the name of the matching individual and no match if there are no matches.</p> </li> <li><p>You may assume that the STR counts will not match more than one individual.</p> </li> </ol> <pre class="lang-py prettyprint-override"><code>import csv import sys import re def main(): # checking if its correct no of arguments if len(sys.argv) != 3: print(&quot;Please specify both csv and text files&quot;) sys.exit(1) data = [] # opening the file into memory with open(sys.argv[1], &quot;r&quot;) as f: reader = csv.DictReader(f) for i in reader: data.append(i) # opening text sequence file and storing as string in seq with open(sys.argv[2]) as f: seq = f.read() # getting count from sequence countDict = count(data, seq) name = &quot;&quot; # comparing with data from csv file name = check(countDict, data) # printing the name of the match if name: print(name) else: print(&quot;No match&quot;) def count(data, seq): # getting STRs from database file so we know what STRs to search for keys = list(data[0].keys()) keys.pop(0) countDict = {} # creating a dictionary to store the count for the keys with key names for i in keys: countDict[i] = 0 strlist = [] # looping through the STRs to see if any matches in the string and if there are adding to the count for key in countDict: counter = 0 for i in range(len(seq)): end = len(key) # to get the length of the key if key == seq[i:end+i]: counter += 1 v = countDict[key] if not key == seq[i+end:end+i+end]: countDict[key] = max(v, counter) counter = 0 # resetting the counter to 0 else: countDict[key] = v i += len(key) return countDict def check(countDict, data): # empty string to store match name name = &quot;&quot; # going through the csv data file with potential matches ine at a time for i in data: # removing names from the data so we can do direct comparison with the count from dna found dictExceptName = dict(list(i.items())[1:]) # converting string count to int count for comparison for key, value in dictExceptName.items(): dictExceptName[key] = int(value) # comparing each person to dna found list if dictExceptName == countDict: name = i[&quot;name&quot;] # getting name of the person if there is a match return name main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T17:09:21.613", "Id": "533720", "Score": "2", "body": "While the question is excellent (perfect match for the site)! We ask that every question is _self contained_, what happens if your link dies? Please include the problemstatement from your link in your question =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T17:10:00.270", "Id": "533721", "Score": "0", "body": "As a second note you would be able to read the problem statement _in your code_ if you had added docstrings and proper documentation ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T17:34:39.020", "Id": "533726", "Score": "0", "body": "also included the problem statement, and i will look into how to add docstrings and do proper documentation thanks" } ]
[ { "body": "<p>Your code seems to work properly on the whole test suite provided which is a very good start.</p>\n<p>Also, splitting the logic in 2 parts, one preprocessing the counts and the other performing the comparison is a great way to proceeed.</p>\n<p>However, there are still various way to improve the code.</p>\n<p><strong>Style</strong></p>\n<p>Python has a style guide called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> which is definitly worth reading and trying to apply.</p>\n<p>Among other things, in your case, it would imply using <code>snake_case</code> instead of <code>camel_case</code>.</p>\n<p>Also, tiny invisible detail: your code contains trailing whitespace which can be cleaned up.</p>\n<p><strong>Documentation</strong></p>\n<p>The functions defined have very generic name which do not bring much information about what is being done. This could be improved with a better name but also by adding documentation to your function, for instance as <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a></p>\n<p><strong>More functions to count</strong></p>\n<p>The <code>count</code> function is quite complicated because it tries to apply some logic to various elements but also needs to worry about preprocessing and storing the results in a usable form.</p>\n<p>Here is my take on this:</p>\n<pre><code>def count_consecutive_repetitions(key, sequence):\n &quot;&quot;&quot;Count the number of consecutive repetitions of string 'key' are in string 'sequence'.&quot;&quot;&quot;\n search_str = key\n counter = 0\n pos = 0\n while True:\n pos = sequence.find(search_str, pos)\n if pos == -1:\n return counter\n counter += 1\n search_str += key\n\ndef count(data, seq):\n &quot;&quot;&quot;Get count for to be continued.&quot;&quot;&quot;\n # Extract relevant key strings from header row and get rid of first item\n keys = list(data[0].keys())[1:]\n\n # Get consecutive counts and store in a dictionnary\n return { k: count_consecutive_repetitions(k, seq) for k in keys }\n</code></pre>\n<p>Note: I've:</p>\n<ul>\n<li>rewritten the algorithm to search to avoid messing with string indices</li>\n<li>used a <a href=\"https://www.python.org/dev/peps/pep-0274/\" rel=\"nofollow noreferrer\">dictionnary comprehension</a> to create the dictionnary. This was not required but it is a nice tool to have in your toolkit</li>\n</ul>\n<p>Also, smaller functions are also easier to test. In my case, I wrote:</p>\n<pre><code>assert count_consecutive_repetitions(&quot;ABC&quot;, &quot;&quot;) == 0\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;DEF&quot;) == 0\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;ABDEFC&quot;) == 0\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;ABCDEF&quot;) == 1\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;DEFABC&quot;) == 1\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;DEFABCABCABCABCGHI&quot;) == 4\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;DEFABCDEFABCABCDEFABCABCABCGHI&quot;) == 3\n</code></pre>\n<p>In order to do things properly, these could have been written with a proper test framework but I was too lazy.</p>\n<p><strong>Improvements to <code>check</code></strong></p>\n<ul>\n<li><p>Instead of giving name the initial value &quot;&quot;, you could give the value <code>None</code>. It would be clearer in case of wrong data to make a difference between someone whose name was input as &quot;&quot; and the case where no relevant result was found. (You would need to update the main code accordingly with <code>name is None</code>).</p>\n</li>\n<li><p>Here again, we can use dictionnary comprehension to perform all the operations you are interested: filtering and converting.</p>\n</li>\n</ul>\n<p>Here is what I got:</p>\n<pre><code>def check(countDict, data):\n &quot;&quot;&quot;Get elements in data matching the string count in `countDict`.&quot;&quot;&quot;\n # Going through the csv data file with potential matches ine at a time\n for i in data:\n # Get count by converting data to integers (except for the name) \n count = { k: int(v) for k, v in i.items() if k != 'name' }\n # Comparing each person to dna found list\n if count == countDict:\n return i[&quot;name&quot;]\n return None\n</code></pre>\n<p>Now, to make the filtering (based on string rather than index) more consistent in the other function, we could update it to:</p>\n<pre><code>def count(data, seq):\n &quot;&quot;&quot;Get count for to be continued.&quot;&quot;&quot;\n # Get consecutive counts and store in a dictionnary\n return { k: count_consecutive_repetitions(k, seq) for k in data[0].keys() if k != 'name' }\n\n</code></pre>\n<p><strong>Final code</strong></p>\n<p>Performing various cosmetic changes, here is my final version of the code:</p>\n<pre><code>import csv\nimport sys\n\n\ndef main():\n # Check number of arguments\n if len(sys.argv) != 3:\n print(&quot;Please specify both csv and text files&quot;)\n sys.exit(1)\n\n # Get list of individuals\n with open(sys.argv[1], &quot;r&quot;) as f:\n data = list(csv.DictReader(f))\n\n # Get DNA sequence\n with open(sys.argv[2]) as f:\n seq = f.read()\n\n # Get count of repeatited keys\n count_dict = count_repeated_keys(data, seq)\n\n # Get name of person with same count\n name = get_name_with_same_count(data, count_dict)\n\n # Print result\n print(&quot;No match&quot; if name is None else name)\n\n\ndef count_consecutive_repetitions(key, sequence):\n &quot;&quot;&quot;Count the number of consecutive repetitions of string 'key' are in string 'sequence'.&quot;&quot;&quot;\n search_str = key\n counter = 0\n pos = 0\n while True:\n pos = sequence.find(search_str, pos)\n if pos == -1:\n return counter\n counter += 1\n search_str += key\n\n\ndef count_repeated_keys(data, seq):\n &quot;&quot;&quot;Get repeated count for each key from data.&quot;&quot;&quot;\n # Get consecutive counts and store in a dictionnary\n return {\n k: count_consecutive_repetitions(k, seq) for k in data[0].keys() if k != &quot;name&quot;\n }\n\n\ndef get_name_with_same_count(data, count_dict):\n &quot;&quot;&quot;Get element in data matching the string count in `count_dict`.&quot;&quot;&quot;\n # Going through the csv data file with potential matches ine at a time\n for i in data:\n # Get count by converting data to integers (except for the name)\n count = {k: int(v) for k, v in i.items() if k != &quot;name&quot;}\n # Comparing each person to dna found list\n if count == count_dict:\n return i[&quot;name&quot;]\n return None\n\n\nmain()\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;&quot;) == 0\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;DEF&quot;) == 0\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;ABDEFC&quot;) == 0\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;ABCDEF&quot;) == 1\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;DEFABC&quot;) == 1\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;DEFABCABCABCABCGHI&quot;) == 4\nassert count_consecutive_repetitions(&quot;ABC&quot;, &quot;DEFABCDEFABCABCDEFABCABCABCGHI&quot;) == 3\n</code></pre>\n<p><strong>Edit</strong></p>\n<p>I just realised that <code>count_consecutive_repetitions</code> could be simplified as:</p>\n<pre><code>def count_consecutive_repetitions(key, sequence):\n &quot;&quot;&quot;Count the number of consecutive repetitions of string 'key' are in string 'sequence'.&quot;&quot;&quot;\n pos = 0\n for c in itertools.count(start=1):\n pos = sequence.find(key * c, pos)\n if pos == -1:\n return c - 1\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T02:15:47.413", "Id": "533957", "Score": "0", "body": "thanks thats really really helpful, i am just starting out , even this took me a few hours to implement. I am gonna look at the style guide and the docstrings. Thank You" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T18:10:16.270", "Id": "270391", "ParentId": "270298", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T16:56:22.707", "Id": "270298", "Score": "1", "Tags": [ "python", "beginner", "algorithm", "programming-challenge" ], "Title": "DNA Challenge from CS50" }
270298
<p>Alright, this is one of my first real projects in python, it's basically a one-way chat where the server sends away an encoded message. The logic of it is pretty simple and I know there is some unnecessary code in there. I have also made a simple client who receives the messages and decrypts it, based on if the user input == the decrypted version of the password. Would love to get some tips on how I could improve it.</p> <p>So initially the program was supposed to encrypt a message the user enter, then create a password and encrypt that password. Then it would store this data in a text file, with the message as the name and the password as the content. Then when you wanted to open it you were supposed to enter the decrypted version of the password, and then somewhere around here I started rethinking it.</p> <p>This with creating the file and so is still in the script, but how I intend it to work now is: You enter your message in the first text box, press the button and the message will be encrypted and a password will be created which also would be displayed. Which then also gets encrypted.</p> <p>Then it should send this in the format of a dictionary over to a client. Then the client is processing this data sent by asking for the password decrypted and if it's correct it will decrypt the message. (The code below is only the server since I want to finish that first)</p> <pre><code>from tkinter import * import os import string import random import socket import pickle window = Tk() window.title(&quot;Password Crypter&quot;) window.configure(background=&quot;white&quot;) def Server(): HEADERSIZE = 10 host = '' port = 50010 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((host,port)) s.listen(5) while True: conn, addr = s.accept() print(f&quot;Connection fom {addr} has been established!&quot;) msg = pickle.dumps(d) msg = bytes(f'{len(msg):&lt;{HEADERSIZE}}', &quot;utf-8&quot;) + msg conn.send(msg) def randomword(length): letters = string.ascii_lowercase global get get = ''.join(random.choice(letters) for i in range(length)) print(get) def click(): global sample_string global inputText inputText = textEntry.get() encoder() def click1(): global inputText1 inputText1 = textEntry1.get() accesDecoder() def encoder(): global sample_string global inputText sample_string = inputText.lower() char_to_replace = {'s': 'X', 'a': 'Y', 'i': 'Z', 'b': 'W', 'k': 'V', 'o': 'U', 'e': 'T', 'c': 'S', 'l': 'R', 'j': 'Q', 'h': 'P', 'm': 'O', 'r': 'N', 'd': 'M', 'q': 'L', 'u': 'K', 'p': 'J', 'y': 'I', 's': 'H', 'f': 'G', 'w': 'F', 't': 'E', 'n': 'D', 'x': 'C', 'r': 'B', 'v': 'A'} for key, value in char_to_replace.items(): sample_string = sample_string.replace(key, value) Label (window, text=sample_string, bg=&quot;white&quot;, fg=&quot;black&quot;, font=&quot;none 12 bold&quot;) .grid(row=3, column=0, sticky=W) randomword(20) passCrypter() Label (window, textvariable=passwordVar, bg=&quot;white&quot;, fg=&quot;black&quot;, font=&quot;none 12 bold&quot;) .grid(row=4, column=0, sticky=W) passwordVar.set(get) with open(sample_string + '.txt', 'w') as messageFile: messageFile.write(sample_string2) add_element(d, sample_string, sample_string2) print(d) Server() def add_element(dict, key, value): if key not in dict: dict[key] = [] dict[key].append(value) d = {} passwordVar = StringVar() decrypted = StringVar() wrongCode = StringVar() def accesDecoder(): with open(sample_string + '.txt', 'r') as messageFile: global code code = messageFile.read() passDecrypt() if inputText1 == sample_string3 or inputText1 == sample_string: print(&quot;You have accesed the decoder.&quot;) decrypted.set('') decoder() else: Label (window, textvariable=decrypted, bg=&quot;white&quot;, fg=&quot;black&quot;, font=&quot;none 12 bold&quot;) .grid(row=4, column=1, sticky=W) decrypted.set(&quot;Wrong code, try again.&quot;) def decoder(): sample_string1 = sample_string char_to_replace1 = {'X': 's', 'Y': 'a', 'Z': 'i', 'W': 'b', 'V': 'k', 'U': 'o', 'T': 'e', 'S': 'c', 'R': 'l', 'Q': 'j', 'P': 'h', 'O': 'm', 'N': 'r', 'M': 'd', 'L': 'q', 'K': 'u', 'J': 'p', 'I': 'y', 'H': 's', 'G': 'f', 'F': 'w', 'E': 't', 'D': 'n', 'C': 'x', 'B': 'r', 'A': 'v'} for key, value in char_to_replace1.items(): sample_string1 = sample_string1.replace(key, value) print(sample_string1) decrypted.set(sample_string1) Label (window, textvariable=decrypted, bg=&quot;white&quot;, fg=&quot;black&quot;, font=&quot;none 12 bold&quot;) .grid(row=3, column=1, sticky=W) def passCrypter(): global sample_string2 sample_string2 = get char_to_replace2 = {'s': 'X', 'a': 'Y', 'i': 'Z', 'b': 'W', 'k': 'V', 'o': 'U', 'e': 'T', 'c': 'S', 'l': 'R', 'j': 'Q', 'h': 'P', 'm': 'O', 'r': 'N', 'd': 'M', 'q': 'L', 'u': 'K', 'p': 'J', 'y': 'I', 's': 'H', 'f': 'G', 'w': 'F', 't': 'E', 'n': 'D', 'x': 'C', 'r': 'B', 'v': 'A'} for key, value in char_to_replace2.items(): sample_string2 = sample_string2.replace(key, value) def passDecrypt(): global sample_string3 sample_string3 = code char_to_replace3 = {'X': 's', 'Y': 'a', 'Z': 'i', 'W': 'b', 'V': 'k', 'U': 'o', 'T': 'e', 'S': 'c', 'R': 'l', 'Q': 'j', 'P': 'h', 'O': 'm', 'N': 'r', 'M': 'd', 'L': 'q', 'K': 'u', 'J': 'p', 'I': 'y', 'H': 's', 'G': 'f', 'F': 'w', 'E': 't', 'D': 'n', 'C': 'x', 'B': 'r', 'A': 'v'} for key, value in char_to_replace3.items(): sample_string3 = sample_string3.replace(key, value) textEntry = Entry(window, width=60, bg=&quot;white&quot;) textEntry.grid(row=1, column=0, sticky=W) Button(window, text=&quot;Submit Text&quot;, width=13, command=click) .grid(row=2, column=0, sticky=W) textEntry1 = Entry(window, width=60, bg=&quot;white&quot;) textEntry1.grid(row=1, column=1, sticky=W) Button(window, text=&quot;Submit Code&quot;, width=13, command=click1) .grid(row=2, column=1, sticky=W) window.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T18:14:39.627", "Id": "533729", "Score": "1", "body": "I would encourage you to edit your question to explain how the code is intended to be used. I ran it and a window pops up with two text boxes. What should I do? I typed something in one and then the program seemed to hang, so I gave up. Later I saw a `PZ.txt` file had been written and it contained an encrypted data structure. You need to explain the intended usage more explicitly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T18:16:30.867", "Id": "533730", "Score": "0", "body": "Alright, will do" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T18:26:51.297", "Id": "533731", "Score": "0", "body": "Changed it up, hopefully, you're able to understand what I mean." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T18:01:22.633", "Id": "270302", "Score": "0", "Tags": [ "python", "tkinter", "socket", "encoding" ], "Title": "One-way chat which encode messages, this is the server side" }
270302
<p>The code below takes a list of users and displays two lists</p> <ol> <li>Refused users</li> <li>Admitted users</li> </ol> <p>Sample output:</p> <blockquote> <p>Refuse: Phil, Lola.</p> <p>Admit: Chris, Anne, Colin, Terri, Sam, Kay, Bruce.</p> </blockquote> <p>Any feedback is highly appreciated.</p> <pre><code>const people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce']; let refusedPeople = ['Lola', 'Phil'] let admittedPeople = people.filter(name =&gt; !refusedPeople.includes(name)) const admitted = document.querySelector('.admitted'); const refused = document.querySelector('.refused'); admitted.textContent = 'Admit: '; refused.textContent = 'Refuse: ' const refusedIndices = refusedPeople.map(x =&gt; people.indexOf(x)).sort() const admittedIndices = admittedPeople.map(x =&gt; people.indexOf(x)).sort() for (let [index, person] of people.entries()) { refusedPeople.includes(person) ? refusedIndices.slice(-1)[0] === index ? refused.textContent += `${person}.` : refused.textContent += `${person}, ` : admittedIndices.slice(-1)[0] === index ? admitted.textContent += `${person}.` : admitted.textContent += `${person}, `; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T18:32:32.957", "Id": "533732", "Score": "4", "body": "Please state the specification for the code. What does it do? The title should state the purpose of the code/application." } ]
[ { "body": "<p>Avoid performing side-effects in the middle of a ternary expression. If you're not using the resulting value of the ternary operation, then you're using it wrong and should be using an ordinary if-then instead.</p>\n<p>Also, be consistent with your usage of semicolons, and let/const.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'];\n\nconst refusedPeople = ['Lola', 'Phil'];\nconst admittedPeople = people.filter(name =&gt; !refusedPeople.includes(name));\nconst admitted = document.querySelector('.admitted');\nconst refused = document.querySelector('.refused');\nadmitted.textContent = 'Admit: ';\nrefused.textContent = 'Refuse: ';\n\nconst refusedIndices = refusedPeople.map(x =&gt; people.indexOf(x)).sort();\n\nconst admittedIndices = admittedPeople.map(x =&gt; people.indexOf(x)).sort();\n\nfor (const [index, person] of people.entries()) {\n if (refusedPeople.includes(person)) {\n if (refusedIndices.slice(-1)[0] === index) {\n refused.textContent += `${person}.`;\n } else {\n refused.textContent += `${person}, `;\n }\n } else if (admittedIndices.slice(-1)[0] === index) {\n admitted.textContent += `${person}.`;\n } else {\n admitted.textContent += `${person}, `;\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p class=\"admitted\"&gt;&lt;/p&gt;\n&lt;p class=\"refused\"&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Next, I'm going to split the for loop into two. You seem to have two independent things going on in that loop anyways. If you're dealing with a refused person, then you update the refused text, and if you're dealing with an admitted person, then you update admitted text. Why not just independently loop over your refusedPeople and admittedPeople arrays instead?</p>\n<p>(This code sample assumes two things. 1. Your refusedPeople array won't contain anything that's not also in people. 2. The order of output is not important. If either of these matters to you, I'll let you figure out how to best incorporate those details).</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'];\n\nconst refusedPeople = ['Lola', 'Phil'];\nconst admittedPeople = people.filter(name =&gt; !refusedPeople.includes(name));\n\nconst admitted = document.querySelector('.admitted');\nconst refused = document.querySelector('.refused');\n\nadmitted.textContent = 'Admit: ';\nrefused.textContent = 'Refuse: ';\n\nfor (const [index, person] of refusedPeople.entries()) {\n if (index === refusedPeople.length - 1) {\n refused.textContent += `${person}.`;\n } else {\n refused.textContent += `${person}, `;\n }\n}\n\nfor (const [index, person] of admittedPeople.entries()) {\n if (index === admittedPeople.length - 1) {\n admitted.textContent += `${person}.`;\n } else {\n admitted.textContent += `${person}, `;\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p class=\"admitted\"&gt;&lt;/p&gt;\n&lt;p class=\"refused\"&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Perhaps you see those two for loops and quickly think &quot;oh, those are very similar, I wonder if I can extract the duplicate parts into some helper function&quot;. Turns out, the language already provides just the helper function you need - <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"noreferrer\">array.join()</a>. The use of array.join will let us toss both of these for loops.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'];\nconst refusedPeople = ['Lola', 'Phil'];\nconst admittedPeople = people.filter(name =&gt; !refusedPeople.includes(name));\n\nconst admittedElement = document.querySelector('.admitted');\nadmittedElement.textContent = `Admit: ${admittedPeople.join(', ')}.`;\n\nconst refusedElement = document.querySelector('.refused');\nrefusedElement.textContent = `Refuse: ${refusedPeople.join(', ')}.`;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p class=\"admitted\"&gt;&lt;/p&gt;\n&lt;p class=\"refused\"&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Now that's looking pretty good :).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T08:12:17.967", "Id": "533767", "Score": "1", "body": "Really like you rewrite!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:51:30.483", "Id": "533798", "Score": "0", "body": "Thanks! Isn't it more appropriate to use \"let\" in loop variables?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T16:10:13.093", "Id": "533802", "Score": "2", "body": "\"let\" is required in a c-style loop `for (let i = 0; i < whatever; ++i)`, because the same binding persists across all iterations, and you reassign to it between each iteration. In a for-of loop, you're effectively creating a new loop variable with each iteration, thus no reassignment is happening, so \"const\" is appropriate.\n\nThe use of \"const\" in for-of will also self-document the fact that you're not reassigning to the loop variable in the middle of your for loop's body." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T00:24:38.043", "Id": "533888", "Score": "0", "body": "Your output differs from OP's. Names can not be refused if they are not in the list of `people` IE You can't be refused of you don't ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T02:38:33.320", "Id": "533891", "Score": "0", "body": "@Blindman67 Yes - that was one of the assumptions I stated my refactoring made - \"Your refusedPeople array won't contain anything that's not also in people\". If this assumption is false, then you're right, and the O.P. would need to modify the answer to fit their needs, or to use your answer." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T00:40:43.560", "Id": "270313", "ParentId": "270303", "Score": "5" } }, { "body": "<h2>Using a Set</h2>\n<p>You are best to use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set\">Set</a> to reduce the complexity that comes with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array includes\">Array.includes</a>.</p>\n<p>Ignoring the sort. Your code has a complexity of <span class=\"math-container\">\\$O(n^2)\\$</span> however using a set will reduce that to <span class=\"math-container\">\\$O(n)\\$</span></p>\n<p>Example of <span class=\"math-container\">\\$O(n^2)\\$</span></p>\n<pre><code>dataA.filter(v =&gt; dataB.includes(v));\n</code></pre>\n<p>Example of same task with <span class=\"math-container\">\\$O(n)\\$</span> complexity</p>\n<pre><code>set = new Set(dataB);\ndataA.filter(v =&gt; set.has(v));\n</code></pre>\n<h2>Functions</h2>\n<p>Even if writing examples always create the code of interest as a named function. See rewrite <code>ListAdmittance</code></p>\n<p>Also to reduce the verbosity (repeated noise) of your code use functions to perform repeated tasks. In rewrite the functions <code>query</code> and <code>strList</code> reduce the need to repeat the long <code>document.querySelector(</code> and simplifies the listing of names.</p>\n<h2>Sort</h2>\n<p>You need only <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array sort\">Array.sort</a> the list of <code>people</code> not the list of refused people. The <code>refused</code> people must be in the <code>people</code> list and thus you use the people list to order the refused list.</p>\n<p>In the example the <code>sort</code> is performed outside the function <code>listAdmittance</code> should not be part of the functions role.</p>\n<h2>Rewrite</h2>\n<p>The rewrite aims to reduce complexity and code noise, and be reusable.</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 query = (qStr, root = document) =&gt; root.querySelector(qStr);\nconst strList = (items, s = \"[\", del = \", \", e = \".\") =&gt; s + items.join(del) + e;\n\nlistAdmittance(\n ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'].sort(),\n ['Phil', 'Lola', `Bill`]\n);\n\nfunction listAdmittance(all, refused) {\n const rMap = new Set(refused);\n query(\"#admitted\").textContent = strList(all.filter(n =&gt; !rMap.has(n)), \"Admit: \");\n query(\"#refused\").textContent = strList(all.filter(n =&gt; rMap.has(n)), \"Refuse: \");\n}\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"admitted\"&gt;&lt;/div&gt;\n&lt;div id=\"refused\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You could also avoid the need to query the document as follows</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>listAdmittance(\n ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce'].sort(),\n ['Phil', 'Lola', `Bill`]\n);\nconst strList = (items, s = \"[\", del = \", \", e = \".\") =&gt; s + items.join(del) + e;\nfunction listAdmittance(all, refused) {\n const rMap = new Set(refused);\n admittedEl.textContent = strList(all.filter(n =&gt; !rMap.has(n)), \"Admit: \");\n refusedEl.textContent = strList(all.filter(n =&gt; rMap.has(n)), \"Refuse: \");\n}\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"admittedEl\"&gt;&lt;/div&gt;\n&lt;div id=\"refusedEl\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T01:04:28.000", "Id": "270373", "ParentId": "270303", "Score": "2" } } ]
{ "AcceptedAnswerId": "270313", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T18:08:46.863", "Id": "270303", "Score": "0", "Tags": [ "javascript", "functional-programming", "ecmascript-6" ], "Title": "Processing list of users- filtering out from refused list" }
270303
<p>I've implemented a menu system where all input calls ultimately go through <code>io_getline</code>, a function which reads a line of input up to the max buffer size or newline (the rest of the line is discarded if it exceeds the buffer size) and returns the number of characters written, or -1 if an EOF is encountered. When an EOF is encountered, io_getline will, from then on, permanently be in a state where the first character it attempts to read yields EOF (which is not a character) and it will always return -1. This is intentional, as I will soon demonstrate:</p> <pre><code>/* Does the same thing as getchar but with guaranteed EOF persistence */ static int getchar_eof(void) { unsigned char ch; static int eof_encountered; if(eof_encountered) return EOF; fread(&amp;ch, 1, 1, stdin); if(feof(stdin)){ eof_encountered = 1; return EOF; } return ch; } ssize_t io_getline(char *buffer, size_t bufsz) { int ch; char *bufp = buffer; while((ch = getchar_eof()) != EOF &amp;&amp; ch != '\n') if(buffer != NULL &amp;&amp; (size_t)(bufp - buffer) &lt; bufsz) *bufp++ = ch; if(ch == EOF) return -1; return bufp - buffer; } /* two functions that use io_getline: */ int generic_getter_str(struct menu_page *unused) { (void)unused; ssize_t nwritten; showprompt(); if((nwritten = io_getline(menustate.input_str, 32)) == -1) return CBRET_EOF; // causes caller to end the program if(nwritten == 0) return CBRET_RETURNTOPARENT; return CBRET_DONOTHING; } void waitcontinue(void) { printf(&quot;Press Enter to continue.&quot;); io_getline(NULL, 0); io_clearscreen(); } </code></pre> <p>A little bit about the menu structure: each page has three callbacks that are called in order: entry, getter and handler. The entry's job is to do anything that needs to be done before getting user input, the getter's job is to get input (<code>str</code>, <code>u32</code>, <code>char_or_u32</code>, and <code>none</code>) from the user, and handle EOF by ending the program, and the handler's job is to interpret the input obtained by the getter (if any). <code>waitcontinue</code> is called in some handler functions for the purpose of pagination, while <code>generic_getter_str</code> is one of the four getter functions.</p> <p>As <code>waitcontinue</code> is not a getter, it does not handle EOF, but EOF will cause it to finish (this is expected). And this design decision is where I thankfully discovered a weird nuance with <code>getchar</code>, wherein it doesn't always persist EOF status. It is possible for getchar to return EOF, be called again, and <em>prompt the user for input post-EOF</em>. I managed to produce this behavior on both a repl.it Linux VM (repl.it/languages/c, without being logged in) and minGW on Windows (where I discovered it).</p> <p>This goes against my understanding that getchar should constantly return EOF after the first time. The result of this is that any time <code>waitcontinue</code> is called in an environment where getchar behaves in this way, pressing <code>ctrl-d</code> (or <code>ctrl-z enter</code> if on Windows), the program will receive the EOF, skip the one waitcontinue call, and then continue to run, when the intent is for it to &quot;bubble out&quot; until a getter inevitably receives the EOF and ends the program.</p> <p>This led me to re-implement getchar to guarantee the behavior that I want and expect, and it works fantastically, however, this is fascinating to me, and I now wonder if there are other nuances I might be missing here.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T19:01:36.870", "Id": "533733", "Score": "0", "body": "The project this is from is [mpassw](https://gitlab.com/bradenbest/mpassw/). A Metroid password generator I've been writing for the past couple weeks. It works on both Linux and Windows (MinGW). I have not tested it with a more windows-y compiler like MSVC, nor have I tested it on Mac. But I have no reason to believe it wouldn't work just fine on OS X." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T07:23:55.440", "Id": "533763", "Score": "0", "body": "Terminology problem: \"_first character it reads is EOF_\" - but `EOF` is **not a character**. I'm not merely being pedantic here, because that's the thinking that leads to `char c = getchar()`, for example, or the idea that EOF is a single \"thing\" that can be consumed (or \"received\")." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T21:29:17.133", "Id": "533883", "Score": "0", "body": "True, I was burned by `char c = getchar()` some years ago, which was how I learned that you really do need an `int`, as EOF is defined in terms of `int` and is out of range for even `unsigned char`. Poor wording on my part. I'd edit the question to mention what the manpage says, but I see an earlier post on my profile mentioning that apparently there's a rule against that. I imagine the rule is about preserving the code as it was first posted so that the answers make sense, but now that you've mentioned the terminology, I'm not sure if it's appropriate to change it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T21:35:23.573", "Id": "533884", "Score": "0", "body": "I'll go ahead and make the edit since 1. it's not a code change and 2. the onus is a comment rather than an answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T07:58:38.347", "Id": "533899", "Score": "0", "body": "Yes, editing to improve the prose to make it clearer, etc, is encouraged, even when you have answers. It's just code changes we have to be more careful with, because that can make the answers seem nonsensical. So you did the right thing. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T08:04:58.110", "Id": "533901", "Score": "0", "body": "I don't have a review because I don't know how to trigger the transient EOF thing you describe - are you using `freopen()` or `fseek()` to clear the EOF in between calls? Or are you reading from a regular file which is getting appended to (perhaps outside this process)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T07:36:31.250", "Id": "534061", "Score": "0", "body": "@TobySpeight In my testing on MinGW on Windows, when stdin is coming from a user, and they send an EOF, and then getchar is called again after that, the terminal will prompt the user again for input. On my linux machine with stock gcc+glibc, sending one EOF is sufficient to make all future calls to getchar immediately return EOF until the program ends. You can send an EOF on a windows cmd terminal with `ctrl+z` followed by `enter`, whereas on a linux shell like bash, this is done with `ctrl+d`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T07:43:31.537", "Id": "534062", "Score": "0", "body": "You could try invoking it directly from my program by just changing the call to `getchar_eof` to `getchar` in `io.c`, and then modifying the makefile as necessary. Then just enter the detailed summary menu and send an EOF. As per my tests, with glibc, it should immediately exit, and with mingw, it should eat the EOF and continue running, exhibiting the (what I consider to be a) bug." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T23:03:04.597", "Id": "534116", "Score": "1", "body": "\"I thankfully discovered a weird nuance with getchar, wherein it doesn't always persist EOF status.\" --> this is either non-conforming C behavior or a false positive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T23:09:36.267", "Id": "534118", "Score": "0", "body": "`getchar()` can return `EOF` and then non-`EOF` due to input error in the first character and not the 2nd, yet this is rare. @BradenBest What do you want `int getchar_eof(void)` to do in this case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T16:51:44.540", "Id": "534156", "Score": "0", "body": "I was going to answer \"return EOF\", but since feof() always works even when a non-compliant getchar misbehaves, I was able to remove getchar_eof. That said, the way I've done it is io_getline will now return separate values for EOF and error in case I decide I want to handle errors differently in the future, but for now, the functions that call io_getline treat both EOF and error as an EOF" } ]
[ { "body": "<p><strong>Redundant code</strong></p>\n<p><code>getchar_eof()</code> essentially mimics <code>getchar()</code> and <code>feof()</code>. It fails to work well when <code>ferror()</code> is true or <code>stdin</code> is re-opened.</p>\n<p><code>getchar()</code> already returns <code>EOF</code> when <code>stdin</code> end-of-file flag is set.</p>\n<p>Instead use, <code>getchar()</code>, <code>feof()</code>, <code>ferror()</code>.</p>\n<p><strong>Bug</strong></p>\n<p><code>int getchar_eof(void)</code> returns junk (indeterminant data) when a rare input error encountered as the return value of <code>fread()</code> was not used.</p>\n<p><strong>Bug</strong></p>\n<p><code>io_getline()</code> returns -1 when end-of-file occurs, even if some data was read. To be like <code>fgets()</code>, only return -1 when 1) end-of-file occurs and nothing read or 2) input error.</p>\n<p><strong>Non-portable type</strong></p>\n<p><code>ssize_t</code> is not defined in standard C.</p>\n<p><strong><code>generic_getter_str()</code> misnamed</strong></p>\n<p><code>generic_getter_str()</code> does not get a <em>string</em> (hinted by the <code>_str</code>) as no <em>null character</em> terminated array is gotten.</p>\n<p><code>io_getline(buffer, ...)</code> does not form a <em>string</em> in <code>buffer</code> as it lacks a <em>null character</em>.</p>\n<p><strong>Repetitive test</strong></p>\n<p><code>if(buffer != NULL &amp;&amp; (size_t)(bufp - buffer) &lt; bufsz)</code> repeated tests <code>buffer != NULL</code>. Once is enough.</p>\n<pre><code>if(buffer != NULL) bufsz == 0; // Test once\nwhile((ch = getchar_eof()) != EOF &amp;&amp; ch != '\\n')\n if((size_t)(bufp - buffer) &lt; bufsz)\n *bufp++ = ch;\n</code></pre>\n<hr />\n<p>Candidate alternative - untested.</p>\n<pre><code>int io_getline(size_t bufsz, char buffer[bufsz]) {\n if (bufsz &gt; INT_MAX) {\n bufsz = INT_MAX; // Or some other error handling\n }\n if (buffer == NULL) {\n bufsz = 0;\n }\n\n int ch;\n char *bufp = buffer;\n bool data_read = false;\n\n while ((ch = getchar()) != EOF) {\n data_read = true;\n if (ch == '\\n') {\n break;\n }\n if ((size_t) (bufp - buffer) + 1u &lt; bufsz) {\n *bufp++ = (char) ch;\n }\n }\n\n if (ch == EOF) {\n if (feof(stdin)) {\n if (!data_read) {\n return -1;\n }\n } else {\n return -1; // Input error\n }\n }\n\n if ((size_t) (bufp - buffer) &lt; bufsz) {\n *bufp = '\\0'; // Form a string if able\n }\n\n return (int) (bufp - buffer);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T00:44:23.190", "Id": "534122", "Score": "0", "body": "\"io_getline() returns -1 when end-of-file occurs, even if some data was read.\" this is actually not a bug. The input is expected to come from a buffered commandline, i.e. a user types a line of input and terminates it by hitting enter. A line terminated by EOF is not a valid line, so it is discarded, just like excess input beyond the buffer size." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T00:45:28.873", "Id": "534123", "Score": "0", "body": "And `generic_getter_str` is not misnamed. Just because it's not a null-terminated string doesn't make it not a string. The function used to be named `generic_getter_char`, but after the introduction of `generic_getter_char_or_u32`, (single char or u32), it no longer made sense to keep it named `char`. I suppose I could name it `_charvec`. That said, in the wider context of the program, I make a point to avoid using null-terminated strings as data structures, and thus avoid `str*` lib functions in favor of their `mem*` counterparts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T00:53:55.303", "Id": "534125", "Score": "0", "body": "The only string functions that appear in the program are used with string literals, and when a string function has to interact with one of my buffers, an intermediary buffer is used to keep their behavior under control (there is only one such case)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T01:55:11.923", "Id": "534126", "Score": "1", "body": "@BradenBest \"I make a point to avoid using null-terminated strings\" --> C does not specify any context where a _string_ is not null character terminated. C lib does define \"A string is a contiguous sequence of characters terminated by and including the first null character.\" Of course you can use _string_ in some other context, but then that risks misunderstanding with the spec. and with users as evidenced by these comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T01:57:19.923", "Id": "534127", "Score": "0", "body": "@BradenBest \"The input is expected to come from a buffered commandline, i.e. a user types a line of input and terminates it by hitting enter.\" --> OK, define it as you wish, yet it still differs from `fgets()`, a function commonly used to get lines and does serve as a model for many get line like code. IIRC, *nix `getine()` also does not discard a last line lacking a `'\\n'`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T14:42:09.980", "Id": "534143", "Score": "0", "body": "Regarding `ssize_t` and `getchar_eof`: I wasn't aware the type was POSIX-exclusive. I've opted instead to use `size_t` and define an absolute maximum line size for my program (4KiB). The EOF signal, which is returned on feof and ferror, is no longer `-1`, but it is a value outside of the range `0..IO_GETLINE_MAX`. I will also be getting rid of `getchar_eof`, as I have confirmed through testing that `feof()` returns correctly even when a non-conformant getchar is misbehaving." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T14:44:23.957", "Id": "534144", "Score": "0", "body": "`size_t` may seem overkill for 4KiB, but in my opinion, `size_t` is clearer about its purpose here than e.g. `uint16_t` or `int`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T17:23:09.490", "Id": "534160", "Score": "0", "body": "Thanks for the feedback, Chux. I've implemented all of your notes except for bug #2 which I do not see as a bug (`io_getline` is not meant to act exactly like `fgets`, otherwise I'd just use/wrap fgets). Instead, I have added \"why\" comments at the head of the function to document why the behavior is correct. I've +1'd your answer and named you in the contributors file. [Here's the commit](https://gitlab.com/bradenbest/mpassw/-/commit/2ed7acca55627ad5269b7ea8816eb6f334659a93)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T19:19:21.877", "Id": "534174", "Score": "0", "body": "@BradenBest Re `size_t` too big: Yes, for this `size_t` is indeed large (note may only be 65535), but if a smaller type was used, warnings may fire when call this code with a variable of type `size_t`." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T22:08:11.823", "Id": "270456", "ParentId": "270304", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T18:35:46.817", "Id": "270304", "Score": "0", "Tags": [ "c", "console", "portability" ], "Title": "Line-wise input, EOF handling, and behavioral differences between implementations of getchar" }
270304
<p>As a smaller part of a programming challenge, I am writing a function in Python that takes two parameters, a given number and a size constraint. The function yields a generator that produces the integer partitions of the given number up to the size constraint. I have a working solution that is derived from the rule_asc algorithm:</p> <pre><code>def rule_asc(n): a = [0 for i in range(n + 1)] k = 1 a[1] = n while k != 0: x = a[k - 1] + 1 y = a[k] - 1 k -= 1 while x &lt;= y: a[k] = x y -= x k += 1 a[k] = x + y yield a[:k + 1] </code></pre> <p>So to implement the size constraint there is a simple addition to the first nested while loop:</p> <pre><code>def generate_subproblems(total_nodes, colors): all_partitions = [0 for i in range(colors)] k = 1 all_partitions[0] = 0 all_partitions[1] = total_nodes while k != 0: x = all_partitions[k - 1] + 1 y = all_partitions[k] - 1 k -= 1 while x &lt;= y and k &lt; colors - 1: all_partitions[k] = x y -= x k += 1 all_partitions[k] = x + y current_partition = all_partitions[:k + 1] yield current_partition </code></pre> <p>This yields all the partitions of <code>total_nodes</code> with length <code>&lt;= colors</code>.</p> <p>For example, the code:</p> <pre><code>for _ in generate_subproblems(6, 3): print(_) </code></pre> <p>Prints:</p> <pre><code>[1, 1, 4] [1, 2, 3] [1, 5] [2, 2, 2] [2, 4] [3, 3] [6] </code></pre> <p>Which are all the integer partitions of the number 6 of size less than or equal to 3.</p> <p>The problem I am facing is that the algorithm is too slow for larger values, by larger I mean anything over 100. The place where I got the first algorithm (<a href="https://jeromekelleher.net/category/combinatorics.html" rel="nofollow noreferrer">https://jeromekelleher.net/category/combinatorics.html</a>) to begin with lists a different, quicker implementation:</p> <pre><code>def accel_asc(n): a = [0 for i in range(n + 1)] k = 1 y = n - 1 while k != 0: x = a[k - 1] + 1 k -= 1 while 2 * x &lt;= y: a[k] = x y -= x k += 1 l = k + 1 while x &lt;= y: a[k] = x a[l] = y yield a[:k + 2] x += 1 y -= 1 a[k] = x + y y = x + y - 1 yield a[:k + 1] </code></pre> <p>However I am unable to wrap my head around this implementation so as to introduce the size constraint. How can I modify the accel_asc function to just yield the partitions less than a specified size?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T07:02:47.500", "Id": "533757", "Score": "1", "body": "Welcome to Code Review@SE. *How-to* questions rarely are a good [fit for this site](https://codereview.stackexchange.com/help/on-topic). In your question, please clearly state which part you want reviewed. Put \"3rd-party code\" in block quotes - see post editor help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T07:04:21.853", "Id": "533759", "Score": "0", "body": "(Congrats on improving naming: You're moving in the right direction. [Docstrings](https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring) would be another improvement.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T07:18:04.073", "Id": "533761", "Score": "0", "body": "(What's the big difference in \"adaption difficulty\"?)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T19:52:52.950", "Id": "270305", "Score": "-1", "Tags": [ "python", "combinatorics", "generator" ], "Title": "Size Constrained Integer Partitions of a Given Number" }
270305
<p>I've been practising my coding skills because I have an interview coming up. The HackerRank challenge has 16 test cases; the code passes 9 of them and the other 7 time out.</p> <p>If you go to <a href="https://www.hackerrank.com/domains/data-structures" rel="nofollow noreferrer">HackerRank Problems Data Structures</a> you might be able to find Array Manipulation under <strong>Hard</strong> problems. I can't seem to provide a direct link.</p> <p>Using Microsoft specific parallel extensions in C++ I have gotten execution time for test case 4 down from hours down to 89 seconds when built for release. Test case 4 is one of the test cases that times out on Hacker Rank. I might be able to squeeze another couple of seconds out by using parallel processing in the merge function as well.</p> <p>Things I don't like about my solution:</p> <ul> <li>It is totally brute force</li> <li>I can't seem to run parallel on HackerRank; maybe I need to try OpenMP.</li> </ul> <p>I'm open to all answers and comments.</p> <h1>Program Challenge Statement</h1> <blockquote> <p>Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.</p> <p><strong>Example</strong></p> <p>Queries are interpreted as follows: a b k<br /> 1 5 3<br /> 4 8 7<br /> 6 9 1</p> <p>Add the values of <em>k</em> between the indices <em>a</em> and <em>b</em> inclusive:</p> <p>index-&gt; 1 2 3 4 5 6 7 8 9 10<br /> [0,0,0, 0, 0,0,0,0,0, 0]<br /> [3,3,3, 3, 3,0,0,0,0, 0]<br /> [3,3,3,10,10,7,7,7,0, 0]<br /> [3,3,3,10,10,8,8,8,1, 0]</p> <p>The largest value is 10 after all operations are performed.</p> <p><strong>Function Description</strong><br /> Complete the function <code>arrayManipulation</code>.</p> <p><code>arrayManipulation</code> has the following parameters:</p> <ul> <li><code>int n</code> - the number of elements in the array</li> <li><code>int queries[q][3]</code> - a two dimensional array of queries where each <code>queries[i]</code> contains three integers, <code>a</code>, <code>b</code>, and <code>k</code>.</li> </ul> <p><strong>Returns</strong></p> <ul> <li><code>int</code> - the maximum value in the resultant array</li> </ul> <p><strong>Constraints</strong><br /> - 3 &lt; n &lt; 10⁷<br /> - 1 &lt; m &lt; 2 * 10⁵<br /> - 1 &lt; a &lt; b &lt; n<br /> - 0 &lt; k &lt; 10⁹</p> <p><strong>Sample Input</strong><br /> 5 3<br /> 1 2 100<br /> 2 5 100<br /> 3 4 100</p> <p><strong>Sample Output</strong><br /> 200</p> </blockquote> <h1>Environment</h1> <p>Dell Precision 7740</p> <p>Processor Intel(R) Core(TM) i7-9850H CPU @ 2.60GHz 2.59 GHz<br /> Installed RAM 64.0 GB (63.8 GB usable)<br /> System type 64-bit operating system, x64-based processor<br /> Edition Windows 10 Pro Version 20H2<br /> OS build 19042.1348</p> <p>Visual Studio 2019.</p> <h1>Test Cases</h1> <h2>Test Case 1</h2> <p>5<br /> 3<br /> 1 2 100<br /> 2 5 100<br /> 3 4 100</p> <h2>Test Case 2</h2> <p>10<br /> 3<br /> 1 5 3<br /> 4 8 7<br /> 6 9 1</p> <h2>Test Case 3</h2> <p>10<br /> 4<br /> 2 6 8<br /> 3 5 7<br /> 1 8 1<br /> 5 9 15</p> <h2>Test Case 4</h2> <p>This is the first 5 lines only, the complete test case is 100,002 lines. You can download the complete test case from my <a href="https://github.com/pacmaninbw/HackerRankArrayManipulation" rel="nofollow noreferrer">GitHub repository</a>.</p> <p>10000000<br /> 100000<br /> 1400906 9889280 90378<br /> 6581237 9872072 87106<br /> 4386373 9779851 52422</p> <p>This test case really shows the scope of the problem, 100,000 outer loops, some inner loops with more the 7 million executions.</p> <h2>Test Output</h2> <p>PS C:\Users\PaulC\Documents\ProjectsNfwsi\CodeReview\HackerRankArrayManip\Release&gt; HackerRankArrayManip.exe<br /> How many test cases do you want to run?4<br /> Test Case 1<br /> Test Case 1 File read time 0.271 milliseconds<br /> Test Case 1 result is 200 Execution time 2.0378 milliseconds</p> <p>Test Case 2<br /> Test Case 2 File read time 0.1541 milliseconds<br /> Test Case 2 result is 10 Execution time 0.0132 milliseconds</p> <p>Test Case 3<br /> Test Case 3 File read time 0.1068 milliseconds<br /> Test Case 3 result is 31 Execution time 0.0985 milliseconds</p> <p>Test Case 4<br /> Test Case 4 File read time 77.3068 milliseconds<br /> Test Case 4 result is 2497169732 Execution time 89.1439 Seconds</p> <p>PS C:\Users\PaulC\Documents\ProjectsNfwsi\CodeReview\HackerRankArrayManip\Release&gt;</p> <h1>C++ Source File</h1> <pre><code>#include &lt;PPL.h&gt; #include&lt;algorithm&gt; #include &lt;chrono&gt; #include&lt;execution&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;mutex&gt; #include &lt;string&gt; #include &lt;vector&gt; constexpr int MAX_TEST_CASE = 4; /* * Infrastructure to replace HackerRank input functions */ std::vector&lt;int&gt; convertInputLineToIntVector(std::string query_string) { constexpr int query_size = 3; std::vector&lt;int&gt; query; std::string::iterator intStart = query_string.begin(); std::string::iterator intEnd; for (int i = 0; i &lt; query_size; i++) { intEnd = std::find(intStart, query_string.end(), ' '); int pos = intEnd - query_string.begin(); std::string tempInt(intStart, intEnd); query.push_back(stoi(tempInt)); if (intEnd &lt; query_string.end()) { intStart = query_string.begin() + pos + 1; } } return query; } std::vector&lt;std::vector&lt;int&gt;&gt; getIntVectors(std::ifstream* inFile) { std::vector&lt;std::vector&lt;int&gt;&gt; inputVector; std::string string_vector_count; getline(*inFile, string_vector_count); int strings_count = stoi(string_vector_count); for (int i = 0; i &lt; strings_count; i++) { std::string string_item; getline(*inFile, string_item); inputVector.push_back(convertInputLineToIntVector(string_item)); } return inputVector; } int getInputLines(std::string inputFileName, int &amp;vectorSize, std::vector&lt;std::vector&lt;int&gt;&gt;&amp; queries) { std::string string_count_size; std::ifstream inFile(inputFileName); if (!inFile.is_open()) { std::cerr &lt;&lt; &quot;Can't open &quot; &lt;&lt; inputFileName &lt;&lt; &quot; for input.\n&quot;; std::cout &lt;&lt; &quot;Can't open &quot; &lt;&lt; inputFileName &lt;&lt; &quot; for input.\n&quot;; return EXIT_FAILURE; } getline(inFile, string_count_size); vectorSize = stoi(string_count_size); queries = getIntVectors(&amp;inFile); return EXIT_SUCCESS; } void getTestCountAndFirstTestCase(int&amp; testCount, int&amp; firstTestCase) { do { std::cout &lt;&lt; &quot;How many test cases do you want to run?&quot;; std::cin &gt;&gt; testCount; if (testCount &lt; 0 || testCount &gt; MAX_TEST_CASE) { std::cerr &lt;&lt; &quot;The number of test cases must be greater &gt; 0 and less than &quot; &lt;&lt; &quot; &quot; &lt;&lt; MAX_TEST_CASE &lt;&lt; &quot;\n&quot;; } } while (testCount &lt; 0 || testCount &gt; MAX_TEST_CASE); if (testCount &lt; MAX_TEST_CASE) { bool hasErrors = true; do { std::cout &lt;&lt; &quot;What test case file do you want to start with?&quot;; std::cin &gt;&gt; firstTestCase; if (firstTestCase &lt; 0 || firstTestCase &gt; MAX_TEST_CASE) { std::cerr &lt;&lt; &quot;The first test cases must be greater &gt; 0 and less than &quot; &lt;&lt; &quot; &quot; &lt;&lt; MAX_TEST_CASE &lt;&lt; &quot;\n&quot;; hasErrors = true; } else { hasErrors = false; } if (!hasErrors &amp;&amp; testCount + firstTestCase &gt; MAX_TEST_CASE) { std::cerr &lt;&lt; &quot;The first test cases and the test count must be less than or equal to &quot; &lt;&lt; MAX_TEST_CASE &lt;&lt; &quot;\n&quot;; hasErrors = true; } } while (hasErrors); } else { firstTestCase = 1; } } /* * Begin HackerRank Solution */ constexpr int IDX_FIRST_LOCATION = 0; constexpr int IDX_LAST_LOCATION = 1; constexpr int IDX_VALUE_TO_ADD = 2; constexpr int MAX_THREADS = 16; unsigned long mergeAndFindMax(std::vector&lt;unsigned long&gt; maxValues, std::vector&lt;std::vector&lt;unsigned long&gt;&gt; calculatedValues, const size_t executionCount) { unsigned long maximumValue = 0; for (size_t i = 0; i &lt; MAX_THREADS; i++) { std::vector&lt;unsigned long&gt;::iterator cvi = calculatedValues[i].begin(); std::vector&lt;unsigned long&gt;::iterator cvEnd = calculatedValues[i].end(); std::vector&lt;unsigned long&gt;::iterator mvi = maxValues.begin(); for ( ; mvi &lt; maxValues.end() &amp;&amp; cvi &lt; cvEnd; mvi++, cvi++) { *mvi += *cvi; if (*mvi &gt; maximumValue) { maximumValue = *mvi; } } if (i &gt; executionCount) { break; } } return maximumValue; } unsigned long arrayManipulation(const int n, const std::vector&lt;std::vector&lt;int&gt;&gt; queries) { std::vector&lt;unsigned long&gt; maximumValues(n, 0); std::vector&lt;std::vector&lt;unsigned long&gt;&gt; calculatedValues(MAX_THREADS); std::mutex m; for_each(calculatedValues.begin(), calculatedValues.end(), [maximumValues](std::vector&lt;unsigned long&gt;&amp; cvi) {cvi = maximumValues; }); int executionCount = 0; Concurrency::parallel_for_each(queries.begin(), queries.end(), [&amp;m, &amp;calculatedValues, &amp;executionCount](std::vector&lt;int&gt; query) { std::lock_guard&lt;std::mutex&gt; guard(m); size_t startLoc = query[IDX_FIRST_LOCATION]; size_t endLoc = query[IDX_LAST_LOCATION]; const unsigned long valueToAdd = query[IDX_VALUE_TO_ADD]; for_each(calculatedValues[executionCount % MAX_THREADS].begin() + (startLoc - 1), calculatedValues[executionCount % MAX_THREADS].begin() + endLoc, [valueToAdd](unsigned long&amp; n) {n += valueToAdd; }); executionCount++; }); return mergeAndFindMax(maximumValues, calculatedValues, executionCount); } int executeAndTimeTestCases(int testCaseCount, int firstTestCase) { using std::chrono::high_resolution_clock; using std::chrono::duration_cast; using std::chrono::duration; using std::chrono::milliseconds; for (int i = 0; i &lt; testCaseCount; i++) { std::string testFileName = &quot;TestCase&quot; + std::to_string(firstTestCase) + &quot;.txt&quot;; int n = 0; std::vector&lt;std::vector&lt;int&gt;&gt; queries; std::cout &lt;&lt; &quot;Test Case &quot; &lt;&lt; firstTestCase &lt;&lt; &quot;\n&quot;; auto fileReadStartTime = high_resolution_clock::now(); int exitStatus = getInputLines(testFileName, n, queries); if (exitStatus != EXIT_SUCCESS) { return exitStatus; } auto fileReadEndTime = high_resolution_clock::now(); duration&lt;double, std::milli&gt; msReadTime = fileReadEndTime - fileReadStartTime; std::cout &lt;&lt; &quot;Test Case &quot; &lt;&lt; firstTestCase &lt;&lt; &quot; File read time &quot; &lt;&lt; msReadTime.count() &lt;&lt; &quot; milliseconds\n&quot;; auto executionStartTime = high_resolution_clock::now(); unsigned long result = arrayManipulation(n, queries); auto executionEndTime = high_resolution_clock::now(); duration&lt;double, std::milli&gt; msExecution = executionEndTime - executionStartTime; if (msExecution.count() &gt; 1000.0) { std::cout &lt;&lt; &quot;Test Case &quot; &lt;&lt; firstTestCase &lt;&lt; &quot; result is &quot; &lt;&lt; result &lt;&lt; &quot; Execution time &quot; &lt;&lt; msExecution.count() / 1000.0 &lt;&lt; &quot; Seconds\n\n&quot;; } else { std::cout &lt;&lt; &quot;Test Case &quot; &lt;&lt; firstTestCase &lt;&lt; &quot; result is &quot; &lt;&lt; result &lt;&lt; &quot; Execution time &quot; &lt;&lt; msExecution.count() &lt;&lt; &quot; milliseconds\n\n&quot;; } firstTestCase++; } return EXIT_SUCCESS; } int main() { int testCaseCount = 0; int firstTestCase = 0; getTestCountAndFirstTestCase(testCaseCount, firstTestCase); return executeAndTimeTestCases(testCaseCount, firstTestCase); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T20:57:04.653", "Id": "533736", "Score": "0", "body": "@Emily_L. I would definitely appreciate any comments or answers you care to contribute, I'm not sure I'm using the correct algorithm for performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T21:51:17.750", "Id": "533741", "Score": "0", "body": "See https://codereview.stackexchange.com/q/185320/35991 for a more efficient algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T22:15:40.150", "Id": "533745", "Score": "0", "body": "I just had a quick glance but it looks a bit weird to have a `parallel_for_each` and then to lock the entire scope with a mutex? From my CPU usage, it does not look like much is happening in parallel although memory bandwidth could be an issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T22:18:52.693", "Id": "533746", "Score": "1", "body": "@jdt Memory bandwidth is definitely an issue. Doing only sequential processing CPU was at 15%. Using the parallel algorithm CPU usage was at 70%." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T14:29:44.677", "Id": "533784", "Score": "0", "body": "@jdt I was working on using the STL standard `for_each()` and using [this documentation](https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t). I've removed the mutex in my testing code thanks. That and Deduplicator's suggestion to change vectors to pass by reference rather than pass by value shaved off 6 seconds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:34:24.947", "Id": "533795", "Score": "0", "body": "I had a bit of fun playing with this and would like to know if [this](https://paste-bin.xyz/16132) is slower or faster on your machine. It runs for about 90 seconds on my i7-9850H CPU @ 2.60GHz" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T15:44:06.597", "Id": "533872", "Score": "0", "body": "@jdt My browser / security software prevents me from going to the link. The moderators tell me the link is safe, since we're using the same i7 processor I suspect the time will be very similar." } ]
[ { "body": "<p>Yes, brute-force is a sub-optimal solution.</p>\n<p>A better way:</p>\n<ol>\n<li><p>Decompose each query <code>a b k</code> into two parts:</p>\n<ul>\n<li>At index a, add k</li>\n<li>At index b + 1, add -k</li>\n</ul>\n</li>\n<li><p>Store those sub-queries in one vector.</p>\n</li>\n<li><p>Sort the sub-queries.</p>\n</li>\n<li><p>Iterate the sub-queries to find the solution.</p>\n</li>\n</ol>\n<p>Opportunities for parallel execution? Sparse outside the sort.</p>\n<hr />\n<p>Inefficiencies common to challenge sites:</p>\n<ul>\n<li><p>Using <code>std::vector</code> when the number of elements is known and small. The overhead of dynamically allocating all those small bits adds up.</p>\n</li>\n<li><p>Copying huge amounts of data unnecessarily, most of the time by passing above big vectors of vectors by value.</p>\n</li>\n<li><p>Flushing the output-stream all the time. If you actually need the flush also contained in <code>std::endl</code>, be explicit and use <code>std::flush</code>.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T22:55:41.603", "Id": "533750", "Score": "1", "body": "Also inefficient: passing strings and vectors by value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:22:15.200", "Id": "533793", "Score": "0", "body": "In the past it has been said that my C++ looks too much like C, is that still the case? Your answer is definitely appreciated." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T21:26:18.703", "Id": "270308", "ParentId": "270307", "Score": "2" } }, { "body": "<p>Practicing for an interview you say?</p>\n<p><code>constexpr int MAX_TEST_CASE = 4;</code> You're off to a good start! Though you might use <code>auto</code> instead of <code>int</code>, or make it a <code>size_t</code> if it will be compared with vector lengths. <strong>Do you have warnings turned on?</strong> Signed/unsigned mismatch in comparison is a serious one to beware of.</p>\n<p><code>std::vector&lt;int&gt; convertInputLineToIntVector(std::string query_string)</code><br />\nAnd now your first serious <em>ding</em>. Why are you passing a <code>string</code> <em>by value</em>? That is rare enough to be a code review issue and distracts reviewers even when there is a legitimate reason to do so. Passing by value is a telltale mistake of people coming from other languages that have reference semantics for objects, and is something the interviewer will immediately spot with concern. You're not familiar enough with C++ source code to think this looks weird.</p>\n<p>You should use <code>std::string_view</code> to pass string things into functions. This gives you the best efficiency for passing either a <code>std::string</code> or a lexical string literal.</p>\n<hr />\n<pre><code>std::string::iterator intStart = query_string.begin();\nstd::string::iterator intEnd;\n</code></pre>\n<p>Declaring the full elaborated type of <code>intStart</code> is brutal, unnecessary, and gets in the way if the type of <code>query_string</code> changes. Try and write in a generic manner even if it's not a template -- that will help in maintenance, as changing the type of something is a very common change to make. You want any <em>dependent</em> things in the function to be worked out automatically. In short, <strong>use <code>auto</code></strong>.</p>\n<p>As for <code>intEnd</code>, why are you declaring it <em>here</em>, without any initializer? It should be declared where you actually use it, inside the loop.</p>\n<pre><code> for (int i = 0; i &lt; query_size; i++)\n {\n intEnd = std::find(intStart, query_string.end(), ' ');\n int pos = intEnd - query_string.begin();\n</code></pre>\n<p>vs.</p>\n<pre><code> for (int i = 0; i &lt; query_size; ++i)\n {\n const auto intEnd = std::find(intStart, query_string.end(), ' ');\n const auto pos = intEnd - query_string.begin();\n</code></pre>\n<p>Prefer prefix increment!<br />\nDefine the variable where you initialize it. Use <code>const</code> as well.<br />\nHere, <code>pos</code> is <em>not an int</em>! Let <code>auto</code> figure out the <code>difference_type</code> between the iterators for you.</p>\n<p>What you are doing here, it appears, is splitting the string. This should be a function call, not elaborated out into the middle of the main code. In real life you'll already have a reusable function for this. So call it something that's not so specific to this usage. Like, <code>parse_csv_ints</code> and take the number of fields to expect as a template argument.</p>\n<p>Since the number of fields is known at compile-time, you can avoid the dynamic memory of a <code>vector</code> and use an <code>array</code>. My function is:</p>\n<pre><code>template &lt;size_t N&gt;\nauto split (char separator, std::string_view input)\n{\n std::array&lt;std::string_view, N&gt; results;\n ⋮ \n return results;\n}\n\n</code></pre>\n<p>This doesn't do the conversion to <code>int</code> of each field; it just separates them out (including whitespace). The caller allocates the fixed-size array on its stack, and the result is populated as pointers into the original <code>input</code> so does not copy any string data at all.</p>\n<p>This is a more reusable core that can have any type of data reading adding around it as another layer.</p>\n<hr />\n<pre><code>std::vector&lt;std::vector&lt;int&gt;&gt; getIntVectors(std::ifstream* inFile)\n{\n std::vector&lt;std::vector&lt;int&gt;&gt; inputVector;\n std::string string_vector_count;\n\n getline(*inFile, string_vector_count);\n</code></pre>\n<p>Why are you passing <code>inFile</code> as a pointer? You're using it without checking for <code>nullptr</code> and you don't assign back over the object to modify the caller's copy, so this should be a reference (not a pointer).</p>\n<p>The return type has a lot of overhead. Each test case has exactly 3 values per element, so make a struct for that, or an <code>array</code>, or <code>tuple</code>; not a variable-length dynamically-allocated vector! Not only will this use tons more memory, but it requires dynamic allocation (and later freeing).</p>\n<hr />\n<p><code>int getInputLines(std::string inputFileName, int &amp;vectorSize, std::vector&lt;std::vector&lt;int&gt;&gt;&amp; queries)</code></p>\n<p>This is returning a SUCCESS/FAILURE flag, and passing the results back through &quot;out&quot; parameters. Furthermore you wrote <code>int &amp;vectorSize</code> instead of <code>int&amp; vectorSize</code>, nevermind that it's a <code>size_t</code> not an <code>int</code> or that the vector itself already knows its own size. This is a weird miss-mash of C code with some C++ features added.</p>\n<p>Reviewing the data to be read, I see that it contains not just a list of commands but the cell count as well. The number of commands becomes the vector of commands' size. But where to store the cell count? You should abstract out the Test Case into its own class, even though it's just a vector plus another number. This will make the code clearer since you know when you have a single Test Case or an array of Test Cases, or the vector of commands without the cell count.</p>\n<hr />\n<pre><code> do {\n std::cout &lt;&lt; &quot;How many test cases do you want to run?&quot;;\n std::cin &gt;&gt; testCount;\n if (testCount &lt; 0 || testCount &gt; MAX_TEST_CASE)\n {\n std::cerr &lt;&lt; &quot;The number of test cases must be greater &gt; 0 and less than &quot; &lt;&lt; &quot; &quot; &lt;&lt; MAX_TEST_CASE &lt;&lt; &quot;\\n&quot;;\n }\n } while (testCount &lt; 0 || testCount &gt; MAX_TEST_CASE);\n\n</code></pre>\n<p>This is something that bothers me about code like this. You write your own ad-hoc &quot;trying to be robust&quot; user input routines. That's not part of the actual problem, and such routines are never perfect anyway.</p>\n<p>In a <em>real</em> program, it won't prompt you. It looks at command-line arguments, and gives an error message if they are not suitable, or a help message if there are none. No loop and retry needed.</p>\n<p>And don't use &quot;out&quot; parameters for returning things!</p>\n<hr />\n<p><code>unsigned long mergeAndFindMax(std::vector&lt;unsigned long&gt; maxValues, std::vector&lt;std::vector&lt;unsigned long&gt;&gt; calculatedValues, const size_t executionCount)</code><br />\nDid you notice that you're passing not just a <code>vector</code> but also a <code>vector</code> of <code>vector</code>s <strong>by value</strong> to this function, causing the whole dynamic memory tree to be duplicated?!</p>\n<p>Scanning ahead, I see other functions doing that too.</p>\n<p>Name the types: your <code>vector&lt;unsigned long&gt;</code> should be the cell array type. Don't use <code>unsigned long</code> as that's implementation defined as to what range it holds. Use the explicitly sized names like <code>uint64_t</code>.</p>\n<hr />\n<p><code>std::vector&lt;unsigned long&gt; maximumValues(n, 0);</code><br />\nYou know that <code>maximumValues[n]</code> does not exist in this vector? I think they intended for subscripts to range from 1 to n inclusive (&quot;1 based&quot;), but you have 0 through <code>n-1</code> inclusive.</p>\n<hr />\n<p>Where can you put <code>const</code> that you haven't?</p>\n<p>Good luck, and keep practicing! And always have fun.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T16:34:10.423", "Id": "533804", "Score": "0", "body": "Forced to use a vector by Hacker Rank." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T16:40:59.913", "Id": "533806", "Score": "1", "body": "Looking forward to the rest of your review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T17:03:18.427", "Id": "533809", "Score": "0", "body": "re \"forced to use vector\" so it's not just feeding you a text file and reading the output? Is it asking for a function with some specific signature? If so, what is the API it wants you to implement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T17:06:50.337", "Id": "533811", "Score": "0", "body": "Not on hackerrank, no the only function that needs to be written on hackerrank is the arrayManipulation function and they have provided the prototype." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T15:39:32.247", "Id": "533871", "Score": "1", "body": "Good review, thank you. post fix increment is a remnant of my C programming days on the Motorola 68000 family of computers and Spark chips and compilers that didn't optimize very well, there was as post fix increment opcode that was faster than the prefix increment that took multiple opcodes, that is no longer valid. I have changed the code in my test environment so that it uses the reference of the vectors rather than the value, it did improve the performance. I need to keep practicing with std::string_view I don't use it enough." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T16:31:00.193", "Id": "270332", "ParentId": "270307", "Score": "2" } } ]
{ "AcceptedAnswerId": "270332", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T20:51:16.313", "Id": "270307", "Score": "1", "Tags": [ "c++", "performance", "programming-challenge", "time-limit-exceeded" ], "Title": "HackerRank \"Array Manipulation\" challenge (using Microsoft concurrent extensions)" }
270307
<h2>Code:</h2> <pre><code># read file of first agrument import sys, os try: data = open(sys.argv[1]).read() except: data = open(&quot;File.txt&quot;).read() sys.argv.append(&quot;File.txt&quot;) dct = {&quot;@&quot;: data, &quot;E&quot;: &quot;0&quot;} iteration = 0 RESET = False define = False printf = False replace = False inp = False join = False Reverse = False getascii = False getfirstchar = False removeallexceptcertainchar = False readfile = False comment = False multilinecomment = False takeagrument = False definebutvar = False getfilesandfolders = False haltifeof = False ################################################################################ variable = &quot;&quot; variable2 = &quot;&quot; variable3 = &quot;&quot; variable4 = &quot;&quot; variable5 = &quot;&quot; variable6 = &quot;&quot; string = &quot;&quot; escape = False isready = False isset = False isgo = False def erroring(errtype, errreason, tb): print(errreason, end=&quot;&quot;, file=sys.stderr) sys.excepthook = erroring def dctremoveallexceptcertain(string, variable): # removes all except certain characters # string = string to be modified # variable = characters to be kept # returns modified string global newstring newstring = &quot;&quot; for i in string: if i in variable: newstring += i return newstring while True: # Note you should use try and except to catch errors, not if x in y: for i in data: if printf: # print the variable of dct variable if i in dct: print(dct[i], end = &quot;&quot;) printf = False else: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;VARIABLE NOT FOUND IN ITERATION&quot;, iteration) break elif define: if isready: if escape: # check if i is quote or backslash add to string else add backslash and i if i == &quot;\&quot;&quot; or i == &quot;\\&quot;: string += i escape = False else: string += &quot;\\&quot; + i escape = False elif i == &quot;\&quot;&quot;: dct[variable] = string string = &quot;&quot; isready = False define = False # check if the variable is &quot;@&quot; change the data if variable == &quot;@&quot;: RESET = True break elif i == &quot;\\&quot;: escape = True continue else: string += i else: variable = i isready = True elif replace: # get 3 variables if isgo: try: dct[variable] = dct[variable2].replace(variable3, i) except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;VARIABLE NOT FOUND IN ITERATION&quot;, iteration) break replace = isset = isready = isgo = False # check if the variable is &quot;@&quot; change the data if variable == &quot;@&quot;: RESET = True break elif isset: variable3 = i isgo = True elif isready: variable2 = i isset = True else: variable = i isready = True elif inp: try: dct[i] = input() dct[&quot;E&quot;] = &quot;0&quot; except EOFError: dct[&quot;E&quot;] = &quot;1&quot; inp = False if i == &quot;@&quot;: RESET = True break elif join: if isset: try: dct[variable] = dct[variable2] + dct[i] except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;VARIABLE NOT FOUND IN ITERATION&quot;, iteration) break join = isset = isready = isgo = False # check if the variable is &quot;@&quot; change the data if variable == &quot;@&quot;: RESET = True break elif isready: variable2 = i isset = True else: variable = i isready = True elif Reverse: # this is equivalent to pseudocode var = var2.reverse() if isready: try: dct[variable] = dct[i][::-1] except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;VARIABLE NOT FOUND IN ITERATION&quot;, iteration) break isready = False Revert = False if variable == &quot;@&quot;: RESET = True break else: variable = i isready = True elif getfirstchar: # gets the first character of the variable if isready: try: dct[variable] = dct[i][0] except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;VARIABLE NOT FOUND IN ITERATION&quot;, iteration) isready = False getfirstchar = False if variable == &quot;@&quot;: RESET = True break else: variable = i isready = True elif getascii: # gets ascii value of the variable if isready: try: dct[i] try: dct[variable] = ord(dct[i]) except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;INVALID NUMBER IN ITERATION&quot;, iteration) except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;VARIABLE NOT FOUND IN ITERATION&quot;, iteration) getascii = False isready = False if variable == &quot;@&quot;: RESET = True break else: variable = i isready = True elif removeallexceptcertainchar: # removes all except certain character if isready: try: dct[variable] = dctremoveallexceptcertain(dct[variable], dct[i]) except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;VARIABLE NOT FOUND IN ITERATION&quot;, iteration) isready = False removeallexceptcertainchar = False if variable == &quot;@&quot;: RESET = True break else: variable = i isready = True elif readfile: if isready: try: dct[i] except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;VARIABLE NOT FOUND IN ITERATION&quot;, iteration) try: dct[variable] = open(dct[i], &quot;r&quot;).read() dct[&quot;E&quot;] = &quot;0&quot; except: dct[&quot;E&quot;] = &quot;1&quot; isready = False readfile = False if variable == &quot;@&quot;: RESET = True break else: variable = i isready = True elif comment: # ignore until a newline is found if i == &quot;\n&quot;: comment = False elif multilinecomment: if i == &quot;}&quot;: multilinecomment = False elif takeagrument: # checks if the variable is defined and the variable is a number if isready: try: dct[i] try: int(dct[i]) try: dct[variable] = sys.argv[int(dct[i])] dct[&quot;E&quot;] = &quot;0&quot; except: dct[&quot;E&quot;] = &quot;1&quot; except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;INVALID NUMBER&quot;, iteration) except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;VARIABLE NOT FOUND IN ITERATION&quot;, iteration) isready = False takeagrument = False if variable == &quot;@&quot;: RESET = True else: variable = i isready = True elif definebutvar: # like &gt; but it defines the variable if isready: try: dct[variable] = dct[i] except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;VARIABLE NOT FOUND IN ITERATION&quot;, iteration) isready = False definebutvar = False if variable == &quot;@&quot;: RESET = True break else: variable = i isready = True elif getfilesandfolders: # gets all files and folders in a variable if folder not found the variable &quot;E&quot; is equal to &quot;1&quot; else &quot;0&quot; if isready: # check if variable is defined try: dct[i] except: raise Exception(&quot;ERROR IN FILE&quot;, sys.argv[1], &quot;VARIABLE NOT FOUND IN ITERATION&quot;, iteration) try: files = os.listdir(dct[i]) dct[variable] = files dct[&quot;E&quot;] = &quot;0&quot; except: dct[&quot;E&quot;] = &quot;1&quot; isready = False getfilesandfolders = False if variable == &quot;@&quot;: RESET = True break else: variable = i isready = True elif haltifeof: if dct[&quot;E&quot;] == &quot;1&quot;:break haltifeof = False elif i == &quot;@&quot;: ############################################################################################################# RESET = True break elif i == &quot;H&quot;: break elif i == &quot;&gt;&quot;: define = True elif i == &quot;*&quot;: printf = True elif i == &quot;$&quot;: replace = True elif i == &quot;&amp;&quot;: inp = True elif i == &quot;+&quot;: join = True elif i == &quot;/&quot;: Reverse = True elif i == &quot;?&quot;: getfirstchar = True elif i == &quot;.&quot;: getascii = True elif i == &quot;!&quot;: removeallexceptcertainchar = True elif i == &quot;;&quot;: readfile = True elif i == &quot;:&quot;: comment = True elif i == &quot;{&quot;: multilinecomment = True elif i == &quot;|&quot;: takeagrument = True elif i == &quot;=&quot;: definebutvar = True elif i == &quot;%&quot;: getfilesandfolders = True elif i == &quot;_&quot;: haltifeof = True # its not necessary to raise error invalid command # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # iteration += 1 # check if string still contains something put it in dct if string != &quot;&quot;: dct[variable] = string string = &quot;&quot; define = False isready = False isset = False isgo = False printf = False replace = False inp = False join, Reverse = False, False getfirstchar = False getascii = False removeallexceptcertainchar = False readfile = False comment = False multilinecomment = False takeagrument = False definebutvar = False getfilesandfolders = False # check if dct is &quot;@&quot; change the data if variable == &quot;@&quot;: RESET = True if RESET: RESET = False data = dct[&quot;@&quot;] iteration = 0 continue break try: print(dct[&quot;#&quot;], end = &quot;&quot;) except: pass </code></pre> <p>This is a programming language interpreter. I will show wiki.</p> <h2>Commands:</h2> <p>(a, b, c, d means variables next command)</p> <p>&quot;@&quot; goto first char</p> <p>&quot;H&quot; halt (must be uppercase, not lowercase)</p> <p>&quot;&gt;&quot; define var Syntax: <code>&gt;~Hello&quot;</code> Escape is backslash (the quote is optional)</p> <p>&quot;*&quot; print the next char variable</p> <p>&quot;$&quot; a = b.replace(c, d)</p> <p>&quot;&amp;&quot; Input the next char variable (&quot;E&quot; var is 1 if EOF)</p> <p>&quot;+&quot; a = b.join(c)</p> <p>&quot;/&quot; a = b.reverse()</p> <p>&quot;?&quot; a = b.getfirstchar()</p> <p>&quot;.&quot; a = chr(b)</p> <p>&quot;!&quot; a = a but non-b chars removed</p> <p>&quot;;&quot; a = readfile(b) (&quot;E&quot; = 1 if the file doesn't exist)</p> <p>&quot;:&quot; comment</p> <p>&quot;{&quot; start multiline comment</p> <p>&quot;}&quot; end multiline comment</p> <p>&quot;|&quot; a = takearg(int(b))</p> <p>&quot;=&quot; a = b</p> <p>&quot;%&quot; a = str(getfilesandfolders(b))</p> <p>&quot;_&quot; halt if EOF</p> <h2>Variables:</h2> <p>&quot;@&quot; if the variable is edited, the program changes</p> <p>&quot;#&quot; print when program ends.</p> <p>&quot;E&quot; EOF Var</p> <br> <h1>Examples:</h1> <pre><code>&gt;#Hello, World! </code></pre> <p>Hello, World!</p> <pre><code>@ </code></pre> <p>Infinite loop</p> <pre><code>&amp;#*# </code></pre> <p>read a line and output without newline twice</p> <pre><code>&gt;HHello, World!&quot; </code></pre> <p>NOP</p> <pre><code>&gt;H\&quot;&quot;*H </code></pre> <p>print double quotes</p> <br> <p>Can you find bugs?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T18:30:37.853", "Id": "533817", "Score": "1", "body": "Do you have a name for your programming language, and a sample program in that language?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T18:41:16.603", "Id": "533819", "Score": "0", "body": "My programming language name is NLRNIS" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T18:43:22.897", "Id": "533821", "Score": "0", "body": "And I will show samples later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T19:20:56.160", "Id": "533823", "Score": "1", "body": "Are you asking us to comment on your samples as well? It's a bit hard to comment on the code without some samples to see what you're expecting to happen. (And use some functions, please.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T20:18:52.823", "Id": "533833", "Score": "0", "body": "@Teepeemm samples added" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T00:19:41.843", "Id": "534041", "Score": "0", "body": "I didn't downvote, but: you have one function and then a hideously long `while True` loop, 18 magic variables, and minimal indenting. It's very hard to understand. Your commands are also hard to understand: e.g., what do you mean by '\"$\" a = b.replace(c, d)'. Is there a reason that you decided to create this language? Is there a reason you named it NLRNIS?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T00:23:21.953", "Id": "534042", "Score": "1", "body": "I named NLRNIS because No Loop, Recursion neither if statements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T00:25:15.630", "Id": "534043", "Score": "0", "body": "And \"$\" means if $abcd then a equals to b.replace(c, d)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T22:52:32.877", "Id": "270310", "Score": "-3", "Tags": [ "python-3.x", "interpreter" ], "Title": "Making programming language" }
270310
<p>I've been trying to implement a simple Boost PMR allocator that has a fixed amount of memory. My first implementation (which can be found <a href="https://github.com/irods/irods/blob/master/lib/core/include/fixed_buffer_resource.hpp" rel="nofollow noreferrer">here</a>) had undefined behavior and did not handle memory alignment.</p> <p>I've been doing a lot of reading around these topics and while I'm still unclear about some of it, I believe the code posted below is closer to a real solution.</p> <p>It would be very helpful if someone could review the code below for the following:</p> <ul> <li>undefined behavior</li> <li>proper handling of memory alignment</li> <li>obvious performance enhancements</li> </ul> <p>Also, is it possible to calculate how many bytes are needed to align a buffer? See <strong>TODO</strong> comment in <code>allocate_block()</code>. What I have there now is the following, but it feels wrong.</p> <pre class="lang-cpp prettyprint-override"><code>const auto max_space_needed = sizeof(header) + sizeof(void*) + _bytes + _alignment; </code></pre> <p>For the most part, the implementation appears to work, but I want to make sure I've covered as many things as possible since this will be included in the next release of the software I work on.</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef IRODS_FIXED_BUFFER_RESOURCE_HPP #define IRODS_FIXED_BUFFER_RESOURCE_HPP /// \file #include &lt;boost/container/pmr/memory_resource.hpp&gt; #include &lt;fmt/format.h&gt; #include &lt;cassert&gt; #include &lt;cstddef&gt; #include &lt;memory&gt; #include &lt;ostream&gt; #include &lt;stdexcept&gt; #include &lt;tuple&gt; #include &lt;type_traits&gt; /// A namespace containing components meant to be used with Boost.Container's PMR library. namespace irods::experimental::pmr { /// A \p fixed_buffer_resource is a special purpose memory resource class template that /// allocates memory from the buffer given on construction. It allows applications to /// enforce a cap on the amount of memory available to components. /// /// This class implements a first-fit scheme and is NOT thread-safe. /// /// \tparam ByteRep The memory representation for the underlying buffer. Must be \p char /// or \p std::byte. /// /// \since 4.2.11 template &lt;typename ByteRep&gt; class fixed_buffer_resource : public boost::container::pmr::memory_resource { public: static_assert(std::is_same_v&lt;ByteRep, char&gt; || std::is_same_v&lt;ByteRep, unsigned char&gt; || std::is_same_v&lt;ByteRep, std::uint8_t&gt; || std::is_same_v&lt;ByteRep, std::byte&gt;); /// Constructs a \p fixed_buffer_resource using the given buffer as the allocation /// source. /// /// \param[in] _buffer The buffer that will be used for allocations. /// \param[in] _buffer_size The size of the buffer in bytes. /// /// \throws std::invalid_argument If any of the incoming constructor arguments do not /// satisfy construction requirements. /// /// \since 4.2.11 fixed_buffer_resource(ByteRep* _buffer, std::int64_t _buffer_size) : boost::container::pmr::memory_resource{} , buffer_{_buffer} , buffer_size_(_buffer_size) , allocated_{} , headers_{} { if (!_buffer || _buffer_size &lt;= 0) { const auto* msg_fmt = &quot;fixed_buffer_resource: invalid constructor arguments &quot; &quot;[buffer={}, size={}].&quot;; const auto msg = fmt::format(msg_fmt, fmt::ptr(_buffer), _buffer_size); throw std::invalid_argument{msg_fmt}; } std::size_t space_left = buffer_size_; // Make sure the buffer is aligned for the header type. if (!std::align(alignof(header), sizeof(header), buffer_, space_left)) { throw std::runtime_error{&quot;fixed_buffer_resource: internal memory alignment error. &quot;}; } headers_ = new (buffer_) header; headers_-&gt;size = space_left - sizeof(header); headers_-&gt;prev = nullptr; headers_-&gt;next = nullptr; headers_-&gt;used = false; } // fixed_buffer_resource fixed_buffer_resource(const fixed_buffer_resource&amp;) = delete; auto operator=(const fixed_buffer_resource&amp;) -&gt; fixed_buffer_resource&amp; = delete; ~fixed_buffer_resource() = default; /// Returns the number of bytes used by the client. /// /// The value returned does not include memory used for tracking allocations. /// /// \return An unsigned integral type. /// /// \since 4.2.11 auto allocated() const noexcept -&gt; std::size_t { return allocated_; } // allocated /// Returns the number of bytes used for tracking allocations. /// /// \return An unsigned integral type. /// /// \since 4.2.11 auto allocation_overhead() const noexcept -&gt; std::size_t { return 0; } // allocation_overhead /// Writes the state of the allocation table to the output stream. /// /// \since 4.2.11 auto print(std::ostream&amp; _os) const -&gt; void { std::size_t i = 0; for (auto* h = headers_; h; h = h-&gt;next) { _os &lt;&lt; fmt::format(&quot;{:&gt;3}. Header Info [{}]: {{previous={:14}, next={:14}, used={:&gt;5}, data={:14}, data_size={}}}\n&quot;, i, fmt::ptr(h), fmt::ptr(h-&gt;prev), fmt::ptr(h-&gt;next), h-&gt;used, fmt::ptr(address_of_data_segment(h)), h-&gt;size); ++i; } } // print protected: auto do_allocate(std::size_t _bytes, std::size_t _alignment) -&gt; void* override { for (auto* h = headers_; h; h = h-&gt;next) { if (auto* p = allocate_block(_bytes, _alignment, h); p) { return p; } } throw std::bad_alloc{}; } // do_allocate auto do_deallocate(void* _p, std::size_t _bytes, std::size_t _alignment) -&gt; void override { void* data = *(static_cast&lt;void**&gt;(_p) - 1); auto* h = reinterpret_cast&lt;header*&gt;(static_cast&lt;ByteRep*&gt;(data) - sizeof(header)); assert(h != nullptr); assert(h-&gt;size == _bytes); h-&gt;used = false; coalesce_with_next_unused_block(h); coalesce_with_next_unused_block(h-&gt;prev); allocated_ -= _bytes; } // do_deallocate auto do_is_equal(const boost::container::pmr::memory_resource&amp; _other) const noexcept -&gt; bool override { return this == &amp;_other; } // do_is_equal private: // Header associated with an allocation within the underlying memory buffer. // All data segments will be preceded by a header. // // Memory Layout: // // +------------------------------------------------------------------+ // | padding | header | data segment | // +------------------+-----------------------------------------------+ // | padding | unaligned pointer | aligned pointer | // +-----------------------------------------------+ // struct header { std::size_t size; // Size of the memory block (excluding all management info). header* prev; // Pointer to the previous header block. header* next; // Pointer to the next header block. bool used; // Indicates whether the memory is in use. }; // struct header auto address_of_data_segment(header* _h) const noexcept -&gt; ByteRep* { return reinterpret_cast&lt;ByteRep*&gt;(_h) + sizeof(header); } // address_of_data_segment auto aligned_alloc(std::size_t _bytes, std::size_t _alignment, header* _h) -&gt; std::tuple&lt;void*, std::size_t&gt; { // The unused memory is located right after the header. void* data = address_of_data_segment(_h); auto space_left = _h-&gt;size - sizeof(void*); // Reserve space for the potentially unaligned pointer. void* aligned_data = static_cast&lt;ByteRep*&gt;(data) + sizeof(void*); if (!std::align(_alignment, _bytes, aligned_data, space_left)) { return {nullptr, 0}; } // Store the address of the original allocation directly before the // aligned memory. new (static_cast&lt;ByteRep*&gt;(aligned_data) - sizeof(void*)) void*{data}; return {aligned_data, space_left}; } // aligned_alloc auto allocate_block(std::size_t _bytes, std::size_t _alignment, header* _h) -&gt; void* { if (_h-&gt;used) { return nullptr; } // Return the block if it matches the requested number of bytes. if (_bytes == _h-&gt;size) { if (auto* aligned_data = std::get&lt;void*&gt;(aligned_alloc(_bytes, _alignment, _h)); aligned_data) { _h-&gt;used = true; allocated_ += _bytes; return aligned_data; } } // TODO Is it possible to compute the amount of memory needed to satisfy // the allocation and alignment requirements? I'm not sure if this line // is correct. const auto max_space_needed = sizeof(header) + sizeof(void*) + _bytes + _alignment; // Split the data segment managed by this header if it is large enough // to satisfy the allocation request and management information. if (max_space_needed &lt; _h-&gt;size) { auto [aligned_data, space_left] = aligned_alloc(_bytes, _alignment, _h); if (!aligned_data) { return nullptr; } void* aligned_header_storage = static_cast&lt;ByteRep*&gt;(aligned_data) + _bytes; if (!std::align(alignof(header), sizeof(header), aligned_header_storage, space_left)) { return nullptr; } // Construct a new header after the memory managed by &quot;_h&quot;. // The new header manages unused memory. auto* new_header = new (aligned_header_storage) header; new_header-&gt;size = space_left - _bytes - sizeof(header); new_header-&gt;prev = _h; new_header-&gt;next = _h-&gt;next; new_header-&gt;used = false; // Update the allocation table links for the header just after the // newly added header. if (auto* next_header = _h-&gt;next; next_header) { next_header-&gt;prev = new_header; } // Adjust the current header's size and mark it as used. _h-&gt;size = _bytes; _h-&gt;next = new_header; _h-&gt;used = true; allocated_ += _bytes; return aligned_data; } return nullptr; } // allocate_block auto coalesce_with_next_unused_block(header* _h) -&gt; void { if (!_h || _h-&gt;used) { return; } auto* header_to_remove = _h-&gt;next; // Coalesce the memory blocks if they are not in use by the client. // This means that &quot;_h&quot; will absorb the header at &quot;_h-&gt;next&quot;. if (header_to_remove &amp;&amp; !header_to_remove-&gt;used) { // TODO This does not consider the header's size. // How should I handle this? _h-&gt;size += header_to_remove-&gt;size; _h-&gt;next = header_to_remove-&gt;next; // Make sure the links between the headers are updated appropriately. // (i.e. &quot;_h&quot; and &quot;header_to_remove-&gt;next&quot; need their links updated). if (auto* new_next_header = header_to_remove-&gt;next; new_next_header) { new_next_header-&gt;prev = _h; } } } // coalesce_with_next_unused_block void* buffer_; std::size_t buffer_size_; std::size_t allocated_; header* headers_; }; // fixed_buffer_resource } // namespace irods::experimental::pmr #endif // IRODS_FIXED_BUFFER_RESOURCE_HPP </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T14:52:45.297", "Id": "533787", "Score": "0", "body": "You're using Boost.PMR instead of std::pmr, with C++17?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:03:07.620", "Id": "533789", "Score": "0", "body": "Yes. The project I work on is tied to Clang 6.0.1 and Boost 1.67." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:06:21.497", "Id": "533790", "Score": "0", "body": "But pmr is available for the std collections in C++17; just because Boost is also in use doesn't mean you have to use Boost.Container." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:08:48.533", "Id": "533791", "Score": "0", "body": "Right. However, I don't think the version of Clang we use has support for std::pmr. I believe I checked for that before, but I'll check again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:38:09.243", "Id": "533796", "Score": "0", "body": "Yeah, Clang 6 does not appear to have support for pmr. It has some headers, but the implementation is not complete. Also, I forgot to mention we are using libc++." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:39:46.020", "Id": "533797", "Score": "0", "body": "Right; it's not in libc++ (https://en.cppreference.com/w/cpp/compiler_support/17). I assume you're using that option since this is a library feature not a language feature. You can also use gcc's libstdc++" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:58:34.493", "Id": "533801", "Score": "0", "body": "BTW, when I've implemented a simple memory pool with variable sized allocations, I worked off the algorithm from Knuth's TAOP." } ]
[ { "body": "<blockquote>\n<pre><code> static_assert(std::is_same_v&lt;ByteRep, char&gt; ||\n std::is_same_v&lt;ByteRep, unsigned char&gt; ||\n std::is_same_v&lt;ByteRep, std::uint8_t&gt; ||\n std::is_same_v&lt;ByteRep, std::byte&gt;);\n</code></pre>\n</blockquote>\n<p>Why those four particular types, but not <code>signed char</code>? Perhaps what we really care about is</p>\n<pre><code> static_assert(sizeof (ByteRep) == 1);\n</code></pre>\n<hr />\n<blockquote>\n<pre><code> const auto* msg_fmt = &quot;fixed_buffer_resource: invalid constructor arguments &quot;\n &quot;[buffer={}, size={}].&quot;;\n const auto msg = fmt::format(msg_fmt, fmt::ptr(_buffer), _buffer_size);\n throw std::invalid_argument{msg_fmt};\n</code></pre>\n</blockquote>\n<p>Why do we discard <code>msg</code>, and populate the exception using the <em>format string</em>?</p>\n<hr />\n<p>The handling of alignment is quite tricky. I don't see any obvious issues. The non-obvious issues need to be exercised using a good test suite; it's a shame you didn't include your tests in the review request.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T12:53:24.140", "Id": "533783", "Score": "0", "body": "Thanks for your reply. The msg/msg_fmt is a typo due to experimenting with online editors (godbolt, etc). I have a very basic unit test which can be found [here](https://github.com/irods/irods/blob/master/unit_tests/src/test_fixed_buffer_resource.cpp). What things should I test for other than allocation/deallocation? Is `signed char` different from `char`? Wouldn't it be possible for someone to pass an empty class as `ByteRep` if I only checked for a size of 1?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:10:37.540", "Id": "533792", "Score": "1", "body": "re `signed char` etc.: For casting to/from raw memory, the language only treats (plain) `char` , `unsigned char`, and `std::byte` as special. However, I think he avoids UB by using placement `new` for the header instead of just pointing into the buffer and calling it a header, even though it has no constructor or destructor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:55:03.120", "Id": "533799", "Score": "0", "body": "@JDługosz, I guess that means that `std::uint8_t` should be removed from the list of acceptable types, then, rather than adding `signed char`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T07:10:10.960", "Id": "270316", "ParentId": "270311", "Score": "1" } }, { "body": "<p>Use inline initializers on your members rather than constants in the only constructor. You can write the members as:</p>\n<pre><code> void* buffer_ = nullptr;\n std::size_t buffer_size_;\n std::size_t allocated_ = 0;\n header* headers_ = nullptr;\n</code></pre>\n<p>And then your constructor needs only:</p>\n<pre><code> : buffer_size_(_buffer_size)\n</code></pre>\n<p>I notice that the parameter is <code>uint64_t</code> while the member uses <code>size_t</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T02:20:21.383", "Id": "534128", "Score": "0", "body": "The parameter type and member type are different on purpose. This is for situations where a negative value is passed to the constructor. We want to be able to detect those cases." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:04:33.610", "Id": "270330", "ParentId": "270311", "Score": "2" } }, { "body": "<p>There is a bug in <code>allocate_block()</code>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> auto [aligned_data, space_left] = aligned_alloc(_bytes, _alignment, _h);\n\n if (!aligned_data) {\n return nullptr;\n }\n\n void* aligned_header_storage = static_cast&lt;ByteRep*&gt;(aligned_data) + _bytes;\n\n if (!std::align(alignof(header), sizeof(header), aligned_header_storage, space_left)) {\n return nullptr;\n }\n\n // Construct a new header after the memory managed by &quot;_h&quot;.\n // The new header manages unused memory.\n auto* new_header = new (aligned_header_storage) header;\n</code></pre>\n<ul>\n<li><code>space_left</code> is not updated to reflect the allocation of <code>_bytes</code> bytes. This means the call to <code>std::align()</code> for <code>aligned_header_storage</code> is incorrect.</li>\n<li><code>space_left</code> needs to be checked to make sure there is enough space left in the buffer to hold an additional <code>header</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T02:35:26.950", "Id": "270458", "ParentId": "270311", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T23:00:05.220", "Id": "270311", "Score": "2", "Tags": [ "c++", "memory-management", "c++17", "memory-optimization", "boost" ], "Title": "Fixed-size memory allocator" }
270311
<p>I created a method to return a copy of <code>List&lt;T&gt;</code>, basically I convert the <code>List&lt;T&gt;</code> into an array <code>T[]</code>, then perform the copy with the <code>arrayCopy(T[])</code> method and back convert again in <code>List&lt;T&gt;</code>.</p> <p>I want to know if the code will be run successfully in different scenarios and it is good in performance or is there a way to do it better.</p> <pre><code>public static &lt;T&gt; List&lt;T&gt; getCopyOfList(List&lt;T&gt; list) { return Arrays.asList((T[]) arrayCopy(list.toArray())); } public static &lt;T&gt; T[] arrayCopy(final T[] original) { return Arrays.copyOf(original, original.length); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T11:22:51.120", "Id": "533777", "Score": "2", "body": "You're not creating a copy of a List. You're creating a new list with the same elements as the original list. The difference is important as \"a copy\" would imply that the result is a copy of the original, sharing the same object type and the elements. As such this helper method is a bit useless as the caller can not choose the correct list implementation for their use case. So I ask the same question as Eric Stein: why not just use the copy constructor? Can you elaborate on why you need these methods?" } ]
[ { "body": "<p>Given that <code>arrayCopy</code> has exactly one line, it's not clear that there's much value in having it extracted as a method.</p>\n<p><code>toArray()</code> is <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/List.html#toArray()\" rel=\"noreferrer\">documented</a> to return a safe array, so there is no need to copy it.</p>\n<p><code>getCopyOfList</code> returns a fixed-length list without documenting that fact. Clients may be surprised that optional <code>List</code> methods such as <code>add()</code> and <code>remove()</code> are not supported.</p>\n<p>Why wouldn't clients prefer to use the copy constructors available on <code>LinkedList</code> and <code>ArrayList</code>? Those would allow clients to control the type of List they're working with, and the call is part of the public API.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T16:38:44.493", "Id": "533805", "Score": "0", "body": "Thanks for the feedback, I will adapt my implementation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T04:18:11.390", "Id": "270314", "ParentId": "270312", "Score": "11" } }, { "body": "<p>Don't create Rube Goldberg machines. There is an easier way to accomplish what you want:</p>\n<pre><code>public static &lt;T&gt; List&lt;T&gt; getCopyOfList(List&lt;T&gt; list) {\n \n return new ArrayList&lt;T&gt;(list);\n \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T19:40:06.607", "Id": "270336", "ParentId": "270312", "Score": "2" } } ]
{ "AcceptedAnswerId": "270314", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T23:37:11.030", "Id": "270312", "Score": "4", "Tags": [ "java", "array", "generics", "casting" ], "Title": "Method for create a copy of List<T>" }
270312
<p>I am working with Raspberry Pi and I made this little Python script that plays sound while you hold down a button and it keeps repeating while you hold it. and no matter when you stopped holding button, the next time you press it it should start from beginning.</p> <p>This code works, but I fear it is slowly leaking memory, memory usage is slowly increasing while program runs, it's intended to run continuously so it could become problem after few weeks/months. Is there anything I could do to improve this script?</p> <pre><code>import digitalio import time import board from mpg123 import Mpg123, Out123 button1 = digitalio.DigitalInOut(board.D17) button1.direction = digitalio.Direction.INPUT button1.pull = digitalio.Pull.UP filepath=str('/home/pi/test/Sound001.mp3') mp3 = Mpg123(filepath) out = Out123() while True: if button1.value: del mp3 mp3 = Mpg123(filepath) for frame in mp3.iter_frames(out.start): if not button1.value: break out.play(frame) time.sleep(2) time.sleep(0.5) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T17:00:13.977", "Id": "533807", "Score": "2", "body": "What is not clear to me is why you continuously do `del mp3` to then re-instantiate it after. It's defined on the top of the script and that should suffice. Not saying this is the cause of the suspected memory leak, but it's the one thing that stands out in that short script. I would suggest to test your application with a **profiling** tool, Valgrind perhaps. The problem can also be caused by third-party libraries you are using." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T06:14:45.057", "Id": "533846", "Score": "0", "body": "@Anonymous I have to re-instantiate it so that it start playing sound from beginning, otherwise it just keeps playing from where I left before." } ]
[ { "body": "<p>I suppose you are using <a href=\"https://github.com/20tab/mpg123-python\" rel=\"nofollow noreferrer\">this wrapper</a>, which appears to be somewhat minimalistic. To &quot;rewind&quot; the sound file it should suffice to re-instantiate the class like this before starting the loop again:</p>\n<pre><code>mp3 = Mpg123(filepath)\nfor frame in mp3.iter_frames(out.start):\n out.play(frame)\n</code></pre>\n<p>See if that makes any difference. There may be a better way, like resetting the offset value, but needs testing.</p>\n<p>While we are at it:</p>\n<pre><code>filepath=str('/home/pi/test/Sound001.mp3')\n</code></pre>\n<p>can simply be written as:</p>\n<pre><code>filepath = '/home/pi/test/Sound001.mp3'\n</code></pre>\n<p>since you are already passing a string, it needs no conversion using str.</p>\n<p>If you are concerned with memory leaks, you can test your program with the calls to the MP3 lib commented out (that is, disable the sounds) and see how it behaves over time, and if the problem can indeed be pinned down on the usage of that library.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T22:01:03.793", "Id": "270369", "ParentId": "270318", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T08:04:58.647", "Id": "270318", "Score": "0", "Tags": [ "python", "memory-optimization", "raspberry-pi" ], "Title": "Possible memory leak in Python script which plays sound while holding down a button" }
270318
<p>I have a collection which, after the code has ran, looks something like the following:</p> <pre><code>[ { title: 'alpha', lines: [ { *some object* } ] }, { title: 'bravo', lines: [ { *some object* } ] }, { title: 'charl', lines: [ { *some object* } ] }, { title: 'delta', lines: [ { *some object*, *some object 2*, *some object 3* } ] m}, { title: 'echoo', lines: [ { *some object* } ] }, ] </code></pre> <p>The way that I'm doing this is:</p> <ol> <li>Check if there is an object in the outer array that has a matching <code>title</code> <ul> <li>If it doesn't exist, create that object with the <code>title</code> and <code>lines</code></li> </ul> </li> <li>Check if inside <code>lines</code> there is an object that exists at the specific supplied index <ul> <li>If it doesn't exist, create the object at that index</li> <li>Otherwise take the existing object at that index and append <code>val</code> to <code>a_or_b</code></li> </ul> </li> </ol> <p>This method will get called multiple times per group i.e. 4 times for <code>alpha</code>, 4 times for <code>bravo</code>, and 4 times for each line in <code>delta</code>. There is currently one group (but there may be more in the future) which has more than one object inside the <code>lines</code>.</p> <pre><code>def data_with(data, val, group, date, nom, a_or_b, line_no = 0) # add this group if it doesn't exist if data.find { |x| x[:title] == group }.nil? data &lt;&lt; { title: group, lines: [] } end # if the line at the line_no doesn't exist, create it if data.find { |x| x[:title] == group }[:lines][line_no].nil? data.find { |x| x[:title] == group }[:lines][line_no] = { date: date, nom: nom, a_or_b.to_sym =&gt; val } else # add to the value of the line at the line_no index data.find { |x| x[:title] == group }[:lines][line_no][a_or_b.to_sym] += val end end </code></pre> <p>What are some ways I can improve this method?</p>
[]
[ { "body": "<p>In general I think something feels off with your data structure and the naming of your parameters / variables is extremely difficult to understand (e.g. what is an <code>a_or_b</code>?).</p>\n<p>Anyway, you could structure your code a bit more object oriented and extract helper methods. I don't know the full context of your application so this might be overkill. To provide some food for thoughts here is an example:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>input = [\n { title: 'alpha', lines: [ { a_or_b: 1 } ] },\n { title: 'bravo', lines: [ { a_or_b: 1 } ] },\n { title: 'charl', lines: [ { a_or_b: 1 } ] },\n { title: 'delta', lines: [ { a_or_b: 1 } ] },\n { title: 'echoo', lines: [ { a_or_b: 1 } ] },\n]\n\nclass Collection\n class Entry\n def initialize(data)\n @data = data\n end\n\n def ==(other)\n @data[:title] == other\n end\n\n def update_or_create_line_by(index:, date:, nom:, a_or_b:, value:)\n update_line_by(index: index, value: value, a_or_b: a_or_b) ||\n create_line_by(index: index, date: date, nom: nom, a_or_b: a_or_b, value: value)\n end\n\n def create_line_by(index:, date:, nom:, a_or_b:, value:)\n lines[index] = {\n date: date,\n nom: nom,\n a_or_b.to_sym =&gt; val\n }\n end\n\n def update_line_by(index:, value:, a_or_b:)\n return unless lines[index]\n\n lines[index][a_or_b.to_sym] += value\n end\n\n private\n\n def lines\n @data[:lines]\n end\n end\n\n def initialize(data)\n @data = data.map { |entry| Entry.new(entry) }\n end\n\n def find_or_create(title:)\n find_by(title: title) || create_by(title: title)\n end\n\n def find_by(title:)\n @data.find { |entry| entry == title }\n end\n\n def create_by(title:)\n entry = Entry.new(title)\n @data &lt;&lt; entry\n entry\n end\nend\n\ndef data_with(data, val, group, date, nom, a_or_b, line_no = 0)\n collection = Collection.new(data)\n entry = collection.find_or_create(title: group)\n entry.update_or_create_line_by(index: line_no, date: date, nom: nom, a_or_b: a_or_b, value: val)\nend\n\ndata_with(input, 1, 'alpha', Time.now, 'nom', 'a_or_b', 0)\nputs input\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T02:34:19.377", "Id": "270402", "ParentId": "270322", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T10:14:43.033", "Id": "270322", "Score": "1", "Tags": [ "ruby" ], "Title": "Code for appending to a certain index of an array" }
270322
<p>I need to write a function to count numbers of nests in an iterable. I reached my goal but wondering if there's any more neat/faster solution (maybe even a library or so?). Besides I'm afraid that my code is error prone.</p> <p>Let's analyze two examples:</p> <pre class="lang-py prettyprint-override"><code>dct_test = { &quot;a&quot;: {1: 2, 2: 3, 3: 4}, &quot;b&quot;: {&quot;x&quot;: &quot;y&quot;, &quot;z&quot;: [1, 2, 3, {7, 8}]}, &quot;c&quot;: {&quot;l&quot;: (2, 3, 5), &quot;j&quot;: {&quot;a&quot;: {&quot;k&quot;: 1, &quot;l&quot;: [1, 3, (2, 7, {&quot;x&quot;: 1})]}}}, &quot;d&quot;: [1, (2, 3)] } tpl_test = (1, [3, 4, {5, 6, 7}], {&quot;a&quot;: 5, &quot;b&quot;: [9, 8]}) </code></pre> <p>This is a visualization of what I'm trying to achieve: <a href="https://i.stack.imgur.com/sIfDZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sIfDZ.png" alt="Algorithm" /></a></p> <p>Code:</p> <pre class="lang-py prettyprint-override"><code>from collections.abc import Iterable from itertools import chain # EXAMPLES dct_test = { &quot;a&quot;: {1: 2, 2: 3, 3: 4}, &quot;b&quot;: {&quot;x&quot;: &quot;y&quot;, &quot;z&quot;: [1, 2, 3, {7, 8}]}, &quot;c&quot;: {&quot;l&quot;: (2, 3, 5), &quot;j&quot;: {&quot;a&quot;: {&quot;k&quot;: 1, &quot;l&quot;: [1, 3, (2, 7, {&quot;x&quot;: 1})]}}}, &quot;d&quot;: [1, (2, 3)] } tpl_test = (1, [3, 4, {5, 6, 7}], {&quot;a&quot;: 5, &quot;b&quot;: [9, 8]}) # FUNCTIONS # checking if an argument is a 'real' iterable (list, tuple, set, dictionary) def IsRealIterable( iter: Iterable ): return True if isinstance(iter, Iterable) and not isinstance(iter, str) else False # converting an iterable to a list def ConvertIterableToList( iter: Iterable, dct_keys=False, # False returns dict.values(), True returns dict.keys() ): if IsRealIterable(iter): if isinstance(iter, tuple) or isinstance(iter, set): return list(iter) elif isinstance(iter, dict): return list(iter.keys()) if dct_keys else list(iter.values()) elif isinstance(iter, list): return iter else: raise TypeError(&quot;Given argument is not a list, tuple, set or dictionary&quot;) # returns a list of iterables extracted from an iterable def ExtractFromIterable( iter: Iterable ): if IsRealIterable(iter): return [i for i in ConvertIterableToList(iter) if IsRealIterable(i)] else: raise TypeError(&quot;Given argument is not a list, tuple, set or dictionary&quot;) # returns number of levels in an iterable def CountNestingLevels( iter: Iterable, cntr: int=0, only_sublevels: bool=True # if False then returns number of all nesting levels - not only a number of nests ): lst_to_inspect = ExtractFromIterable(iter) lst_deep = [] # empty list for nested iterables # analyzing structure # if lst_to_inspect is empty then returns already counted number of levels if not lst_to_inspect: return cntr if only_sublevels else cntr + 1 else: cntr += 1 for i in lst_to_inspect: # temporary list for iterables from each element in lst_to_inspect temp_list = ExtractFromIterable(i) # elements (only non-empty) should be added to lst_deep because otherwise ExtractFromIterable() would overwrite existing values lst_deep.append(temp_list) if temp_list else None # flattening lst_deep. it contains lists returned by ExtractFromIterable so lst_deep has structure: [[[], [], ...]] lst_deep = list(chain.from_iterable(lst_deep)) # using ExtractFromIterable in lst_deep may return the same structure as lst_to_inspect # if no - use recursion to analyze remaining elements again # if yes - finish analyzing if lst_deep != lst_to_inspect: return CountNestingLevels(lst_deep, cntr) else: return cntr if only_sublevels else cntr + 1 print(CountNestingLevels(dct_test)) # returns 6 print(CountNestingLevels(tpl_test)) # returns 2 </code></pre> <p>Do you have any tips how to improve this code?</p>
[]
[ { "body": "<p>I think we could make use of recursivity, as well as dunder (double underscore) attribute.\nFor example</p>\n<pre><code>def is_iterable(a):\n if &quot;__iter__&quot; in a.__dir__():\n print(&quot;I am an iterable ! You can do `for x in a`&quot;)\n else:\n print(&quot;I am not an iterable ! You can move on&quot;)\n\n&gt;&gt;&gt; a_dict = {&quot;5&quot;: 3}\n&gt;&gt;&gt; is_iterable(a_dict)\nI am an iterable ! You can do `for x in a`\n&gt;&gt;&gt; a_list = [1]\n&gt;&gt;&gt; is_iterable(a_list)\nI am an iterable ! You can do `for x in a`\n&gt;&gt;&gt; a_int = 7\n&gt;&gt;&gt; is_iterable(a_int)\nI am not iterable ! You can move on\n&gt;&gt;&gt; a_set = {3}\n&gt;&gt;&gt; is_iterable(a_set)\nI am an iterable ! You can do `for x in a`\n</code></pre>\n<p>With that, you can now check if the object you have is iterable, if it is, you iterate over it (for x in the_iterable) and call the same function on all the items of that iterable, incrementing a function parameter counter by 1 at each step</p>\n<pre><code>def recursive_function(an_object, counter=0):\n if &quot;__iter__&quot; in an_object.__dir__():\n for x in an_object:\n recursive_function(x, counter+1)\n</code></pre>\n<p>Now the last part is to keep the highest counter, but I think you got the idea !</p>\n<p>This should use memory and time way more efficiently</p>\n<p>Hope this helps !</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T17:31:18.300", "Id": "533813", "Score": "3", "body": "From the Python [docs](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable): *The only reliable way to determine whether an object is iterable is to call `iter(obj)`*. Using `iter()` is also a bit simpler/easier in terms of the code that has to be typed. For more context, see [StackOverflow](https://stackoverflow.com/a/36407550/55857)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T17:11:10.457", "Id": "270334", "ParentId": "270323", "Score": "2" } }, { "body": "<p>In more than one place your code assumes that it is restricted to tuple, list, set,\nor dict. That's a perfectly reasonable policy decision for code like this. Given\nthat decision, the code to check for iterability is needlessly complex. Something\nalong these lines would do the trick:</p>\n<pre><code>isinstance(obj, (tuple, list, set, dict))\n</code></pre>\n<p>If your goal is to count nesting levels, there is no need to convert all of\nthose data structures into a list form. It's extra code and extra computation.\nThe only complication will be distinguishing dict from the other three types of\nsupported objects -- but that's easy enough to do.</p>\n<p>If we focus narrowly on lists, the depth of a list is just one plus the maximum\nof the depths of any sublists. Very roughly like this:</p>\n<pre><code>def depth(xs):\n if isinstance(xs, list):\n return 1 + max(depth(x) for x in xs)\n else:\n return 0\n</code></pre>\n<p>But that code will fail, for example, if the list is empty, because <code>max()</code>\nwill raise a <code>ValueError</code>.</p>\n<p>So we can revise that rough draft to handle the empty case. In the process,\nwe can also handle the other three collection types:</p>\n<pre><code>def depth(obj):\n xs = (\n obj if isinstance(obj, (tuple, list, set)) else\n obj.values() if isinstance(obj, dict) else\n None\n )\n return (\n 0 if xs is None else # Not a collection.\n 1 if not xs else # Empty collection.\n 1 + max(depth(x) for x in xs) # Non-empty.\n )\n</code></pre>\n<p>Finally, note that <code>depth()</code> differs from your implementation because it counts\nthe top level, so it returns depths one greater than your calculations. That\nmakes more sense to me, because it distinguishes the supported data types\n(which always have a depth of at least one) from the unsupported data types\n(which have a depth of zero). Maintaining that distinction allows the algorithm\nto be composed more easily in a recursive context. Adjust as needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T10:33:10.393", "Id": "533855", "Score": "0", "body": "Wow! I haven't expected this code can be THAT short. Thank you so much - especially for realizing that I don't have to write chains of `isinstance() or isinstance()...`. However, I don't fully understand how the last `depth()` works. Can you explain it further?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T15:28:01.410", "Id": "533870", "Score": "1", "body": "@Konrad The first part just distinguishes between (a) tuple/list/set, (b) dict, or (c) something else. And the second part computes the depth: 0 for something-else, 1 for an empty collection, and 1 plus the depths of sub-collections for non-empty." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T15:19:45.097", "Id": "533920", "Score": "0", "body": "Thanks for explanation. I added comments in order to better understand your code. Are they correct? Additionally, I asked another question which expands this subject. Please check if you like: [link](https://codereview.stackexchange.com/q/270386/252081)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T18:28:37.803", "Id": "270335", "ParentId": "270323", "Score": "2" } } ]
{ "AcceptedAnswerId": "270335", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T10:39:17.077", "Id": "270323", "Score": "6", "Tags": [ "python", "beginner" ], "Title": "Counting 'absolute' nesting levels of an iterable" }
270323
<p>I have the following function that returns StaffQualifications where either the qualification is expiring or the qualification type is expiring, but this section doesn't seem to sit well with me as it splits up the SQL string... Should this be two separate functions perhaps even though 95% of the query is the same?</p> <pre><code> if ($qualification instanceof Qualification) { $sql .= &quot;AND q.id = :qualificationId &quot;; } elseif ($qualificationType instanceof QualificationType) { $sql .= &quot;AND q.qualification_type_id = :qualificationTypeId &quot;; } </code></pre> <p>The above doesn't quite feel right, but not sure how to better it.</p> <pre><code>/** * @return StaffQualification[] */ public function getStaffQualificationsExpiringOnQualificationOrQualificationType(?Qualification $qualification, ?QualificationType $qualificationType): array { if ($qualification === null &amp;&amp; $qualificationType === null) { throw new \Exception('Qualification or QualificationType must not be null'); } if ($qualification instanceof Qualification &amp;&amp; $qualificationType instanceof QualificationType) { throw new \Exception('Only one of Qualification or QualificationType can be present'); } $sql = &quot; SELECT * FROM staff_qualification AS sq &quot;; // Complicated SQL ensues that I've omitted from this SE question... if ($qualification instanceof Qualification) { $sql .= &quot;AND q.id = :qualificationId &quot;; } elseif ($qualificationType instanceof QualificationType) { $sql .= &quot;AND q.qualification_type_id = :qualificationTypeId &quot;; } $sql .= &quot; GROUP BY sq.id ORDER BY sq.end_date ; &quot;; $rsm = new ResultSetMapping(); $rsm-&gt;addEntityResult(StaffQualification::class, 'sq'); $rsm-&gt;addJoinedEntityResult(Staff::class, 's', 'sq', 'staff'); $rsm-&gt;addFieldResult('sq', 'id', 'id'); $rsm-&gt;addFieldResult('s', 'staff_id', 'id'); $query = $this-&gt;getEntityManager()-&gt;createNativeQuery($sql, $rsm); if ($qualification instanceof Qualification) { $query-&gt;setParameter('qualificationId', $qualification-&gt;getId()); } elseif ($qualificationType instanceof QualificationType) { $query-&gt;setParameter('qualificationTypeId', $qualificationType-&gt;getId()); } $result = $query-&gt;getResult(); return $result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T11:57:01.300", "Id": "533780", "Score": "1", "body": "We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//codereview.meta.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//codereview.meta.stackexchange.com/q/2436), rather than your concerns about the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T11:57:56.843", "Id": "533781", "Score": "3", "body": "It also appears that your code has been eviscerated - no need for that here; we prefer to review _full_ functions or programs." } ]
[ { "body": "<p>I think the best thing to do would be to extract the logic outside of the string building and pass it in. You could do this either inline as per below or with <code>sprintf</code> or Heredoc.</p>\n<pre><code>/**\n * @param ?Qualification $qualification\n * @param ?QualificationType $qualificationType\n * @return StaffQualification[]\n * @throws Exception\n */\npublic function getStaffQualificationsExpiringOnQualificationOrQualificationType(\n ?Qualification $qualification,\n ?QualificationType $qualificationType\n): array\n{\n if ($qualification === null &amp;&amp; $qualificationType === null) {\n throw new Exception('Qualification or QualificationType must not be null');\n }\n if ($qualification instanceof Qualification &amp;&amp; $qualificationType instanceof QualificationType) {\n throw new Exception('Only one of Qualification or QualificationType can be present');\n }\n\n if ($qualification instanceof Qualification) {\n $filterSql = &quot;q.id = :qualificationId &quot;;\n } elseif ($qualificationType instanceof QualificationType) {\n $filterSql = &quot;q.qualification_type_id = :qualificationTypeId &quot;;\n }\n $sql = &quot;\n SELECT *\n FROM staff_qualification AS sq\n WHERE 1=1\n AND $filterSql\n GROUP BY sq.id\n ORDER BY sq.end_date\n ;\n &quot;;\n\n $rsm = new ResultSetMapping();\n $rsm-&gt;addEntityResult(StaffQualification::class, 'sq');\n $rsm-&gt;addJoinedEntityResult(Staff::class, 's', 'sq', 'staff');\n $rsm-&gt;addFieldResult('sq', 'id', 'id');\n $rsm-&gt;addFieldResult('s', 'staff_id', 'id');\n $query = $this-&gt;getEntityManager()-&gt;createNativeQuery($sql, $rsm);\n if ($qualification instanceof Qualification) {\n $query-&gt;setParameter('qualificationId', $qualification-&gt;getId());\n } elseif ($qualificationType instanceof QualificationType) {\n $query-&gt;setParameter('qualificationTypeId', $qualificationType-&gt;getId());\n }\n $result = $query-&gt;getResult();\n return $result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T14:47:43.393", "Id": "270328", "ParentId": "270325", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T11:40:14.537", "Id": "270325", "Score": "-1", "Tags": [ "doctrine", "php7", "symfony4" ], "Title": "Find qualifications that are expiring" }
270325
<p><strong>Let's suppose I have 2 <code>repositories</code>:</strong></p> <ul> <li>first is responsible for creating job and return <code>jobId</code></li> <li>second is responsible for creating log and take <code>jobId</code> as argument</li> </ul> <p><strong>My goal is to:</strong></p> <ul> <li>save <code>Job</code> and <code>Log</code> simultaneously</li> <li>prevent situation when in case of error only <code>Job</code> would be saved without <code>Log</code></li> </ul> <h3>What is the most recommended way to get desired result?</h3> <p>I prepared 3 cases which came to my mind but if you see better alternative please share it.</p> <ul> <li><strong>option 1 (getting result and save changes in controller)</strong></li> </ul> <pre class="lang-cs prettyprint-override"><code>public class JobRepository : IJobRepository { private readonly Context _context; public JobRepository(Context context) { _context = context; } public Guid CreateJob() { var job = new Job { Id = Guid.NewGuid() }; _context.Jobs.Add(job); return job.Id; } } // ... public class LogRepository : ILogRepository { private readonly Context _context; public LogRepository(Context context) { _context = context; } public void CreateLog(Guid id) { var log = new Log { Jobid = id }; _context.Logs.Add(log); } } // ... public class JobsController : Controller { private readonly Context _context; private readonly IJobRepository _jobRepository; private readonly ILogRepository _logRepository; public JobsController(Context context, JobRepository jobRepository, ILogRepository logRepository) { _context = context; _jobRepository = jobRepository; _logRepository = logRepository } [HttpGet] public IActionResult Create() { return View(); } [HttpPost] public IActionResult Create() { var id = _jobRepository.CreateJob(); _logRepository.CreateLog(id); _context.SaveChanges(); return RedirectToAction(&quot;Index&quot;); } } </code></pre> <ul> <li><strong>option 2 (inject one repository into another)</strong></li> </ul> <pre class="lang-cs prettyprint-override"><code>public class JobRepository : IJobRepository { private readonly Context _context; private readonly ILogRepository _logRepository; public JobRepository(Context context, ILogRepository logRepository) { _context = context; } public void CreateJob() { var job = new Job { Id = Guid.NewGuid() }; _context.Jobs.Add(job); _logRepository.CreateLog(job.Id); _context.SaveChanges(); } } // ... public class LogRepository : ILogRepository { private readonly Context _context; public LogRepository(Context context) { _context = context; } public void CreateLog(Guid id) { var log = new Log { Jobid = id }; _context.Logs.Add(log); } } // ... public class JobsController : Controller { private readonly IJobRepository _jobRepository; public JobsController(JobRepository jobRepository) { _jobRepository = jobRepository; } [HttpGet] public IActionResult Create() { return View(); } [HttpPost] public IActionResult Create() { _jobRepository.CreateJob(); return RedirectToAction(&quot;Index&quot;); } } </code></pre> <ul> <li><strong>option 3 (do not use context in controller but declare <code>Save</code> method in each repo)</strong></li> </ul> <pre class="lang-cs prettyprint-override"><code>public class JobRepository : IJobRepository { private readonly Context _context; public JobRepository(Context context) { _context = context; } public Guid CreateJob() { var job = new Job { Id = Guid.NewGuid() }; _context.Jobs.Add(job); return job.Id; } public void Save() { _context.SaveChanges(); } } // ... public class LogRepository : ILogRepository { private readonly Context _context; public LogRepository(Context context) { _context = context; } public void CreateLog(Guid id) { var log = new Log { Jobid = id }; _context.Logs.Add(log); } public void Save() { _context.SaveChanges(); } } // ... public class JobsController : Controller { private readonly IJobRepository _jobRepository; private readonly ILogRepository _logRepository; public JobsController(JobRepository jobRepository, ILogRepository logRepository) { _jobRepository = jobRepository; _logRepository = logRepository } [HttpGet] public IActionResult Create() { return View(); } [HttpPost] public IActionResult Create() { var id = _jobRepository.CreateJob(); _logRepository.CreateLog(id); return RedirectToAction(&quot;Index&quot;); } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T15:55:06.620", "Id": "533800", "Score": "2", "body": "Unfortunately none of them is correct. If one of the `save` command fails then the other is not rolled back. So both changes should be tackled under the same DbContext to be able to participate in a same transaction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T16:25:16.663", "Id": "533803", "Score": "0", "body": "plus, it seems you're using `EF` as `SaveChanges` exists in `DbContext`, if that's true, then the best approach would be to override `SaveChanges` to log entities changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T13:01:56.257", "Id": "533859", "Score": "2", "body": "This question seems better suited to StackOverflow or SoftwareEngineering.SE. This isn't a request for a code review." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T14:49:07.513", "Id": "270329", "Score": "0", "Tags": [ "c#", ".net", "asp.net-mvc" ], "Title": "Best approach to combine repositories logic" }
270329
<p>I wrote this script partly as an exercise in learning Bash and partly because I needed a tool to find specific versions of library files and copy them to a particular device.</p> <p>The script takes parameters that control its operation. First, it searches for the file specified by the user. Then it displays the search results, allowing the user to pick one of the files found, and (assuming a file was selected) copying it to the specified destination/path.</p> <p>I would most like feedback on whether the script could be written more clearly or perhaps whether there are better ways to approach its tasks.</p> <pre><code>#!/bin/bash # libr.sh (librarian): find the file you need, and put it where you want. #-------------------------process parameters if [ $# -eq 0 ] || [ $# -gt 3 ] then echo &quot;Usage: libr &lt;FILENAME&gt; [DESTINATION] [IP]&quot; echo &quot;The librarian will find FILENAME in the current directory or below&quot; echo &quot;and will then copy it to the DESTINATION path on the unit at IP.&quot; echo &quot;If multiple files are found, the user may choose which to copy.&quot; exit fi FILE=$1 DEST=${2:-/usr/lib/} IP=${3:-160.48.199.99} #-------------------------find the file FULLRESULTS=$(find -name $FILE 2&gt; /dev/null) echo &quot;File \&quot;$FILE\&quot; was found in the following directories:&quot; if [ -z &quot;$FULLRESULTS&quot; ] then echo &quot; None!&quot; exit fi # `find` returns the path plus filename for each file found # but we just want the directories, for ease of reading RESULTS=$(dirname $FULLRESULTS) #-------------------------display results and get the source path PS3=&quot;Which one do you want to copy ? &quot; select SRCPATH in $RESULTS do if [ ! -z &quot;$SRCPATH&quot; ] then #-----------------copy the file CMD=&quot;scp $SRCPATH/$FILE root@$IP:$DEST&quot; echo &quot;Executing: $CMD&quot; $CMD fi # we don't actually want to loop break done </code></pre>
[]
[ { "body": "<p>Thanks for submitting this for a code review. I like the indentation and documentation in your code.</p>\n<p>The biggest problem I see with this is dealing with filenames that haves spaces in them. Your <code>select</code> line will almost certainly break. The <code>find</code> command will let you get the results null-terminated using <code>-print0</code>, but I'm not sure how to get the <code>select</code> to work with that. Hopefully in your use-case you can avoid filename with spaces and avoid fixing this.</p>\n<h1>Small suggestions</h1>\n<ul>\n<li>Mention the defaults in the usage printout. Maybe move the defaults to variables so you Don't Repeat Yourself.</li>\n<li>Use double square brackets around conditionals to avoid unpleasant surprises and subtle bugs.</li>\n<li>Move the <code>then</code>s up on the same line as the <code>if</code> with <code>; then</code>.</li>\n<li>Consider checking for whether the find got any results before printing &quot;was found&quot;. You could print out one message for no results and only print your current &quot;File ... was found ...&quot; message if something was actually found.</li>\n<li>Rather than put the <code>scp</code> command into a variable just so you can display it you could cut on tracing with <code>set -x</code> and then cut it back off right after with <code>set +x</code>.</li>\n<li>Check out <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">shellcheck</a>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T21:51:25.910", "Id": "270343", "ParentId": "270331", "Score": "4" } } ]
{ "AcceptedAnswerId": "270343", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T16:05:50.780", "Id": "270331", "Score": "5", "Tags": [ "beginner", "bash" ], "Title": "Librarian script to find and copy a file" }
270331
<p>I'm using (non-boost) Asio 1.18.1 and C++17. Forgive the boost tag, there wasn't a more specific one.</p> <p>I have a <code>async_connect_with_retry</code> composed asynchronous operation:</p> <pre class="lang-cpp prettyprint-override"><code>/// Calls resolver.async_resolve(...), async_connect(socket, ...), and (on /// failure) timer.async_wait(...) to start over. template &lt;typename Timer, typename Token&gt; auto async_connect_with_retry(Timer&amp; timer, asio::ip::tcp::socket&amp; socket, asio::ip::tcp::resolver&amp; resolver, std::string_view host, std::string_view service, typename Timer::duration retry_delay, Token token); </code></pre> <p>I'm struggling to turn this into a reusable and extensible <code>reconnecting_socket</code> TCP client socket class (or possibly another composed op, if its more ergonomic). This is useful for connecting to embedded systems, for instance.</p> <p>My main focus is ease of use for the person extending the class, especially for new-to-Asio users.</p> <p>I am not interested in making everything generic yet (e.g. it's fine that I use <code>ip::tcp::socket</code> and not <code>basic_socket&lt;Protocol, Executor&gt;</code>). That can come later.</p> <p>Feedback on the <code>async_</code> methods is welcome, but I'm mostly interested in <code>reconnecting_socket.h</code>.</p> <p>The biggest unsolved problems:</p> <ol> <li>How do I give the user a customization point in the <code>reconnecting_socket::handle_connect</code> method? The user could start an <code>async_read</code> loop, and maybe a <code>async_write</code> heartbeat loop. <ul> <li>Extending the class (and making <code>socket_</code> <code>protected</code>) makes using <code>shared_from_this()</code> to extend the object's lifetime <a href="https://stackoverflow.com/questions/657155/how-to-enable-shared-from-this-of-both-parent-and-derived">tricky to get right</a>.</li> <li>Providing a callback has the same lifetime issues, and now we need a getter for <code>socket_</code> if they want to write anything.</li> </ul> </li> <li>How does the &quot;reconnect&quot; get triggered? The user could call <code>close()</code> if they get an error, but then if they have a write loop and a read loop, and both fail, they'll probably call <code>close()</code> twice, which would cause problems (two <code>start_connect</code> calls, multiple closes, etc.). Plus with this scheme the user has to remember to call <code>close()</code>. Maybe that's an OK tradeoff, though.</li> </ol> <p><strong>reconnecting_socket.h</strong></p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;iostream&gt; #include &quot;asio.hpp&quot; #include &quot;async_connect_with_retry.h&quot; class reconnecting_socket : public std::enable_shared_from_this&lt;reconnecting_socket&gt; { public: using ptr = std::shared_ptr&lt;reconnecting_socket&gt;; using tcp = asio::ip::tcp; using timer = asio::high_resolution_timer; reconnecting_socket(asio::io_context&amp; io_context, timer::duration retry_delay) : io_context_(io_context), socket_(io_context_), resolver_(io_context_), reconnect_timer_(io_context_), retry_delay_(retry_delay) {} void start(std::string_view host, std::string_view service) { assert(!started_); started_ = true; std::cout &lt;&lt; &quot;starting\n&quot;; host_ = host; service_ = service; start_connect(); } void stop() { end_ = true; close(false); } private: bool started_ = false; bool end_ = false; asio::io_context&amp; io_context_; tcp::socket socket_; tcp::resolver resolver_; timer reconnect_timer_; timer::duration retry_delay_; std::string_view host_; std::string_view service_; void close(bool reconnect = true) { asio::post(io_context_, [self = shared_from_this(), reconnect] { std::error_code ignored; self-&gt;socket_.shutdown(tcp::socket::shutdown_both, ignored); self-&gt;socket_.close(ignored); if (reconnect) self-&gt;start_connect(); }); } void start_connect() { if (end_) return; async_connect_with_retry( reconnect_timer_, socket_, resolver_, host_, service_, retry_delay_, [self = shared_from_this()](std::error_code error, auto endpoint) { self-&gt;handle_connect(error, endpoint); }); } void handle_connect(std::error_code error, tcp::endpoint endpoint) { if (!error) { std::cout &lt;&lt; &quot;connected to &quot; &lt;&lt; endpoint &lt;&lt; &quot;\n&quot;; // @todo how does the user customize this connection? } } }; </code></pre> <p><strong>async_connect_with_retry.h</strong></p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &quot;asio.hpp&quot; // @todo include what you use #include &quot;async_connect_to.h&quot; namespace detail { template &lt;typename Timer&gt; struct async_connect_with_retry_to_impl { Timer&amp; timer_; asio::ip::tcp::socket&amp; socket_; asio::ip::tcp::resolver&amp; resolver_; std::string_view host_; std::string_view service_; typename Timer::duration retry_delay_; // overload: starting template &lt;typename Self&gt; void operator()(Self&amp; self) { async_connect_to(socket_, resolver_, host_, service_, std::move(self)); } // overload: async_connect_to handler template &lt;typename Self&gt; void operator()(Self&amp; self, std::error_code error, asio::ip::tcp::endpoint endpoint) { if (error) { timer_.expires_after(retry_delay_); timer_.async_wait(std::move(self)); } else { self.complete(error, endpoint); } } // overload: async_wait handler template &lt;typename Self&gt; void operator()(Self&amp; self, std::error_code error) { if (error) { self.complete(error, {}); } else { async_connect_to(socket_, resolver_, host_, service_, std::move(self)); } } }; } // namespace detail /// Calls resolver.async_resolve(...), async_connect(socket, ...), and (on /// failure) timer.async_wait(...) to start over. template &lt;typename Timer, typename Token&gt; auto async_connect_with_retry(Timer&amp; timer, asio::ip::tcp::socket&amp; socket, asio::ip::tcp::resolver&amp; resolver, std::string_view host, std::string_view service, typename Timer::duration retry_delay, Token token) { return asio::async_compose&lt;Token, void(std::error_code, asio::ip::tcp::endpoint)&gt;( detail::async_connect_with_retry_to_impl&lt;Timer&gt;{ timer, socket, resolver, host, service, retry_delay}, token); } </code></pre> <p><strong>async_connect_to.h</strong></p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &quot;asio.hpp&quot; // @todo include what you use namespace detail { struct async_connect_to_impl { asio::ip::tcp::socket&amp; socket_; asio::ip::tcp::resolver&amp; resolver_; std::string_view host_; std::string_view service_; // overload: starting template &lt;typename Self&gt; void operator()(Self&amp; self) { resolver_.async_resolve(host_, service_, std::move(self)); } // overload: async_resolve handler template &lt;typename Self&gt; void operator()(Self&amp; self, std::error_code error, asio::ip::tcp::resolver::results_type results) { if (error) { self.complete(error, {}); } else { asio::async_connect(socket_, results, std::move(self)); } } // overload: async_connect handler template &lt;typename Self&gt; void operator()(Self&amp; self, std::error_code error, asio::ip::tcp::endpoint endpoint) { self.complete(error, std::move(endpoint)); } }; } // namespace detail /// Connect to a given address and port. Will resolve URIs. template &lt;typename Token&gt; auto async_connect_to(asio::ip::tcp::socket&amp; socket, asio::ip::tcp::resolver&amp; resolver, std::string_view host, std::string_view service, Token&amp;&amp; token) { return asio::async_compose&lt;Token, void(std::error_code, asio::ip::tcp::endpoint)&gt;( detail::async_connect_to_impl{socket, resolver, host, service}, token); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T17:08:19.513", "Id": "270333", "Score": "2", "Tags": [ "c++", "asynchronous", "c++17", "socket", "boost" ], "Title": "A reuseable reconnecting TCP socket with Asio" }
270333
<p>I'm trying to implement sum of 2 array using multi threading.</p> <p>I expected that when I use more threads it will be faster than when I use one thread, but that isn't the case.</p> <pre><code>public static int[] a = new int[100]; public static int[] b = new int[100]; public static int[] c = new int[a.Length]; public static int numberofthreads; static void Main(string[] args) { Random r = new Random(); for (int i = 0; i &lt; 100; i++) { a[i] = r.Next(5, 20); b[i] = r.Next(10, 30); } Console.WriteLine(&quot;Enter the Number of threads to use: &quot;); numberofthreads = int.Parse(Console.ReadLine()); var watch = new System.Diagnostics.Stopwatch(); watch.Start(); Thread[] threadsarray = new Thread[numberofthreads]; List&lt;Thread&gt; threads = new List&lt;Thread&gt;(); for (int i = 0; i &lt; numberofthreads; i++) { threadsarray[i] = new Thread(new ParameterizedThreadStart(myThreadMethod)); threadsarray[i].Start(i); // threadsarray[i].Join(); } watch.Stop(); Console.WriteLine(&quot;The First Array : &quot;); Console.WriteLine(string.Join(&quot;,&quot;, a)); Console.WriteLine(&quot;The Secound Array : &quot;); Console.WriteLine(string.Join(&quot;,&quot;, b)); Console.WriteLine(&quot;The Result Array : &quot;); Console.WriteLine(string.Join(&quot;,&quot;, c)); Console.WriteLine(&quot; &quot;); Console.WriteLine(watch.ElapsedMilliseconds.ToString()); } static void myThreadMethod(object threadid) { lock (threadid) { int start = a.Length; int thid = (int)threadid; for (int i = thid * a.Length / numberofthreads; i &lt; (thid + 1) * a.Length / numberofthreads; i++) { c[i] = a[i] + b[i]; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T20:47:40.417", "Id": "533835", "Score": "0", "body": "perhaps you're not aware of `Task` and `async` tasks on `NET 4+` as they're the better version of using `Thread` on the old versions of `NET`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T22:09:57.470", "Id": "533837", "Score": "5", "body": "You really would not see improvement on such a small array. In fact you should see degraded performance since there is a small overhead to spin up each thread. You may also consider using a .NET Range Partitioner to reduce code, but it too would be slower on such a small array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T00:36:05.850", "Id": "533840", "Score": "2", "body": "I disagree with the close vote - performance is on-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T07:14:47.793", "Id": "533848", "Score": "0", "body": "I'm trying to learn c# multi-threading can you help me with a better implementation , I don't know how to start learning at this topic. I googling for more answer but i didn't find an interesting topic. Thank you so much" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T07:31:53.130", "Id": "533849", "Score": "0", "body": "Are you trying to learn multi-threading with C# specifically or in general? The subject is vast : overhead, stalls, diminishing returns, synchronization ... I would suggest to find a \"pet project\" that uses a lot of parallel resources then try to apply threads concepts on it. e.g. apply an expensive block transform to a huge image and have each block processed by a different thread." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T07:55:36.627", "Id": "533850", "Score": "0", "body": "To be honest i learn multi-threading to resolve basic algorithms problem such as buble-sort algorithm and then i apply what i learned to my project tell me if it's a bad approche" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T08:52:49.813", "Id": "533851", "Score": "0", "body": "Welcome to Code Review@SE. Consider following a spelling checkers guidance. Please check the indentation of the code presented for review - I find it least error prone to copy code verbatim from the development environment, \"fencing it in\" lines containing just `~~~`. Even with `then` replaced I don't understand `better than * use one thread`." } ]
[ { "body": "<h1>Joining threads</h1>\n<p>After starting a thread, you have to call <code>join</code> to make sure it is done with its work. I see you have commented <code>join</code> out and I can guess why. The correct way to do this is to first start <b>all</b> the threads and then join them like so:</p>\n<pre><code>for (int i = 0; i &lt; numberofthreads; i++)\n{\n threadsarray[i] = new Thread(new ParameterizedThreadStart(myThreadMethod));\n threadsarray[i].Start(i);\n}\n\nfor (int i = 0; i &lt; numberofthreads; i++)\n{\n threadsarray[i].Join();\n}\n</code></pre>\n<h1>Unnecessarily locking threads</h1>\n<p>In <code>myThreadMethod</code> you are creating a critical section which basically means that only one thread at a time will be able to execute the function and the rest will be idling away waiting for the lock to become open. There is no need here to lock.</p>\n<h1>Performance</h1>\n<p>There are a couple of issues here with most of them already mentioned in the comments.</p>\n<p>Your calculation is too simple. Most of the time is simply spent reading and writing to memory and multi-threading will not really help with that.</p>\n<p>Let's see if we can create a bit more complicated tasks for the threads to keep them busy:</p>\n<pre><code>c[i] = (int)Math.Sqrt(Math.Pow(a[i], 2.0) + Math.Pow(b[i], 2.0));\n</code></pre>\n<h1>Putting it all together:</h1>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Threading;\n\nclass Program\n{\n public const int count = 100000000;\n public static int[] a = new int[count];\n public static int[] b = new int[count];\n public static int[] c = new int[count];\n public static int numberofthreads;\n\n static void Main(string[] args)\n {\n Random r = new Random();\n for (int i = 0; i &lt; count; i++)\n {\n a[i] = r.Next(5, 20);\n b[i] = r.Next(10, 30);\n }\n\n Console.WriteLine(&quot;Enter the Number of threads to use: &quot;);\n numberofthreads = int.Parse(Console.ReadLine());\n\n var watch = new System.Diagnostics.Stopwatch();\n\n watch.Start();\n Thread[] threadsarray = new Thread[numberofthreads];\n List&lt;Thread&gt; threads = new List&lt;Thread&gt;();\n\n for (int i = 0; i &lt; numberofthreads; i++)\n {\n threadsarray[i] = new Thread(new ParameterizedThreadStart(myThreadMethod));\n threadsarray[i].Start(i);\n }\n\n for (int i = 0; i &lt; numberofthreads; i++)\n threadsarray[i].Join();\n\n\n watch.Stop();\n Console.WriteLine($&quot;time = {watch.ElapsedMilliseconds.ToString()} ms&quot;);\n\n int total = 0;\n foreach (int v in c)\n total += v;\n\n Console.Write(&quot;c = &quot; + c);\n }\n static void myThreadMethod(object threadid)\n {\n int start = a.Length;\n int thid = (int)threadid;\n for (int i = thid * a.Length / numberofthreads; i &lt; (thid + 1) * a.Length / numberofthreads; i++)\n {\n c[i] = (int)Math.Sqrt(Math.Pow(a[i], 2.0) + Math.Pow(b[i], 2.0));\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T13:04:14.970", "Id": "270352", "ParentId": "270338", "Score": "1" } }, { "body": "<p>NOTE: my code examples below use .NET 6.</p>\n<p>As I said in the comments, your test is really so small that you will actual degrade performance with multiple threads. As this is CodeReview, all aspects of your code are subject to review, so let's cover some of the basics:</p>\n<p>You really should not have almost everything in Program.Main. Your specific logic should be placed in its own class, and leave Program at a minimum to call that logic.</p>\n<p>In your own class, the arrays should not be static. They should be class properties.</p>\n<p>Naming convention is to spell things out. So static field <code>a</code> becomes property <code>ArrayA</code>. Admittedly my own names could be better. I copied your code into a class that I named <code>Original</code>, so my modified class was named <code>Alternative</code>. Mea culpa.</p>\n<p>You should have your code be flexible to allow for larger arrays.</p>\n<p>You should employ some basic parameter checks for bad inputs.</p>\n<p>You should not rely upon so many magic numbers.</p>\n<p><strong>On to the heart of the app ...</strong></p>\n<p>You should stop thinking in terms of threads and number of threads. You may send 1000 threads to the scheduler and the scheduler will likely run far less than that concurrently. Instead, think in terms of MaxDegreeOfParallelism, i.e. the maximum number of threads that will be running concurrently. You should not waste time spinning up more threads than that or else you will degrade performance.</p>\n<p>Rather than a custom &quot;roll your own&quot; method, I am going to use a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.partitioner?view=net-6.0\" rel=\"nofollow noreferrer\">Partitioner</a> from the <code>System.Collections.Concurrent</code> namespace.</p>\n<p>I will now run a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.parallel.foreach?view=net-6.0\" rel=\"nofollow noreferrer\">Parallel.ForEach</a> passing in the ranged partitions as well as using <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.paralleloptions?view=net-6.0\" rel=\"nofollow noreferrer\">ParallelOptions</a> to declare <strong>MaxDegreeOfParallelism</strong>. Note as well that I have 2 methods: one runs single threaded and the other runs multi-threaded for easy comparison.</p>\n<p><strong>Alternative.cs</strong> (forgive the poor name)</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Collections.Concurrent;\nusing System.Diagnostics;\n\nnamespace Threading_Example\n{\n internal class Alternative\n {\n\n public int[] ArrayA { get; private set; } = new int[0];\n public int[] ArrayB { get; private set; } = new int[0];\n public int[] ArrayC { get; private set; } = new int[0];\n\n public int MaxDegreeOfParallelism { get; private set; }\n public int ArraySize { get; private set; } = 100;\n\n private Alternative(int size, int maxDegreeOfParallelism)\n {\n // There are probably more checks that could be done but here are the minimum.\n if (size &lt;= 0)\n {\n throw new ArgumentOutOfRangeException(nameof(size), &quot;Array size must be greater than 0&quot;);\n }\n if (maxDegreeOfParallelism &lt;= 0)\n {\n throw new ArgumentOutOfRangeException(nameof(maxDegreeOfParallelism), &quot;MaxDegreeOfParallelism must be greater than 0&quot;);\n }\n\n // While I could call Initialize() here, my philosophy is that a constructor\n // should do the BARE MINIMUM, which is only to set some properties and\n // then return as quickly as possible.\n // To that end, I mark the constructor as private, and require accessing\n // it via the public Create().\n\n this.ArraySize = size;\n this.MaxDegreeOfParallelism = maxDegreeOfParallelism;\n }\n\n public static Alternative Create(int size, int maxDegreeOfParallelism)\n {\n var instance = new Alternative(size, maxDegreeOfParallelism);\n // Initialize is intentionally run after construction.\n instance.Initialize();\n return instance;\n }\n\n private void Initialize()\n {\n ArrayA = new int[ArraySize];\n ArrayB = new int[ArraySize];\n ArrayC = new int[ArraySize];\n\n // Magic number replacements.\n // https://en.wikipedia.org/wiki/Magic_number_(programming)\n // Consider increasing with bigger arrays.\n // Consider making parameters or properties rather than constants.\n const int minA = 5;\n const int maxA = 20;\n const int minB = 10;\n const int maxB = 30;\n\n Random random = new Random();\n for (int i = 0; i &lt; ArraySize; i++)\n {\n // Consider increasing the magic num\n ArrayA[i] = random.Next(minA, maxA);\n ArrayB[i] = random.Next(minB, maxB);\n }\n }\n\n public TimeSpan RunSingleThreaded()\n {\n var watch = Stopwatch.StartNew();\n for (int i = 0; i &lt; ArraySize; i++)\n {\n ArrayC[i] = ArrayA[i] + ArrayB[i];\n\n }\n watch.Stop();\n return watch.Elapsed;\n }\n\n public TimeSpan RunMultiThreaded()\n {\n var watch = Stopwatch.StartNew();\n\n var rangeSize = ArraySize / MaxDegreeOfParallelism;\n if (ArraySize % MaxDegreeOfParallelism != 0)\n {\n rangeSize++;\n }\n\n // https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.partitioner?view=net-6.0\n var partitions = Partitioner.Create(0, ArraySize, rangeSize);\n var options = new ParallelOptions() { MaxDegreeOfParallelism = MaxDegreeOfParallelism };\n\n Parallel.ForEach(partitions, options, x =&gt;\n {\n for (var i = x.Item1; i &lt; x.Item2; i++)\n {\n ArrayC[i] = ArrayA[i] + ArrayB[i];\n }\n });\n\n watch.Stop();\n return watch.Elapsed;\n }\n\n }\n}\n</code></pre>\n<p><strong>Program.cs</strong></p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\n// https://codereview.stackexchange.com/questions/270338/sum-of-2-arrays-using-multi-threading\n\nnamespace Threading_Example\n{\n class Program\n {\n static void Main(string[] args)\n {\n RunTest(100, 4);\n RunTest(100, 8);\n RunTest(1_000_000, 4);\n RunTest(1_000_000, 8);\n RunTest(1_000_000_000, 4);\n RunTest(1_000_000_000, 8);\n\n Console.WriteLine();\n Console.WriteLine(&quot;Press ENTER key to quit.&quot;);\n Console.ReadLine();\n }\n\n private static void RunTest(int size, int maxDegreeOfParallism)\n {\n var example = Alternative.Create(size, maxDegreeOfParallism);\n\n Console.WriteLine();\n Console.WriteLine($&quot;Running single threaded for array size = {size:N0}&quot;);\n var elapsed1 = example.RunSingleThreaded();\n Console.WriteLine($&quot; Elapsed = {elapsed1}&quot;);\n\n Console.WriteLine($&quot;Running multi-threaded for array size = {size:N0}, maxDegreeOfParallism = {maxDegreeOfParallism}&quot;);\n var elapsed2 = example.RunMultiThreaded();\n Console.WriteLine($&quot; Elapsed = {elapsed2}&quot;);\n }\n }\n}\n</code></pre>\n<p><strong>Sample Console Output</strong></p>\n<p>This .NET 6 app was run on my PC with AMD Ryzen 9 3900X but it was being run inside a Hyper-V VM with 6 virtual processors.</p>\n<pre><code>Running single threaded for array size = 100\n Elapsed = 00:00:00.0000223\nRunning multi-threaded for array size = 100, maxDegreeOfParallism = 4\n Elapsed = 00:00:00.0264532\n\nRunning single threaded for array size = 100\n Elapsed = 00:00:00.0000009\nRunning multi-threaded for array size = 100, maxDegreeOfParallism = 8\n Elapsed = 00:00:00.0044602\n\nRunning single threaded for array size = 1,000,000\n Elapsed = 00:00:00.0074864\nRunning multi-threaded for array size = 1,000,000, maxDegreeOfParallism = 4\n Elapsed = 00:00:00.0007149\n\nRunning single threaded for array size = 1,000,000\n Elapsed = 00:00:00.0026112\nRunning multi-threaded for array size = 1,000,000, maxDegreeOfParallism = 8\n Elapsed = 00:00:00.0015015\n\nRunning single threaded for array size = 1,000,000,000\n Elapsed = 00:00:01.9090166\nRunning multi-threaded for array size = 1,000,000,000, maxDegreeOfParallism = 4\n Elapsed = 00:00:00.6679679\n\nRunning single threaded for array size = 1,000,000,000\n Elapsed = 00:00:02.2135724\nRunning multi-threaded for array size = 1,000,000,000, maxDegreeOfParallism = 8\n Elapsed = 00:00:00.7445674\n\nPress ENTER key to quit.\n</code></pre>\n<p><strong>Findings</strong></p>\n<p>What you should clearly see is that 100 elements is too small to gain performance from multi-threading. We see some improvement going to 1 million elements, and even more so going to 1 billion.</p>\n<p>What one could also see if that sometimes a larger <strong>MaxDegreeOfParallelism</strong> does not always mean better performance. It depends on many factors, such as complexity of calculations as well as CPU speed to name a couple.</p>\n<p><strong>UPDATE</strong></p>\n<p>I created a custom partitioner that has been posted as its <a href=\"https://codereview.stackexchange.com/questions/270502/a-custom-range-partitioner\">own CR question</a>. You may want to check it out since it demonstrates some eye-opening behavior when processing in parallel. It uses a slightly modified version of my answer using your array examples.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T15:42:27.627", "Id": "270355", "ParentId": "270338", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T20:16:16.213", "Id": "270338", "Score": "2", "Tags": [ "c#", "performance", "multithreading" ], "Title": "Sum of 2 arrays using multi threading" }
270338
<p>I want to edit Windows <strong>hosts</strong> file in the best way for the end user, using a batch-only solution. I ended up with this script, which works fine, but since I don't have enough knowledge, the syntax is very poor. So please, may you take a look and tell me how to improve it, especially the <code>=999</code> part (for some reason I can't use there <code>=replaced</code>, and can't use <code>=0</code> as it breaks future iterations):</p> <pre><code>REM In short: REM FOR for every line of the hosts file REM FOR to check current line if it contains our hosts and replace if so REM FOR for our hosts if they not been replaced and thus shall be inserted at the end of the hosts file @echo off setlocal enabledelayedexpansion set hostspath=%SystemRoot%\System32\drivers\etc\hosts set hosts[0]=first.host.com set hosts[1]=second.host.com set ip=127.1.2.3 set hostslenght=0 :hostsLenght if defined hosts[%hostsLenght%] ( set /a &quot;hostslenght+=1&quot; GOTO :hostslenght ) &gt;&quot;%hostspath%.new&quot; ( set /a hostslenght-=1 for /f &quot;delims=: tokens=1*&quot; %%a in ('%SystemRoot%\System32\findstr.exe /n /r /c:&quot;.*&quot; &quot;%hostspath%&quot;') do ( set skipline= for /L %%h in (0,1,!hostslenght!) do ( echo %%b|find &quot;!hosts[%%h]!&quot; &gt;nul if not errorlevel 1 ( echo %ip% !hosts[%%h]! set /a hosts[%%h]=999 set skipline=true ) ) if not &quot;!skipline!&quot;==&quot;true&quot; (echo.%%b) ) for /L %%h in (0,1,!hostslenght!) do ( if not !hosts[%%h]!==999 ( echo %ip% !hosts[%%h]! ) ) ) REM move /y &quot;%hostspath%&quot; &quot;%hostspath%.bak&quot; &gt;nul || echo Can't backup %hostspath%. Try run the script as Administrator. REM move /y &quot;%hostspath%.new&quot; &quot;%hostspath%&quot; &gt;nul || echo Can't update %hostspath%. Try run the script as Administrator. endlocal echo The hosts file is updated. pause </code></pre> <p>It would be great to get rid of <code>set /a hostslenght-=1</code> (initially I wanted to decrement this in <code>for</code> loops, but it's wont decremented that way), and the last <code>for</code> as well.</p> <p><strong>Upd:</strong> Version 2. Horrible <code>=999</code> is defeated, but there is still problems with <code>hostslenght</code> (is there a way to not enumerate the hosts count?), and it will be nice to preserve original file's last line (<code>echo</code> is always leave empty line at the end, but I don't see a easy way to detect last <code>for</code> iteration)</p> <p>Before:</p> <pre><code>... set /a hosts[%%h]=999 ... if not !hosts[%%h]!==999 ( </code></pre> <p>After:</p> <pre><code>... set hosts[%%h]= ... if defined hosts[%%h] ( </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T00:34:43.893", "Id": "533839", "Score": "0", "body": "Oof. Why batch? If you're specifically targeting Windows, PowerShell is more ergonomic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T03:29:00.770", "Id": "533842", "Score": "0", "body": "@Reinderien Batch is simpler for end user, just download and run. And such solution is a classic in my specific case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T04:01:26.497", "Id": "533843", "Score": "1", "body": "It looks like your goal is to map multiple hostnames to 127.0.0.1 as a kind of black hole, and you want to do this on multiple machines that you manage? How are you deploying and getting this script to run on your hosts? It seems like it would be far more practical to run your own DNS proxy server (such as dnsmasq or similar)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T14:09:24.810", "Id": "533865", "Score": "0", "body": "@200_success For the end user, it's just a way to use some application with my server without editing the application files. I already have a good script for those who expect nothing but a working application, but I also want to have the perfect script for those who will check its source before running it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-23T21:47:51.613", "Id": "270342", "Score": "1", "Tags": [ "performance", "algorithm", "windows", "batch" ], "Title": "In a search of perfect batch script for editing the hosts file" }
270342
<p>I started learning classes and operator overloading in C++. To test my skills I decided to make a Fraction class with all necessary operations.</p> <p>I would appreciate improvements and suggesstions on my implementation.</p> <p>Here is the code -</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;stdexcept&gt; // throw std::invalid_argument // Function to find GCD(Greatest Common Divisor) of two numbers int gcd(int x, int y) { if (y == 0) return x; return gcd(y, x % y); } // Function to find LCM(Lowest Common Multiple) of two numbers int lcm(int x, int y) { return (x * y) / gcd(x, y); } // An immutable Fraction class class Fraction { private: int numerator; int denominator; public: // Constructor for improper fractions Fraction(int num, int deno=1) { if (deno == 0) { throw std::invalid_argument(&quot;Denominator can not be 0.&quot;); } int gcd_ = gcd(num, deno); num /= gcd_; deno /= gcd_; numerator = num; denominator = deno; if (denominator &lt; 0) { numerator *= -1; denominator *= -1; } } // Constructor for mixed fractions Fraction(int whole, int num, int deno) { if (deno == 0) { throw std::invalid_argument(&quot;Denominator can not be 0.&quot;); } int gcd_ = gcd(num, deno); num /= gcd_; deno /= gcd_; numerator = (whole * deno) + num; denominator = deno; } // Getter methods int get_numerator() {return numerator;} int get_denominator() {return denominator;} // Type casting methods operator int() {return numerator / denominator;} operator float() {return float(numerator) / denominator;} operator double() {return double(numerator) / denominator;} operator long() {return long(numerator) / denominator;} operator std::string() { std::string str_frac = std::to_string(numerator); if (denominator != 1) { str_frac += '/' + std::to_string(denominator); } return str_frac; } // Helps to print a fraction to the console friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Fraction&amp; frac) { os &lt;&lt; frac.numerator; if (frac.denominator != 1) { os &lt;&lt; '/' &lt;&lt; frac.denominator; } return os; } // Assingment operator Fraction operator=(Fraction frac2) { numerator = frac2.numerator; denominator = frac2.denominator; int gcd_ = gcd(numerator, denominator); numerator /= gcd_; denominator /= gcd_; } // Unary '-' operator, eg. -(1/2) Fraction operator-() { numerator *= -1; if (denominator &lt; 0) { numerator *= -1; denominator *= -1; } return *this; } // Binary operators - (+, -, *, /) Fraction operator+(Fraction frac2) { int lcm_ = lcm(denominator, frac2.denominator); return Fraction( (numerator * lcm_ / denominator) + (frac2.numerator * lcm_ / frac2.denominator), lcm_ ); } Fraction operator-(Fraction frac2) { int lcm_ = lcm(denominator, frac2.denominator); return Fraction( (numerator * lcm_ / denominator) - (frac2.numerator * lcm_ / frac2.denominator), lcm_ ); } Fraction operator*(Fraction frac2) { return Fraction(numerator * frac2.numerator, denominator * frac2.denominator); } Fraction operator/(Fraction frac2) { return Fraction(numerator * frac2.denominator, denominator * frac2.numerator); } // Comparision operators bool operator&lt;(Fraction frac2) { int lcm_ = lcm(denominator, frac2.denominator); return (numerator * lcm_ / denominator) &lt; (frac2.numerator * lcm_ / frac2.denominator); } bool operator&gt;(Fraction frac2) { int lcm_ = lcm(denominator, frac2.denominator); return (numerator * lcm_ / denominator) &gt; (frac2.numerator * lcm_ / frac2.denominator); } bool operator==(Fraction frac2) { int lcm_ = lcm(denominator, frac2.denominator); return (numerator * lcm_ / denominator) == (frac2.numerator * lcm_ / frac2.denominator); } bool operator&lt;=(Fraction frac2) { int lcm_ = lcm(denominator, frac2.denominator); return (numerator * lcm_ / denominator) &lt;= (frac2.numerator * lcm_ / frac2.denominator); } bool operator&gt;=(Fraction frac2) { int lcm_ = lcm(denominator, frac2.denominator); return (numerator * lcm_ / denominator) &gt;= (frac2.numerator * lcm_ / frac2.denominator); } }; int main() { Fraction frac1(-1, 2); Fraction frac2(1, -2); std::cout &lt;&lt; &quot;-1/2 * 1/-2 = &quot; &lt;&lt; frac1 * frac2 &lt;&lt; '\n'; } </code></pre> <p>Thanks for your time!</p>
[]
[ { "body": "<p>Generally, making your binary arithmetic operators member function a you have here is an issue because the two arguments are treated differently. The right argument will undergo implicit conversions, but the left will not! So, given a <code>Fraction f</code> and <code>int y</code> you could write <code>f+y</code> but cannot compile <code>y+f</code>.</p>\n<p>What you should do, canonically, is implement <code>+=</code> as a member function, and then implement <code>+</code> as a non-member (not a friend either) that just calls <code>+=</code> on a copy of the left argument.</p>\n<hr />\n<p>You are missing <code>const</code> on <strong>a lot</strong> of your member functions. Why can't you support, e.g.</p>\n<pre><code>const Fraction f (17,3);\nint x = f; // invoke operator int().\n\nif (7 &gt; f) ... // can't do that either\nif (f &lt; 7) ... // but this one works?\n\nconst Fraction g (19,2);\nif (f &lt; g) ... // can't do that :(\n</code></pre>\n<hr />\n<p>Instead of <code>int</code>, you should declare the component scalar type as a named alias. Later, you can easily turn it into a template.</p>\n<p>Instead of writing all the comparison operators (again, you have the left argument is different issue) individually, in C++20 you should implement the 3-way comparison operator and let them all autogenerate from that.</p>\n<p>In older compilers, if that is your intent to support the, you are missing <code>!=</code>. In C++20 it's autogenerated from <code>==</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T15:42:29.467", "Id": "270356", "ParentId": "270347", "Score": "3" } }, { "body": "<p>The helper functions <code>gcd()</code> and <code>lcm()</code> should have internal linkage (declared <code>static</code> or in an anonymous namespace), to avoid link-time name conflicts when we make this a library.</p>\n<p>Prefer to implement <code>gcd()</code> iteratively rather than recursively. Not all C++ compilers will eliminate even tail-recursion for you.</p>\n<hr />\n<p>Prefer to <em>initialise</em> your members, rather than <em>assigning</em> within the constructor:</p>\n<pre><code>// Constructor for improper fractions\nFraction(int num, int deno=1)\n : numerator{num},\n denominator{deno}\n{\n if (denominator == 0)\n {\n throw std::invalid_argument(&quot;Denominator can not be 0.&quot;);\n }\n int gcd_ = gcd(numerator, denominator);\n numerator /= gcd_;\n denominator /= gcd_;\n\n if (denominator &lt; 0)\n {\n numerator *= -1;\n denominator *= -1;\n }\n}\n\n// Constructor for mixed fractions\nFraction(int whole, int num, int deno)\n : Fraction{num + whole * deno, deno}\n{}\n</code></pre>\n<hr />\n<p>The assignment operator has some problems:</p>\n<ul>\n<li>It fails to return a value (your compiler should be telling you about this - make sure you enable plenty of warnings).</li>\n<li>It shouldn't need to reduce the fraction to simplest terms (we should simplify as part of each arithmetic operation).\nIt's probably best to remove this operator and let the compiler default it, as we do for the copy/move constructor.</li>\n</ul>\n<hr />\n<p>Conversion to <code>float</code> should probably do <code>double</code> division before truncating to <code>float</code>. Certainly on platforms such as the one I tested on (Linux/amd64) where <code>float</code> has less precision than <code>int</code>.</p>\n<pre><code>operator float() const { return static_cast&lt;float&gt;(operator double()); }\n</code></pre>\n<p>Conversion to integer types should be <code>explicit</code>:</p>\n<pre><code>explicit operator int() const { return numerator / denominator; }\n</code></pre>\n<hr />\n<p>Unary <code>-</code> should be a <code>const</code> operator, and not modify <code>*this</code>.</p>\n<hr />\n<p>We should use the output streaming operator in our tests, instead of hard-coding the values in the string:</p>\n<pre><code>std::cout &lt;&lt; frac1 &lt;&lt; &quot; * &quot; &lt;&lt; frac2 &lt;&lt; &quot; = &quot;\n &lt;&lt; frac1 * frac2 &lt;&lt; '\\n';\n</code></pre>\n<hr />\n<p>There's no guard against integer overflow in any of this code. That's something that should be considered.</p>\n<p>Also look at <a href=\"/a/157911/75307\">my review of <em>Implementation of a Rational Number class in C++</em></a> for some further inspiration, such as including user-defined literals and adding a suite of unit-tests.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T08:48:07.503", "Id": "270378", "ParentId": "270347", "Score": "2" } } ]
{ "AcceptedAnswerId": "270378", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T07:38:45.073", "Id": "270347", "Score": "2", "Tags": [ "c++", "object-oriented", "overloading", "rational-numbers" ], "Title": "Fractions in C++" }
270347
<p>I have a string like the one below from which I am extracting the tariff name.</p> <p><code>const url = &quot;https://any-api/supplier/tariffSelectionG_E5449168?t=randomChars&quot;</code></p> <p>So from the above string, I want text <code>tariffSelectionG_E5449168</code> and I am using the code below at the moment, which is working fine.</p> <pre><code>const supplyUrl = &quot;https://any-api/supplier/tariffSelectionG_E5449168?t=randomChars&quot; if(supplyUrl.includes('?')) { const url = supplyUrl.split('?') if(url.length &gt; 0) { const tariff = url[0].split('supplier/') return tariff[1] } } </code></pre> <p>Is there any better way to do the above extracting?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T10:42:27.653", "Id": "533856", "Score": "3", "body": "You could leverage named capturegroups like `re = /https.*?supplier\\/(?<param>.*)\\?/g; re.exec(supplyUrl).groups[\"param\"]` to retrieve the same result more compact." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T14:13:28.807", "Id": "533866", "Score": "1", "body": "If your environment supports it, you could use the [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) constructor." } ]
[ { "body": "<p>Super short review;</p>\n<ul>\n<li>The code should handle the presence or the absence <code>?</code> in a transparent way</li>\n<li>The code should probably check for <code>/supplier/</code> instead of <code>?</code></li>\n</ul>\n<p>That leaves me with</p>\n<pre><code>function extractTariffName(url){\n const resource = '/supplier/';\n if(url.contains(resource)){\n return url.split('?').shift().split(resource).pop();\n }\n //return undefined\n}\n\nconsole.log(extractTariffName('https://any-api/supplier/tariffSelectionG_E5449168?t=randomChars'));\nconsole.log(extractTariffName('https://any-api/supplier/tariffSelectionG_E5449168'));\nconsole.log(extractTariffName('https://any-api/supliar/tariffSelectionG_E5449168'));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T12:42:56.787", "Id": "270351", "ParentId": "270349", "Score": "5" } }, { "body": "<p>While it may be unlikely to occur, the URL <em>could</em> contain a hostname with a top-level domain <code>supplier</code>. Currently <a href=\"https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains#S\" rel=\"nofollow noreferrer\"><code>.supplies</code> is registered to Donuts Inc</a> and someday URLs could have a TLD with <code>supplier</code>, which would lead the current code to not correctly find the target text.</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 supplyUrl = \"https://my.supplier/supplier/tariffSelectionG_E5449168?t=randomChars\"\n if(supplyUrl.includes('?')) {\n const url = supplyUrl.split('?')\n if(url.length &gt; 0) {\n const tariff = url[0].split('supplier/')\n console.log('tariff:', tariff[1])\n }\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>A more robust solution would use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL\" rel=\"nofollow noreferrer\">URL API</a> with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL/pathname\" rel=\"nofollow noreferrer\">pathname property</a>. For example, if it was known that the last part of the pathname was the tariff string then the array method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop\" rel=\"nofollow noreferrer\"><code>.pop()</code></a> could be used:</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 supplyUrl = \"https://my.supplier/supplier/tariffSelectionG_E5449168?t=randomChars\"\nconsole.log('tariff: ', new URL(supplyUrl).pathname.split(/\\//).pop());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Otherwise if there is a need to find strings anywhere in the path that start with <code>tariff</code> then a pattern match could be used for that - for example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const supplyUrl = \"https://my.supplier/supplier/tariffSelectionG_E5449168?t=randomChars\"\nfunction findTariff(url) {\n const pathParts = new URL(url).pathname.split(/\\//);\n for (const part of pathParts) {\n if (part.match(/^tariff/)) {\n return part;\n }\n }\n return -1; // or something to signify not found\n}\nconsole.log('tariff: ', findTariff(supplyUrl));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Or one could take a functional approach, which can be more concise:</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 supplyUrl = \"https://my.supplier/supplier/tariffSelectionG_E5449168?t=randomChars\"\nfunction findTariff(url) {\n const pathParts = new URL(url).pathname.split(/\\//);\n return pathParts.find(part =&gt; part.match(/^tariff/));\n}\nconsole.log('tariff: ', findTariff(supplyUrl));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T17:46:06.490", "Id": "270362", "ParentId": "270349", "Score": "4" } }, { "body": "<p>If you can, use the <code>URL</code> constructor. It is a bit clearer semantically:</p>\n<pre><code>const supplyUrl = new URL(&quot;https://any-api/supplier/tariffSelectionG_E5449168?t=randomChars&quot;);\nconst parts = supplyUrl.pathname.split(&quot;/&quot;);\n\n// the 0th item is empty since the pathname starts with a slash\nconst tariff = parts[2];\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T18:15:54.353", "Id": "270363", "ParentId": "270349", "Score": "1" } }, { "body": "<p>I think for any url related task you have two good tools as</p>\n<ol>\n<li>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL\" rel=\"nofollow noreferrer\">URL API</a></li>\n<li>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API\" rel=\"nofollow noreferrer\">URLPattern API</a></li>\n</ol>\n<p>With the <code>URL</code> constructor you may do like;</p>\n<pre><code>var url = new URL(&quot;https://any-api/supplier/tariffSelectionG_E5449168?t=randomChars&quot;),\n tariffCode = url.pathname.slice(url.pathname.lastIndexOf(&quot;/&quot;)+1);\n</code></pre>\n<p><code>URLPattern</code> API, on the other hand is more powerful and convenient for this job despite being a little comprehensive. Keep in mind that it's a recent API and available in Chrome 95+. Server side, it is available in <a href=\"https://deno.land/\" rel=\"nofollow noreferrer\">Deno</a> (<em>which i like very much</em>) and possibly in recent Node versions too.</p>\n<p>In this particular case we can generate an URL Pattern which takes the path up until a variable that we declare. This variable represents the url portion of our interest. Lets name it <code>tariff</code>. Accordingly</p>\n<pre><code>var pat = new URLPattern({pathname: &quot;/supplier/:tariff&quot;});\n</code></pre>\n<p>Thats it.</p>\n<p>Once you receive an url first you can test it's validity against the pattern like;</p>\n<pre><code>pat.test(&quot;https://any-api/supplier/tariffSelectionG_E5449168?t=randomChars&quot;); // &lt;- true\n</code></pre>\n<p>If <code>true</code> then you can extract your tariff code like</p>\n<pre><code>var tariffCode = pat.exec(&quot;https://any-api/supplier/tariffSelectionG_E5449168?t=randomChars&quot;)\n .pathname.groups.tariff; // &lt;- &quot;tariffSelectionG_E5449168&quot;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T15:39:55.330", "Id": "270387", "ParentId": "270349", "Score": "3" } }, { "body": "<p>Get text before '?' with <code>split('?').at()</code>,\nthen reverse it and get text before '/'\nand reverse it back ;)\n<code>supplyUrl.split('?').at().split('').reverse().join('').split('/').at().split('').reverse().join('')</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T21:39:07.783", "Id": "270397", "ParentId": "270349", "Score": "0" } } ]
{ "AcceptedAnswerId": "270362", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T09:21:00.133", "Id": "270349", "Score": "6", "Tags": [ "javascript", "parsing", "ecmascript-6" ], "Title": "Extracting a part of a URL path" }
270349
<p>I have tried my hand with implementing simple quadrature formulas in C++.</p> <p>Definite integral: <span class="math-container">$$\int_a^b f(x) dx$$</span> Domain of integration <span class="math-container">\$[a, b]\$</span> divided into <span class="math-container">\$n\$</span> intervals of equal length <span class="math-container">\$h = (b - a) / n\$</span>.</p> <p>Midpoint of interval <span class="math-container">\$h_i = b_i - a_i\$</span> is <span class="math-container">$$x_i = a + h / 2 + (i - 1) h$$</span> with <span class="math-container">\$i = 1, \dots, n \$</span>.</p> <p>Newton-Cotes quadrature formulas implemented in the code:</p> <ul> <li><em>Midpoint</em> rule (constant approx) <span class="math-container">$$F_M = h \sum_{i=1}^n f(x_i)$$</span></li> <li><em>Trapezoidal</em> rule (linear approx) <span class="math-container">$$F_T = \frac{h}{2} \left(f(a) + f(b) \right) + h \sum_{i=1}^{n-1} f(a_i)$$</span></li> <li><em>Simpson's</em> rule (quadratic approx) <span class="math-container">$$F_S = \frac{h}{6} \left(f(a) + f(b) \right) + \frac{h}{3} \sum_{i=1}^{n-1} f(a_i) + 2 \frac{h}{3} \sum_{i=1}^{n} f(x_i) $$</span></li> </ul> <p>I decided to go with a parametrized factory pattern that has no subclasses involved.</p> <p>I employ <span class="math-container">\$ f(x) = \sqrt{x} \exp{(-x)} \$</span> as test function, to be integrated between <span class="math-container">\$a = 1 \$</span> and <span class="math-container">\$b = 3\$</span>.</p> <p>I wonder whether the <code>#include &quot;NewtonCotesFormulas.cpp&quot;</code> at the end of the <code>NewtonCotesFormulas.h</code> header file could be somehow avoided. I used it because without I'd get linking errors.</p> <p>Here is the code.</p> <p><em>main.cpp</em>:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; #include &quot;NewtonCotesFormulas.h&quot; #include &quot;NewtonCotesFactory.h&quot; using namespace std; double func(double x) { return sqrt(x) * exp(-x); } int main() { cout &lt;&lt; &quot;Choose method:\n&quot; &lt;&lt; &quot;Midpoint numeric quadrature -----&gt; (1)\n&quot; &lt;&lt; &quot;Trapezoidal numeric quadrature --&gt; (2)\n&quot; &lt;&lt; &quot;Simpson's numeric quadrature ----&gt; (3)\n&quot; &lt;&lt; endl; // //user input code: // int choice; // cin &gt;&gt; choice; // while (choice &lt; 1 || choice &gt; 3) { // cout &lt;&lt; &quot;Pick again a number from 1 to 3\n&quot;; // cin &gt;&gt; choice; // } NewtonCotesFactory creator; // alternative to user input, print all results at once: for (int choice : {1,2,3}) { NewtonCotesFormulas* rule = creator.createQuadrature(choice, 1, 3, 0.000001); double result = rule-&gt;printConvergenceValues(4, &amp;func); cout &lt;&lt; &quot;Final result within tolerance: &quot; &lt;&lt; result &lt;&lt; endl &lt;&lt; endl; delete rule; } return 0; } </code></pre> <p><em>NewtonCotesFormulas.h</em>:</p> <pre><code>#ifndef NEWTONCOTESFORMULAS_H_INCLUDED #define NEWTONCOTESFORMULAS_H_INCLUDED #include &lt;string&gt; class NewtonCotesFormulas { public: NewtonCotesFormulas(double, double, double, std::string); virtual ~NewtonCotesFormulas(); virtual double computeIntegral(int, double (*func)(double)) = 0; double convergeToTol(int, double (*func)(double)); double printConvergenceValues(int, double (*func)(double)); protected: double inf, sup; double tol; std::string method_name; }; class Midpoint: public NewtonCotesFormulas { public: Midpoint(double, double, double); ~Midpoint(){}; double computeIntegral(int, double (*func)(double)) override; }; class Trapezoidal: public NewtonCotesFormulas { public: Trapezoidal(double, double, double); ~Trapezoidal(){}; double computeIntegral(int, double (*func)(double)) override; }; class Simpsons: public NewtonCotesFormulas { public: Simpsons(double, double, double); ~Simpsons(){}; double computeIntegral(int, double (*func)(double)) override; }; #include &quot;NewtonCotesFormulas.cpp&quot; #endif // NEWTONCOTESFORMULAS_H_INCLUDED </code></pre> <p><em>NewtonCotesFormulas.cpp</em>:</p> <pre><code>#include &lt;iomanip&gt; #include &quot;NewtonCotesFormulas.h&quot; using namespace std; NewtonCotesFormulas::NewtonCotesFormulas(double a, double b, double inp_tol, string name): inf(a), sup(b), tol(inp_tol), method_name(name) {} NewtonCotesFormulas::~NewtonCotesFormulas() {} double NewtonCotesFormulas::convergeToTol(int intervals, double (*func)(double)) { double old_integral = this-&gt;computeIntegral(intervals, func); intervals *= 2; double new_integral = this-&gt;computeIntegral(intervals, func); double difference = abs(new_integral - old_integral); while(difference &gt; tol) { cout &lt;&lt; setprecision(8) &lt;&lt; string(9 - to_string(intervals).size(), ' ') &lt;&lt; // blank padding used to format output table intervals &lt;&lt; string(3,' ') &lt;&lt; fixed &lt;&lt; new_integral &lt;&lt; string(3,' ') &lt;&lt; scientific &lt;&lt; difference &lt;&lt; endl; old_integral = new_integral; intervals *= 2; new_integral = this-&gt;computeIntegral(intervals, func); difference = abs(new_integral - old_integral); } cout &lt;&lt; setprecision(8) &lt;&lt; fixed &lt;&lt; string(9 - to_string(intervals).size(), ' ') &lt;&lt; intervals &lt;&lt; string(3,' ') &lt;&lt; new_integral &lt;&lt; string(3,' ') &lt;&lt; scientific &lt;&lt; difference &lt;&lt; endl; return new_integral; } double NewtonCotesFormulas::printConvergenceValues(int intervals, double (*func)(double)) { cout &lt;&lt; method_name &lt;&lt; &quot; method, with tolerance &quot; &lt;&lt; tol &lt;&lt; &quot;\n&quot;; cout &lt;&lt; &quot;intervals&quot; &lt;&lt; string(5,' ') &lt;&lt; &quot;integral &quot; &lt;&lt; string(9,' ') &lt;&lt; &quot;tol\n&quot;; cout &lt;&lt; setprecision(8) &lt;&lt; string(9 - to_string(intervals).size(), ' ') &lt;&lt; intervals &lt;&lt; string(3,' ') &lt;&lt; this-&gt;computeIntegral(intervals, func) &lt;&lt; string(3,' ') &lt;&lt; fixed &lt;&lt; 0.0 &lt;&lt; endl; double result = this-&gt;convergeToTol(intervals, func); return result; } Midpoint::Midpoint(double a, double b, double inp_tol): NewtonCotesFormulas(a, b, inp_tol, &quot;Midpoint&quot;){} Trapezoidal::Trapezoidal(double a, double b, double inp_tol): NewtonCotesFormulas(a, b, inp_tol, &quot;Trapezoidal&quot;){} Simpsons::Simpsons(double a, double b, double inp_tol): NewtonCotesFormulas(a, b, inp_tol, &quot;Simpson's&quot;){} double Midpoint::computeIntegral(int intervals, double (*func)(double)) { double interval_width = (sup - inf) / intervals; double result = 0; for (int i = 1; i &lt;= intervals; ++i) result += func(inf + (i - 0.5) * interval_width); return result * interval_width; } double Trapezoidal::computeIntegral(int intervals, double (*func)(double)) { double interval_width = (sup - inf) / intervals; double result = (func(inf) + func(sup)) / 2.; for (int i = 1; i &lt;= intervals - 1; ++i) result += func(inf + i * interval_width); return result * interval_width; } double Simpsons::computeIntegral(int intervals, double (*func)(double)) { double interval_width = (sup - inf) / intervals; double result = (func(inf) + func(sup)) / 6; for (int i = 1; i &lt;= intervals - 1; ++i) result += func(inf + i * interval_width) / 3 + 2 * func(inf + (i - 0.5) * interval_width) / 3; result += 2 * func(inf + (intervals - 0.5) * interval_width) / 3; return result * interval_width; } </code></pre> <p><em>NewtonCotesFactory.h</em>:</p> <pre><code>#ifndef NEWTONCOTESFACTORY_H_INCLUDED #define NEWTONCOTESFACTORY_H_INCLUDED #include &lt;string&gt; #include &lt;stdexcept&gt; #include &quot;NewtonCotesFormulas.h&quot; class NewtonCotesFactory { // Parametrized factory, no children public: virtual NewtonCotesFormulas* createQuadrature(int choice, double a, double b, double inp_tol) const { if (choice == 1) return new Midpoint(a, b, inp_tol); else if (choice == 2) return new Trapezoidal(a, b, inp_tol); else if (choice == 3) return new Simpsons(a, b, inp_tol); else throw std::runtime_error(&quot;Pick either choice = 1, 2, or 3&quot;); return 0; // never gets here } virtual ~NewtonCotesFactory(){} }; #endif // NEWTONCOTESFACTORY_H_INCLUDED </code></pre> <p>Results look fine:</p> <pre class="lang-none prettyprint-override"><code>Choose method: Midpoint numeric quadrature -----&gt; (1) Trapezoidal numeric quadrature --&gt; (2) Simpson's numeric quadrature ----&gt; (3) Midpoint method, with tolerance 1e-06 intervals integral tol 4 0.40715731 0.00000000 8 0.40807542 9.18106750e-04 16 0.40829709 2.21674991e-04 32 0.40835199 5.49009778e-05 64 0.40836569 1.36924160e-05 128 0.40836911 3.42104469e-06 256 0.40836996 8.55132348e-07 Final result within tolerance: 4.08369962e-01 Trapezoidal method, with tolerance 1.00000000e-06 intervals integral tol 4 4.10757439e-01 0.00000000 8 0.40895737 1.80006398e-03 16 0.40851640 4.40978614e-04 32 0.40840674 1.09651812e-04 64 0.40837937 2.73754169e-05 128 0.40837253 6.84150045e-06 256 0.40837082 1.71022788e-06 512 0.40837039 4.27547766e-07 Final result within tolerance: 4.08370390e-01 Simpson's method, with tolerance 1.00000000e-06 intervals integral tol 4 4.08357353e-01 0.00000000 8 0.40836940 1.20498403e-05 16 0.40837019 7.90455982e-07 Final result within tolerance: 4.08370194e-01 Process returned 0 (0x0) execution time : 0.063 s Press any key to continue. </code></pre>
[]
[ { "body": "<blockquote>\n<p>I wonder whether the #include &quot;NewtonCotesFormulas.cpp&quot; at the end of the NewtonCotesFormulas.h header file could be somehow avoided. I used it because without I'd get linking errors.</p>\n</blockquote>\n<p>Yea, that's simply wrong. You need to give both that CPP file and the <code>main.cpp</code> file to the compiler, so it knows that both are part of the program to build.</p>\n<hr />\n<h1><a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</h1>\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=\"noreferrer\">SF.7</a>.)</p>\n<hr />\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<hr />\n<pre><code>NewtonCotesFormulas* rule = creator.createQuadrature(choice, 1, 3, 0.000001);\n ⋮\ndelete rule;\n</code></pre>\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c149-use-unique_ptr-or-shared_ptr-to-avoid-forgetting-to-delete-objects-created-using-new\" rel=\"noreferrer\">⧺C.149</a> — no naked <code>new</code> or <code>delete</code>.</p>\n<p>You can simply have <code>createQuadrature</code> return a <code>unique_ptr&lt;NewtonCotesFormulas&gt;</code> instead. Use <code>auto</code> when you call it.</p>\n<hr />\n<pre><code>class NewtonCotesFactory { // Parametrized factory, no children\npublic:\n virtual NewtonCotesFormulas* createQuadrature(int choice, double a, double b, double inp_tol) const {\n</code></pre>\n<p>Not only does it not have any derived classes, the comment even says &quot;no children&quot;. So what is the purpose of using <code>virtual</code> on the function?\nThere is no member data at all, so it can be a <code>static</code> member. Actually, why is it even a class? You just need a single stand-alone free function.</p>\n<p>As for the class as-written, <strong>never</strong> write a destructor or other special member function with an empty body. That will stop the compiler from realizing that it is trivial or has the built-in meaning with no changes, and causes it to stop auto-generating some of the other members because now it's &quot;custom&quot;. Use <code>=default</code> instead.</p>\n<hr />\n<p><code>NewtonCotesFormulas::~NewtonCotesFormulas() {}</code><br />\nJust don't define this. The only reason for having it is to make it <code>virtual</code>, but you could have put the definition directly in-line in the header. But as explained above, don't do that for an empty destructor; just write it as <code>=default</code>.</p>\n<p><code>NewtonCotesFormulas(double, double, double, std::string);</code>\nDon't pass the <code>string</code> <strong>by value</strong> !\n(Though, for a constructor with a &quot;sink&quot; parameter, you could use the &quot;sink&quot; idiom but I don't think you were intending to use this. Generally, pass strings as <code>const ... &amp;</code> but it's better to use a <code>string_view</code> for parameters.)</p>\n<hr />\n<p><code>double old_integral = this-&gt;computeIntegral(intervals, func);</code><br />\nDon't write <code>this-&gt;</code> generally to access members. They are in scope. That is not the C++ way.</p>\n<p>Use <code>const</code> whenever you can.</p>\n<hr />\n<h2>good!</h2>\n<p>I see you used <code>override</code> on the derived classes.</p>\n<hr />\n<h1>not &quot;wrong&quot; but...</h1>\n<p>You're limiting the supplied function to being a plain non-member (or static member) function, rather than any kind of callable thing like a lambda.</p>\n<p>And, you are preventing the implementation from inlining the call to the supplied <code>func</code> (in two different ways), which can have a serious effect on performance especially when the function is so simple.</p>\n<p>You might want to look into doing this part better, like how the standard library handles the function passed to <code>sort</code> and everywhere that comparison or callback functions are passed, in a future study session.</p>\n<p>I think the most important thing to master next would be how to work with projects that have more than one CPP file.</p>\n<p>Keep it up!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T07:56:25.090", "Id": "533898", "Score": "1", "body": "Thank you for the exhaustive rundown. I use Codeblocks as IDE, apparently I did not check enough option boxes for the `.cpp` files included: https://stackoverflow.com/questions/5971206/codeblocks-how-to-compile-multiple-source-files\nI should familiarize myself with Makefiles, I don't like Visual Studio because of the bloated size of projects it creates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T08:01:03.243", "Id": "533900", "Score": "0", "body": "Also I should give a look to `string_view`, I am at loss with new content C++17 onward, as https://www.cplusplus.com/reference/ has not been updated since and I like its brevity better than https://en.cppreference.com ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T17:28:25.977", "Id": "534026", "Score": "0", "body": "Re: constructor and pass `string` by value or ref. Perhaps that's what you mean by \"sink\" idiom, but in this particular case, byvalue+move is more appropriate/efficient, cf. [Should I always move on `sink` constructor or setter arguments?](https://stackoverflow.com/q/18673658/6655648)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T17:18:50.500", "Id": "270360", "ParentId": "270354", "Score": "15" } }, { "body": "<h1>Use an <code>enum</code> to give names to choices</h1>\n<p>Consider using an <code>enum</code>, or even better an <a href=\"https://en.cppreference.com/w/cpp/language/enum#Scoped_enumerations\" rel=\"noreferrer\"><code>enum class</code></a>, to enumerate the possible choices for the Newton-Cotes formulas:</p>\n<pre><code>enum class Formula {\n MIDPOINT = 1,\n TRAPEZOIDAL = 2,\n SIMPSONS = 3,\n};\n</code></pre>\n<p>See below for how to use it.</p>\n<h1>Don't use (virtual) classes unnecessarily</h1>\n<p>There is no reason for <code>class NewtonCotesFactory</code> to have virtual functions. Nothing is inheriting from it. In fact, it has no member variables and only a single member function that does anything useful, so it should not be a class to begin with. Just create a stand-alone function:</p>\n<pre><code>std::unique_ptr&lt;NewtonCotesFormula&gt; createQuadrature(Formula choice, ...) {\n switch (choice) {\n case Formulas::MIDPOINT:\n return new Midpoint(a, b, inp_tol);\n case Formulas::TRAPEZOIDAL:\n return new Trapezoidal(a, b, inp_tol);\n case Formulas::SIMPSONS:\n return new Simpsons(a, b, inp_tol);\n }\n}\n</code></pre>\n<p>It's also possible to restructure the other classes to not need virtual functions. The actual <code>computeIntegral()</code> functions don't depend on much, except for the the <code>sup</code> and <code>inf</code> values. Why not pass those as parameters as well? And again you can write them as stand-alone functions:</p>\n<pre><code>template&lt;typename Function&gt;\ndouble Midpoint(double inf, double sup, int intervals, Function func) {\n double interval_width = (sup - inf) / intervals;\n double result = 0;\n\n for (int i = 0; i &lt; intervals; ++i)\n result += func(inf + (i + 0.5) * interval_width);\n\n return result * interval_width;\n}\n</code></pre>\n<p>Since you are passing functions to other functions already: you can pass both the function you wish to integrate over and the quadrature function to <code>convergeToTol()</code>:</p>\n<pre><code>template&lt;typename Function, function Quadrature&gt;\ndouble convergeToTol(double inf, double sup, int intervals, double tol, Function func, Quadrature computeIntegral) {\n ...\n while (difference &gt; tol) {\n ...\n new_integral = computeIntegral(inf, sup, intervals, func);\n ...\n }\n ...\n}\n</code></pre>\n<p>Now that functions are no longer in classes, the question is how <code>createQuadrature()</code> should be rewritten. One way is to use <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function\" rel=\"noreferrer\"><code>std::function</code></a> to be able to <code>return</code> a function:</p>\n<pre><code>std::function&lt;double(double, double, int, std::function&lt;double(double)&gt;)&gt;\ncreateQuadrature(Formula choice) {\n switch (choice) {\n case Formulas::MIDPOINT:\n return Midpoint&lt;std::function&lt;double(double)&gt;&gt;;\n case Formulas::TRAPEZOIDAL:\n return Trapezoidal&lt;std::function&lt;double(double)&gt;&gt;;\n case Formulas::SIMPSONS:\n return Simpsons&lt;std::function&lt;double(double)&gt;&gt;;\n }\n}\n</code></pre>\n<p>The above is now more in a functional programming style, which I think is more appropriate for the problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T08:05:38.923", "Id": "533902", "Score": "0", "body": "Great tips as always. I wrote a class hierarchy for the `Factory` method, then realised was overkill but forgot to take away the `virtual` moniker." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T08:18:04.660", "Id": "533904", "Score": "0", "body": "I used a function pointer, thought about using a functor, but I looked up this `std::function()` feature and I agree is much more elegant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T03:13:42.713", "Id": "534197", "Score": "0", "body": "@G-Sliepen in case you are curious I have implemented your suggestions in my own answer below" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T18:47:55.837", "Id": "270364", "ParentId": "270354", "Score": "11" } }, { "body": "<h3>Prefer Composition to Inheritance</h3>\n<p>Currently, you have objects that store and hide the interval you’re integrating over, the tolerance, and the method of integration. Each class has a different virtual method that you pass a number of intervals and a C-style pointer to the function to be integrated. The basic idea of a object defining a type of integration method, which you can re-use or store, is sound. (Although you could overload a non-member integration function to take its data members as arguments.)</p>\n<p>This won’t work well for an application where you want to try integrating the same function using different methods and tolerances. You really have two somewhat orthogonal parts to the integral: the function you want to integrate plus the interval over which you want to integrate it, and the method you want to use to integrate it, along with its parameters.</p>\n<p>Client code should create or receive these two things separately, and compose them together with a function call equivalent to, “Integrate f from a to b, by whatever method this object represents.” You don’t want your API to have to specify and pass along a number-of-intervals parameter separately. Among other problems, that limits the API to only ever handle regular partitions.</p>\n<p>You also shouldn’t encapsulate elements of what you’re integrating, like the limits of integration, along with elements of the numeric method for integrating it, such as <code>inp_tol</code>, if you want to be able to either integrate a function over different intervals with the same method, or a function over the same interval with several different methods.</p>\n<p>The basic idea of having different <code>Simpsons</code>, <code>Trapezoidal</code> and <code>Midpoint</code> methods seems sound, but in that case, the instances should encapsulate <code>n</code> and <code>inp_tol</code>.</p>\n<p>You might also think it worthwhile to have a <code>DefiniteIntegral</code> class that encapsulates the function to be integrated along with the limits of integration. At that point, your API could support any or all of the following ways to compose your two orthogonal objects:</p>\n<ul>\n<li><code>integrationMethod.computeIntegral(f, a, b);</code></li>\n<li><code>f_a_to_b.computeIntegral(integrationMethod);</code></li>\n<li><code>integrationMethod.computeIntegral(f_a_to_b);</code></li>\n</ul>\n<p>If you then want an object, let’s say <code>int_f</code>, that evaluates the integral of <code>f</code> from <code>a</code> to <code>b</code> according to a given method, you can then create one with</p>\n<pre><code>const auto int_f = std::bind_from( &amp;Midpoint::computeIntegral,\n Midpoint( intervals, inp_tol ),\n f );\narea = int_f( a, b );\n</code></pre>\n<h3>Declare Constants Where You Can</h3>\n<p>Numeric integration is a great use case for a pure computation. A function like <code>NewtonCotesFormulas::computeIntegral</code> should be declared <code>constexpr</code> if some integrals can be computed purely at compile time, and <code>const</code> if it does not modify any per-instance data.</p>\n<p>Similarly, you do not want to create a shallow copy of a <code>std::string</code> object that says <code>“midpoint”</code> for every instance, or dynamically allocate a new copy of the string on the heap every time you copy the object. You should actually use <code>typeid</code> to determine the type of these objects at runtime. This will work because they contain at least one <code>virtual</code> function, so a virtual function table will be created for them.</p>\n<p>An alternative to storing any per-instance data at all is to write a <code>virtual</code> function that returns a <code>const</code> reference to a <code>private:</code> <code>static const std::string</code> object. For example,</p>\n<pre><code>// Declared as static in the definition of Midpoint:\nconst std::string Midpoint::method_name = &quot;midpoint&quot;;\n\n// Declared as virtual in the base class: \nconstexpr const std::string&amp; Midpoint::get_methodname() noexcept\n{\n return Midpoint::method_name; // Good practice to specify the namespace when re-using identifiers.\n}\n</code></pre>\n<p>This uses no additional memory (beyond one more pointer in the virtual function table) and runs with zero overhead when the type of the object is known at compile time.</p>\n<p>However, if you do want to have a data member in each instance that contains the name of the method, it should be a pointer to a <code>static</code> string constant. You will never want to customize or modify constants such as <code>&quot;Simpson's&quot;</code> or <code>&quot;trapezoidal&quot;</code>. All copies of the string are then shallow copies, which not only is much more efficient, it allows <code>constexpr</code> instances to exist, potentially allowing the compiler to pre-calculate integrals whose parameters are all compile-time constants, and greatly optimizing your program.</p>\n<h3>Pass the Right Types</h3>\n<p>You should pass the function to be integrated as a <code>std::function</code> object instead of a C-style function pointer. This enables you to use many more types of functions, such as a member call to an object, a lambda expression, or an object such as <code>std::bind( normalDistribution, mean, variance )</code>.</p>\n<p>You pass the number of intervals as an <code>int</code>, which might be zero or negative, then never check that the domain is valid. Since an <code>int</code> is not necessarily 32 bits wide, you might want to declare the type as <code>unsigned long</code> or perhaps <code>std::uint32_t</code> from <code>&lt;cstdint&gt;</code>. Then if you declare what requesting zero intervals means, there would be no possible domain errors Or, if the number of partitions is encapsulated in the integration method, it can be checked and throw an exception when set to an invalid value, and then the critical path that you want to optimize can be guaranteed safe, and declared <code>noexcept</code>.</p>\n<h3>Shut Down the Factory</h3>\n<p>Just use the constructor. The factory pattern would be useful if you want to, for example, create a singleton as needed and return a reference to it. You’re not doing anything like that here, but creating individual instances with their own data.</p>\n<p>Instead of client code writing</p>\n<pre><code>constexpr int QUAD_MIDPOINT = 1;\nNewtonCotesFormulas* const quadrature =\n NewtonCotesFactory::createQuadrature(QUAD_MIDPOINT, a, b, inp_tol );\n</code></pre>\n<p>You can instead write</p>\n<pre><code>const auto&amp; quadrature = Midpoint( a, b, inp_tol );\n</code></pre>\n<p>or, if you need virtual function dispatch,</p>\n<pre><code>const NewtonCotesFormulas&amp; quadrature =\n Midpoint( a, b, inp_tol );\n</code></pre>\n<p>This works fine, because an object of a derived class implicitly converts to a reference to the base class. Access through the reference to an abstract base class will properly dispatch all virtual functions.</p>\n<p>If you decide you do need a factory, it should return either a reference to a static object, such as a singleton—which should never return <code>NULL</code>—or a <code>std::unique_ptr&lt;NewtonCotesFormulas&gt;</code>. (In many use cases, there is a good third option, returning an object that will be created with guaranteed copy elision, but that is not possible here because you want a reference to a pure virtual class.) The smart pointer will automatically free the object it owns, once and only once, when its lifetime expires, and a naked <code>new</code> will not.</p>\n<p>If you do want a factory method that creates an object of a derived class dynamically and returns it as a smart pointer to a base class, which would be useful if you need to store references to the abstract interface in a data structure, a possible implementation would be:</p>\n<pre><code>template&lt;class T, class... Args&gt;\n std::unique_ptr&lt;NewtonCotesFormulas&gt; make_NewtonCotes( Args&amp;&amp;... args )\n {\n return std::unique_ptr&lt;NewtonCotesFormulas&gt;(\n static_cast&lt;NewtonCotesFormulas*&gt;(new T(args...)));\n }\n\nconst auto mid = make_NewtonCotes&lt;Midpoint&gt;( a, b, inp_tol );\nconst double area = mid-&gt;computeIntegral( n, f );\n</code></pre>\n<p>While that sample gives you a <code>std::unique_ptr&lt;NewtonCotesFormulas&gt;</code> object, you can also initialize different kinds of smart pointers from it:</p>\n<pre><code>const std::shared_ptr&lt;NewtonCotesFormulas&gt; shared = make_NewtonCotes&lt;Midpoint&gt;( a, b, inp_tol );\nconst std::unique_ptr&lt;const NewtonCotesFormulas&gt; cmid = make_NewtonCotes&lt;Midpoint&gt;( a, b, inp_tol );\n</code></pre>\n<p>These work for any type of object that can be constructed or implicitly converted from a <code>std::unique_ptr&lt;NewtonCotesMethod&gt;</code>. It would not work for a <code>std::weak_ptr</code>, for example.</p>\n<p>This function template constructs a new object, dynamically, of the class you specify (<code>Midpoint</code>), forwarding the arguments (here, <code>a</code>, <code>b</code> and <code>inp_tol</code>, but any arguments will work) to the constructor of the derived class. If any of them can be moved instead of copied, it will do that. It wraps the created object in a smart pointer to the base class, which will manage its memory automatically. Dereferencing the smart pointer will use virtual function dispatch.</p>\n<p>Since this removes the need for all derived classes to have the same type of constructor—you could call <code>make_NewtonCoates&lt;MethodA&gt;(foo)</code> or <code>make_NewtonCoates&lt;MethodB&gt;(foo, bar, baz)</code>—this probably removes any need for the abstract base class to specify any data members. Each daughter class can define whatever ones it needs.</p>\n<h3>Consider Wrapping Your Library in a Namespace</h3>\n<p>If you declare all identifiers in <code>namespace NumericIntegration</code> and then <code>using namespace NumericIntegration</code>, you’ll get the best of both worlds: the namespace is completely transparent to your clients, but if there is, unlikely as it might seem, another library that declares an identifier with the same name, you can still link your program, and write <code>NumericIntegration::foo</code> to disambiguate as needed.</p>\n<h3>Listen to the Other Answers Too</h3>\n<p>Don’t <code>#include</code> a <code>.cpp</code> file, avoid <code>using namespace std;</code> use the <code>default</code> constructors and destructors instead of empty braes, and so on. I won’t repeat all of that here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T17:03:04.997", "Id": "534024", "Score": "1", "body": "This takes the initial code to production level quality. In your last snippet of code, I like the way you propose for the factory to select for subclasses using general programming. In fact, the `if ... else if` statement I did use is taken verbatim from the Gang of four 1994 book, or at least from what I can remember of it. \nTo obviate the issue with `std::string` parameter to the `NewtonCotesFormula` constructor, can't I just turn it into a `const std::string&` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T03:14:10.710", "Id": "534054", "Score": "1", "body": "@Giogre You actually don’t need to store any per-instance data at all. Write a `virtual` member function that returns the method name as a `const std::string&`. Have the implementation return a reference to a `private:`, `static const std::string`. the function can also be `constexpr` and `noexcept`,." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T03:36:49.763", "Id": "534056", "Score": "1", "body": "@Giogre Thanks for reminding me about the `make_NewtonCotes` code sample. I just noticed and removed an unnecessary reference operator in it. We want a smart-pointer object, not a reference to one. Whoops!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T02:26:26.507", "Id": "270401", "ParentId": "270354", "Score": "1" } }, { "body": "<p>I have adapted my code in the original question to accommodate for the more functional approach suggested by @G-Sliepen in his answer.</p>\n<p>Also a timing subroutine was added here and to the old OOP code, in order to compare performances.</p>\n<p>Functional version of code implementing Newton-Cotes quadrature formulas:</p>\n<p><em>main.cpp</em>:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;cmath&gt;\n#include &lt;cctype&gt;\n#include &lt;functional&gt;\n#include &lt;chrono&gt;\n#include &quot;NewtonCotesFormulas.h&quot;\n\nusing std::cin; using std::cout;\nusing std::pow; using std::function;\nusing std::exp;\nnamespace chrono = std::chrono;\n\n// helps with input\nvoid flushCin() {\n cin.clear();\n cin.ignore();\n}\n\n// timer\nunsigned int stopwatch()\n{\n static auto start_time = chrono::steady_clock::now();\n\n auto end_time = chrono::steady_clock::now();\n auto delta = chrono::duration_cast&lt;chrono::microseconds&gt;(end_time - start_time);\n\n start_time = end_time;\n\n return delta.count();\n}\n\n// use a functor this time\nstruct func {\n double operator()(double x) {\n return sqrt(x) * exp(-x);\n }\n};\n//double func(double x) {\n// return sqrt(x) * exp(-x);\n//}\n\nint main() {\n cout &lt;&lt; &quot;Choose method:\\n&quot;\n &lt;&lt; &quot;Midpoint numeric quadrature -----&gt; (1)\\n&quot;\n &lt;&lt; &quot;Trapezoidal numeric quadrature --&gt; (2)\\n&quot;\n &lt;&lt; &quot;Simpson's numeric quadrature ----&gt; (3)\\n\\n&quot;;\n\n // user picks a quadrature method\n// int choice_int;\n// cin &gt;&gt; choice_int;\n// while (choice_int &lt; 1 || choice_int &gt; 3) {\n// flushCin();\n// cout &lt;&lt; &quot;Pick again a number from 1 to 3\\n&quot;;\n// cin &gt;&gt; choice_int;\n// }\n// Formula choice = static_cast&lt;Formula&gt;(choice_int);\n\n // cycle through all quadrature formulas\n stopwatch();\n for (Formula choice : {Formula::Midpoint, Formula::Trapezoidal, Formula::Simpsons}) {\n double result = printConvergenceValues(choice, 1, 3, 4, 0.000001, func() );\n // above parameters:choice, inf, sup, intervals, tol, func\n cout &lt;&lt; &quot;Final result within tolerance: &quot; &lt;&lt; result &lt;&lt; &quot;\\n\\n&quot;;\n }\n cout &lt;&lt; &quot;Performance time: &quot; &lt;&lt; stopwatch() &lt;&lt; &quot; microseconds.\\n\\n&quot;;\n\n return 0;\n}\n</code></pre>\n<p><em>NewtonCotesFormulas.h</em>:</p>\n<pre><code>#ifndef NEWTONCOTESFORMULAS_H_INCLUDED\n#define NEWTONCOTESFORMULAS_H_INCLUDED\n\n#include &lt;iostream&gt;\n#include &lt;functional&gt;\n\nenum class Formula {\n Midpoint = 1,\n Trapezoidal,\n Simpsons\n};\n\nstd::ostream&amp; operator&lt;&lt; (std::ostream&amp;, const Formula&amp;);\n\ntemplate&lt;typename Function, typename Quadrature&gt;\ndouble convergeToTol(const double, const double, int, const double, const Function&amp;, const Quadrature&amp;);\n\ntemplate&lt;typename Function&gt;\ndouble printConvergenceValues(const Formula&amp;, const double, const double, const int, const double, const Function&amp;);\n\ntemplate&lt;typename Function&gt; double Midpoint(const double, const double, const int, const Function&amp;);\n\ntemplate&lt;typename Function&gt; double Trapezoidal(const double, const double, const int, const Function&amp;);\n\ntemplate&lt;typename Function&gt; double Simpsons(const double, const double, const int, const Function&amp;);\n\nstd::function&lt;double (double, double, int, std::function&lt;double (double) &gt;) &gt;\ncreateQuadrature(const Formula&amp;);\n\n#include &quot;NewtonCotesFormulas.cpp&quot;\n#endif // NEWTONCOTESFORMULAS_H_INCLUDED\n</code></pre>\n<p><em>NewtonCotesFormulas.cpp</em>:</p>\n<pre><code>#include &lt;iomanip&gt;\n#include &lt;string&gt;\n#include &lt;cmath&gt;\n#include &lt;stdexcept&gt;\n#include &quot;NewtonCotesFormulas.h&quot;\n\nusing std::string; using std::cout;\nusing std::setprecision; using std::fixed;\nusing std::scientific; using std::to_string;\nusing std::abs; using std::function;\nusing std::runtime_error; using std::ostream;\n\n// this prints the enum on cout\nostream&amp; operator&lt;&lt; (ostream&amp; os, const Formula&amp; method) {\n if (method == Formula::Midpoint)\n os &lt;&lt; &quot;Midpoint&quot;;\n else if (method == Formula::Trapezoidal)\n os &lt;&lt; &quot;Trapezoidal&quot;;\n else if (method == Formula::Simpsons)\n os &lt;&lt; &quot;Simpsons&quot;;\n\n return os;\n}\n\ntemplate&lt;typename Function, typename Quadrature&gt;\ndouble convergeToTol(const double inf, const double sup, int intervals, const double tol,\n const Function&amp; func, const Quadrature&amp; my_method) {\n double old_integral = my_method(inf, sup, intervals, func);\n intervals *= 2;\n double new_integral = my_method(inf, sup, intervals, func);\n double difference = abs(new_integral - old_integral);\n\n cout.setf(ios_base::scientific);\n cout.precision(8);\n while(difference &gt; tol) {\n cout &lt;&lt; string(9 - to_string(intervals).size(), ' ') &lt;&lt; intervals &lt;&lt;\n string(3,' ') &lt;&lt; fixed &lt;&lt; new_integral &lt;&lt; string(3,' ') &lt;&lt;\n scientific &lt;&lt; difference &lt;&lt; '\\n';\n old_integral = new_integral;\n intervals *= 2;\n new_integral = my_method(inf, sup, intervals, func);\n difference = abs(new_integral - old_integral);\n }\n cout &lt;&lt; fixed &lt;&lt; string(9 - to_string(intervals).size(), ' ') &lt;&lt;\n intervals &lt;&lt; string(3,' ') &lt;&lt; new_integral &lt;&lt; string(3,' ') &lt;&lt;\n scientific &lt;&lt; difference &lt;&lt; '\\n';\n\n return new_integral;\n}\n\ntemplate&lt;typename Function&gt;\ndouble printConvergenceValues(const Formula&amp; choice, const double inf, const double sup, \n const int intervals, const double tol, const Function&amp; func)\n{\n function&lt;double (double, double, int, function&lt;double (double) &gt;) &gt;\n my_method = createQuadrature(choice);\n\n cout &lt;&lt; choice &lt;&lt; &quot; method, with tolerance &quot; &lt;&lt; tol &lt;&lt; &quot;\\n&quot;;\n cout &lt;&lt; &quot;intervals&quot; &lt;&lt; string(5,' ') &lt;&lt; &quot;integral &quot; &lt;&lt; string(9,' ') &lt;&lt; &quot;tol\\n&quot;;\n cout &lt;&lt; setprecision(8) &lt;&lt; fixed &lt;&lt; string(9 - to_string(intervals).size(), ' ') &lt;&lt;\n intervals &lt;&lt; string(3,' ') &lt;&lt; my_method(inf, sup, intervals, func) &lt;&lt;\n string(3,' ') &lt;&lt; 0.0 &lt;&lt; '\\n';\n\n double result = convergeToTol(inf, sup, intervals, tol, func, my_method);\n\n return result;\n}\n\ntemplate &lt;typename Function&gt;\ndouble Midpoint(const double inf, const double sup, const int intervals, const Function&amp; func) {\n double interval_width = (sup - inf) / intervals;\n double result = 0;\n for (int i = 1; i &lt;= intervals; ++i)\n result += func(inf + (i - 0.5) * interval_width);\n\n return result * interval_width;\n}\n\ntemplate &lt;typename Function&gt;\ndouble Trapezoidal(const double inf, const double sup, const int intervals, const Function&amp; func) {\n double interval_width = (sup - inf) / intervals;\n double result = (func(inf) + func(sup)) / 2.;\n for (int i = 1; i &lt;= intervals - 1; ++i)\n result += func(inf + i * interval_width);\n\n return result * interval_width;\n}\n\ntemplate &lt;typename Function&gt;\ndouble Simpsons(const double inf, const double sup, const int intervals, const Function&amp; func) {\n double interval_width = (sup - inf) / intervals;\n double result = (func(inf) + func(sup)) / 6;\n for (int i = 1; i &lt;= intervals - 1; ++i)\n result += func(inf + i * interval_width) / 3 + 2 * func(inf + (i - 0.5) * interval_width) / 3;\n result += 2 * func(inf + (intervals - 0.5) * interval_width) / 3;\n\n return result * interval_width;\n}\n\nfunction&lt;double (double, double, int, function&lt;double (double) &gt;) &gt;\ncreateQuadrature(const Formula&amp; choice) {\n if (choice == Formula::Midpoint)\n return Midpoint&lt;function&lt;double (double)&gt; &gt;;\n else if (choice == Formula::Trapezoidal)\n return Trapezoidal&lt;function&lt;double (double)&gt;&gt;;\n else if (choice == Formula::Simpsons)\n return Simpsons&lt;function&lt;double (double)&gt;&gt;;\n else\n throw runtime_error(&quot;Pick between choice = 1, 2, or 3&quot;);\n\n return 0; // never gets here\n}\n</code></pre>\n<p>Numerical results are obviously identical among the two versions.\nPerformances are as following:</p>\n<ul>\n<li><p>Old OO code:</p>\n<pre><code> Performance time: 23375 microseconds.\n</code></pre>\n</li>\n<li><p>Functional approach, code above:</p>\n<pre><code> Performance time: 22211 microseconds.\n</code></pre>\n</li>\n</ul>\n<p>I'd say performances are similar. I suppose the introduction of templates balances out the removal of virtual calls, in terms of slowing down computational times?</p>\n<p>The functional approach is surely more elegant, but also a bit more complicate to write, and read as well. Or perhaps it's just me not being overly familiar with functional programming.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T03:07:11.490", "Id": "270480", "ParentId": "270354", "Score": "0" } } ]
{ "AcceptedAnswerId": "270360", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T15:31:06.550", "Id": "270354", "Score": "14", "Tags": [ "c++", "object-oriented", "numerical-methods", "factory-method" ], "Title": "Numerical integration in C++: Newton-Cotes formulas" }
270354
<p>My Data consists of rows containing a Length/Duration in Minutes, a Begin &amp; EndTime. The precision is 1min (or larger).</p> <p>the table looks something like that:</p> <pre><code>CREATE TABLE public.&quot;TimeSeries&quot; ( &quot;Id&quot; uuid NOT NULL, &quot;BeginTime&quot; timestamptz NOT NULL, &quot;EndTime&quot; timestamptz NOT NULL DEFAULT '0001-01-01 00:00:00' :: timestamp without time zone, &quot;LengthMin&quot; int4 NOT NULL ); INSERT INTO public.&quot;TimeSeries&quot; (&quot;Id&quot;,&quot;BeginTime&quot;,&quot;LengthMin&quot;,&quot;EndTime&quot;) VALUES ('ecabcd8d-3129-4128-b126-a4e1abcd49c9'::uuid,'2021-11-16 11:45:00.000',1,'2021-11-16 11:46:00.000'), ('e5abcd70-5125-412b-9128-93ecabcdcba9'::uuid,'2021-11-16 11:46:00.000',1,'2021-11-16 11:47:00.000'), ('03abcdb8-8129-4124-b126-f5bbabcd7157'::uuid,'2021-11-16 11:47:00.000',1,'2021-11-16 11:48:00.000'), ('54abcdcc-6129-4126-912b-34b2abcde19a'::uuid,'2021-11-16 11:50:00.000',1,'2021-11-16 11:51:00.000'), ('77abcd28-212f-4122-912f-5060abcd2aa0'::uuid,'2021-11-16 11:51:00.000',1,'2021-11-16 11:52:00.000'), ('8babcdd1-f12a-4124-9128-2529abcda136'::uuid,'2021-11-16 11:52:00.000',1,'2021-11-16 11:53:00.000'), ('8aabcd94-9129-4121-b12c-1ebfabcd06b8'::uuid,'2021-11-16 12:35:00.000',1,'2021-11-16 12:36:00.000'), ('96abcd04-b12e-4122-b12b-4dc2abcdcee4'::uuid,'2021-11-16 12:40:00.000',1,'2021-11-16 12:41:00.000'), ('42abcd4a-f129-412c-9124-41b3abcd3ca3'::uuid,'2021-11-16 12:44:00.000',1,'2021-11-16 12:45:00.000'), ('beabcd8f-c12f-4126-a12b-0a37abcdd0bb'::uuid,'2021-11-16 12:49:00.000',1,'2021-11-16 12:50:00.000'), ('b8abcd79-d12c-4120-912f-754fabcdd220'::uuid,'2021-11-16 12:50:00.000',1,'2021-11-16 12:51:00.000'), ('c3abcd08-e121-4127-b125-4e70abcd5756'::uuid,'2021-11-16 12:59:00.000',1,'2021-11-16 13:00:00.000'), ('65abcdbe-7121-412a-a12c-1f68abcd94eb'::uuid,'2021-11-16 13:00:00.000',1,'2021-11-16 13:01:00.000'), ('f5abcd38-9122-412c-b12f-957fabcd79b5'::uuid,'2021-11-16 13:05:00.000',1,'2021-11-16 13:06:00.000'); </code></pre> <p>The code I came up with looks something like that: ( <a href="http://www.sqlfiddle.com/#!17/8a517/2" rel="nofollow noreferrer">http://www.sqlfiddle.com/#!17/8a517/2</a> )</p> <pre><code>SELECT u.&quot;SeriesBegin&quot;, COUNT(u.&quot;BeginTime&quot;) as cnt, min(u.&quot;BeginTime&quot;) as min, max(u.&quot;EndTime&quot;) as max, max(u.&quot;EndTime&quot;) - min(u.&quot;BeginTime&quot;) as delta FROM ( SELECT v.&quot;BeginTime&quot;, v.&quot;EndTime&quot;, v.&quot;isInSeries&quot;, v.&quot;n_in_series&quot;, lag(&quot;BeginTime&quot;, v.&quot;n_in_series&quot; :: int) OVER ( ORDER BY &quot;BeginTime&quot; ) AS &quot;SeriesBegin&quot;, grp FROM ( SELECT t.*, row_number() OVER ( partition BY t.&quot;BeginTime&quot; - grp * make_interval(mins =&gt; t.&quot;LengthMin&quot;) ORDER BY t.&quot;BeginTime&quot; ) - 1 as n_in_series FROM ( SELECT row_number() OVER ( ORDER BY &quot;BeginTime&quot; ) AS grp, &quot;BeginTime&quot; = lag(&quot;EndTime&quot;) OVER ( ORDER BY &quot;BeginTime&quot; ) AS &quot;isInSeries&quot;, * FROM &quot;TimeSeries&quot; WHERE &quot;LengthMin&quot; = 1 ) t ORDER BY t.&quot;BeginTime&quot; ) AS v ) u GROUP BY &quot;SeriesBegin&quot; ORDER BY &quot;SeriesBegin&quot; ASC </code></pre> <p>The result:</p> <pre><code> | SeriesBegin | cnt | min | max | delta | |----------------------|-----|----------------------|----------------------|------------------------------------------------| | 2021-11-16T11:45:00Z | 3 | 2021-11-16T11:45:00Z | 2021-11-16T11:48:00Z | 0 years 0 mons 0 days 0 hours 3 mins 0.00 secs | | 2021-11-16T11:50:00Z | 3 | 2021-11-16T11:50:00Z | 2021-11-16T11:53:00Z | 0 years 0 mons 0 days 0 hours 3 mins 0.00 secs | | 2021-11-16T12:35:00Z | 1 | 2021-11-16T12:35:00Z | 2021-11-16T12:36:00Z | 0 years 0 mons 0 days 0 hours 1 mins 0.00 secs | | 2021-11-16T12:40:00Z | 1 | 2021-11-16T12:40:00Z | 2021-11-16T12:41:00Z | 0 years 0 mons 0 days 0 hours 1 mins 0.00 secs | | 2021-11-16T12:44:00Z | 1 | 2021-11-16T12:44:00Z | 2021-11-16T12:45:00Z | 0 years 0 mons 0 days 0 hours 1 mins 0.00 secs | | 2021-11-16T12:49:00Z | 2 | 2021-11-16T12:49:00Z | 2021-11-16T12:51:00Z | 0 years 0 mons 0 days 0 hours 2 mins 0.00 secs | | 2021-11-16T12:59:00Z | 2 | 2021-11-16T12:59:00Z | 2021-11-16T13:01:00Z | 0 years 0 mons 0 days 0 hours 2 mins 0.00 secs | | 2021-11-16T13:05:00Z | 1 | 2021-11-16T13:05:00Z | 2021-11-16T13:06:00Z | 0 years 0 mons 0 days 0 hours 1 mins 0.00 secs | </code></pre> <p>I think this code can be optimized, on one hand 4 SELECT statements seem pretty much for me. On the other hand currently there are 2 approaches included, however one only active.</p> <p>The Approach I like more is checking if the <code>BeginTime = lag(EndTime)</code> however then I was not able to connect rows which are in the same series.</p> <p>The active approach is calculating some common value <code>t.&quot;BeginTime&quot; - grp * make_interval(mins =&gt; t.&quot;LengthMin&quot;)</code> and mapping them via the calculated position in the series <code>n_in_series</code> &amp; <code>lag(&quot;BeginTime&quot;, v.&quot;n_in_series&quot; :: int)</code> to a group.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T16:51:29.997", "Id": "533877", "Score": "2", "body": "Thanks for this great question - particularly for including your table definitions, which many new users overlook. I hope you get some good reviews, and I hope to see more of your contributions here in future!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T21:04:54.783", "Id": "533882", "Score": "0", "body": "@TobySpeight thanks for your comment. I think in SQL there is always some possibility for improvements in readability and also in performance, therefore this topic gives good questions :) I'm always annoyed when there is missing info, thus I included the fiddle too" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T14:15:38.203", "Id": "533916", "Score": "0", "body": "What version of PostgreSQL? Your Fiddle uses 9.6 but that's very old at this point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T22:02:26.467", "Id": "533939", "Score": "0", "body": "@Reinderien I'm currently using v13, however I will upgrade to v14 as it is available via the zalan.do k8s operator - are there any new features which would help me in this case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T22:12:07.180", "Id": "533941", "Score": "1", "body": "Probably nothing specific, but you should replace sqlfiddle with dbfiddle as the latter offers your specific version and the former doesn't." } ]
[ { "body": "<p>It's unwise to have a <code>LengthMin</code> in your table - this is redundant, and can be found as the difference between the begin and end time fields.</p>\n<p>None of your column or table names need quoting, and in most cases you also don't need to prefix the <code>public.</code> namespace.</p>\n<p><code>timestamptz</code> is a non-standard abbreviation for <code>timestamp with time zone</code>; prefer standards when you can - and PostgreSQL is uniquely very, very good at supporting standards compared to the other databases.</p>\n<p>In your insert, you don't need explicit <code>uuid</code> casts, and you don't need to include second and millisecond fields in your times.</p>\n<p>You have a mix of uppercase and lowercase keywords. Most people prefer uppercase; I prefer lowercase and (just like every other language we write in) use syntax highlighting rather than SHOUTING to make it clear where the keywords are. Also, internally PostgreSQL lowercase-folds everything anyway.</p>\n<p>You also have many different capitalization styles for your own names - <code>BeginTime</code>, <code>isInSeries</code> and <code>n_in_series</code> being UpperCamelCase, lowerCamelCase and lower_snake_case respectively. Best to choose one style and be consistent.</p>\n<p>I don't have much to say about the content of the query, other than - it's good that you've used subqueries instead of CTEs, as the latter impose an optimization boundary.</p>\n<h2>Suggested</h2>\n<pre><code>create table TimeSeries (\n Id uuid not null,\n BeginTime timestamp with time zone not null,\n EndTime timestamp with time zone not null\n);\n\ninsert into TimeSeries(Id, BeginTime, EndTime) values\n ('ecabcd8d-3129-4128-b126-a4e1abcd49c9', '2021-11-16 11:45', '2021-11-16 11:46'),\n ('e5abcd70-5125-412b-9128-93ecabcdcba9', '2021-11-16 11:46', '2021-11-16 11:47'),\n ('03abcdb8-8129-4124-b126-f5bbabcd7157', '2021-11-16 11:47', '2021-11-16 11:48'),\n ('54abcdcc-6129-4126-912b-34b2abcde19a', '2021-11-16 11:50', '2021-11-16 11:51'),\n ('77abcd28-212f-4122-912f-5060abcd2aa0', '2021-11-16 11:51', '2021-11-16 11:52'),\n ('8babcdd1-f12a-4124-9128-2529abcda136', '2021-11-16 11:52', '2021-11-16 11:53'),\n ('8aabcd94-9129-4121-b12c-1ebfabcd06b8', '2021-11-16 12:35', '2021-11-16 12:36'),\n ('96abcd04-b12e-4122-b12b-4dc2abcdcee4', '2021-11-16 12:40', '2021-11-16 12:41'),\n ('42abcd4a-f129-412c-9124-41b3abcd3ca3', '2021-11-16 12:44', '2021-11-16 12:45'),\n ('beabcd8f-c12f-4126-a12b-0a37abcdd0bb', '2021-11-16 12:49', '2021-11-16 12:50'),\n ('b8abcd79-d12c-4120-912f-754fabcdd220', '2021-11-16 12:50', '2021-11-16 12:51'),\n ('c3abcd08-e121-4127-b125-4e70abcd5756', '2021-11-16 12:59', '2021-11-16 13:00'),\n ('65abcdbe-7121-412a-a12c-1f68abcd94eb', '2021-11-16 13:00', '2021-11-16 13:01'),\n ('f5abcd38-9122-412c-b12f-957fabcd79b5', '2021-11-16 13:05', '2021-11-16 13:06');\n\n\nselect\n u.SeriesBegin,\n count(u.BeginTime) as cnt,\n min(u.BeginTime) as min,\n max(u.EndTime) as max,\n max(u.EndTime) - min(u.BeginTime) as delta\nfrom (\n select\n v.BeginTime,\n v.EndTime,\n v.isInSeries,\n v.n_in_series,\n lag(BeginTime, v.n_in_series::int) over (order by BeginTime) as SeriesBegin,\n grp\n from (\n select\n t.*,\n row_number() over (\n partition by t.BeginTime - grp*make_interval(mins =&gt; t.LengthMin)\n order by t.BeginTime\n ) - 1 as n_in_series\n from\n (\n select\n row_number() over (order by BeginTime) as grp,\n BeginTime = lag(EndTime) over (order by BeginTime) as isInSeries,\n *\n from (\n select *,\n (extract(epoch from EndTime - BeginTime)/60)::int as LengthMin\n from TimeSeries\n ) as s\n where LengthMin = 1\n ) t\n order by t.BeginTime\n ) as v\n) as u\ngroup by SeriesBegin\norder by SeriesBegin asc;\n</code></pre>\n<p><a href=\"https://dbfiddle.uk/?rdbms=postgres_14&amp;fiddle=f3c2228c4fafac88ffd33de00c07d2c0\" rel=\"nofollow noreferrer\">https://dbfiddle.uk/?rdbms=postgres_14&amp;fiddle=f3c2228c4fafac88ffd33de00c07d2c0</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T22:14:28.087", "Id": "533943", "Score": "0", "body": "Thank you for your answer. In short: I agree on everything. Long: 1. I using LengthMin to filter my data, but I agree, one of the 3 columns is too much. 2. I have to quote the column and table names since they are in Pascalcase in the DB - thanks to EFcore (I did not check if this is configurable). 3. this is one of the reasons why I switched to postgresl 4. about the data, I just exported it from dBeaver, but for positing in the future I will keep this in mind, to clean everything up. 5. this is a general problem I have when always switching languages" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T15:09:10.663", "Id": "270385", "ParentId": "270358", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T15:46:31.250", "Id": "270358", "Score": "2", "Tags": [ "sql", "datetime", "postgresql", "interval" ], "Title": "Find coherent datetime ranges in postgresql" }
270358
<p>I'm learning Objects calisthenics and I was practicing with the typical Tic Tac Toe game, I was wondering if you could gimme feedback about my mistakes (Algorithmic problems, logic, and especially OOP following Objects calisthenics rules). Thanks in advance!</p> <ul> <li>Only One Level Of Indentation Per Method</li> <li>Don’t Use The ELSE Keyword</li> <li>Wrap All Primitives And Strings First Class Collections</li> <li>One Dot Per Line</li> <li>Don’t Abbreviate</li> <li>Keep All Entities Small</li> <li>No Classes With More Than Two Instance Variables</li> <li>No Getters/Setters/Properties</li> </ul> <h2>Player.cs</h2> <pre><code>namespace Tic_tac_toe { public class Token { // TODO: Get rid off this auto propertie. public char TokenSelected { get; } public Token(char token) =&gt; TokenSelected = token; } public class Player { private readonly Matrix _matrix = new Matrix(3, 3); public Token Token { get; } public Player(Token token) { Token = token; } public void PutTokenAt(Coords coords) { if (_matrix.IsNotEmpty(coords)) _matrix.SetToken(coords, Token); } public bool CheckIfPlayerWon() { return _matrix.CheckRow(Token) || _matrix.CheckColumn(Token) || _matrix.CheckSlashDiagonal(Token) || _matrix.CheckBackSlashDiagonal(Token); } } } </code></pre> <h2>Coords.cs</h2> <pre><code>using System.Collections.Generic; using System.Linq; namespace Tic_tac_toe { public class Coords { public Coords(int x, int y) { X = x; Y = y; } public int X { get; } public int Y { get; } } public class CoordsCollection { private readonly List&lt;Coords&gt; _coordsList; public CoordsCollection() { _coordsList = new List&lt;Coords&gt;(); } public void Add(Coords coords) { _coordsList.Add(coords); } public int Sum(int[,] magicSquare) { return _coordsList.Sum(cord =&gt; magicSquare[cord.X, cord.Y]); } } } </code></pre> <h2>Matrix.cs</h2> <pre><code>namespace Tic_tac_toe { public class Matrix { private readonly int _n; private readonly int _m; private readonly char[,] _value; private Coords _lastMove; public Matrix(int n, int m) { _n = n; _m = m; _value = new char[_n, _m]; CreateMatrix(); } private void CreateMatrix() { for (int i = 0; i &lt; _n; i++) for (int j = 0; j &lt; _m; j++) _value[i, j] = '.'; } public bool IsNotEmpty(Coords coords) { return _value[coords.X, coords.Y] == '.'; } public void SetToken(Coords coords, Token token) { _value[coords.X, coords.Y] = token.TokenSelected; _lastMove = coords; } private bool MagicSquare(CoordsCollection listCord) { // https://en.wikipedia.org/wiki/Magic_square int[,] mS = new int[3, 3]; mS[0, 0] = 2; mS[0, 1] = 7; mS[0, 2] = 6; mS[1, 0] = 9; mS[1, 1] = 5; mS[1, 2] = 1; mS[2, 0] = 4; mS[2, 1] = 3; mS[2, 2] = 8; return listCord.Sum(mS) == 15; } public bool CheckRow(Token token) { CoordsCollection rowCordList = new CoordsCollection(); for (int x = 0; x &lt; _m; x++) if (_value[x, _lastMove.Y] == token.TokenSelected) rowCordList.Add(new Coords(x, _lastMove.Y)); return MagicSquare(rowCordList); } public bool CheckColumn(Token token) { CoordsCollection columnsCordList = new CoordsCollection(); for (int y = 0; y &lt; _n; y++) if (_value[y, _lastMove.Y] == token.TokenSelected) columnsCordList.Add(new Coords(_lastMove.X, y)); return MagicSquare(columnsCordList); } public bool CheckBackSlashDiagonal(Token token) { CoordsCollection backSlashCordsList = new CoordsCollection(); for (int i = 0; i &lt; _n; i++) if (_value[i, i] == token.TokenSelected) backSlashCordsList.Add(new Coords(i, i)); return MagicSquare(backSlashCordsList); } public bool CheckSlashDiagonal(Token token) { CoordsCollection slashCordsList = new CoordsCollection(); for (int x = 0, y = _n - 1; x &lt; _m; x++, y--) if (_value[x, y] == token.TokenSelected) slashCordsList.Add(new Coords(x, y)); return MagicSquare(slashCordsList); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T10:29:43.090", "Id": "533987", "Score": "0", "body": "Which version of C# are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T13:30:10.360", "Id": "534002", "Score": "0", "body": "@PeterCsala Visual studio 2019 (8.0) C# .Net Core 3.1" } ]
[ { "body": "<p>I think there are some good pointers in calisthenics rules, but <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS</a> principles should always trump.</p>\n<p>Consider the following example:</p>\n<pre><code>class Animal\n{\n public Animal(string type, string color)\n {\n Type = type;\n Color = color;\n }\n public string Type;\n public string Color;\n};\n\nclass Program\n{\n static void Main(string[] args)\n {\n var animal = new Animal(&quot;horse&quot;, &quot;brown&quot;);\n Console.WriteLine(animal.Type);\n }\n}\n</code></pre>\n<p>Here we are breaking the <code>One Dot Per Line</code> rule in <code>Console.WriteLine(animal.Type);</code></p>\n<p>How can we solve this?</p>\n<p>Option A: Create a new function to write stuff to the console:</p>\n<pre><code>static void WriteLineToConsole(string text)\n{\n Console.WriteLine(text);\n}\n\nstatic void Main(string[] args)\n{\n var animal = new Animal(&quot;horse&quot;, &quot;brown&quot;);\n WriteLineToConsole(animal.Type);\n}\n</code></pre>\n<p>Option B: Create a new function to return the type of animal:</p>\n<pre><code>static string GetAnimalType(Animal animal)\n{\n return animal.Type;\n}\n\nstatic void Main(string[] args)\n{\n var animal = new Animal(&quot;horse&quot;, &quot;brown&quot;);\n Console.WriteLine(GetAnimalType(animal);\n}\n</code></pre>\n<p>Both options A and B add unnecessary complications and make the program harder to read.</p>\n<hr>\n<p>I have noticed that you are breaking <code>Only One Level Of Indentation Per Method</code> in a couple of places like in <code>CheckColumn</code> but would not recommend that you change them as this would only add unnecessary complications.</p>\n<hr>\n<p>Keeping with KISS principles. Checking Win states using magic squares is pretty cool but it does not really add much value and makes things much more complicated than they need to be.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T17:58:06.910", "Id": "534027", "Score": "0", "body": "Hey, thanks for your reply not only in this post but in other one I did, I remember I read your reply but didn't say anything so now it's perfect time to say thanks for it! Turning to the question, (also I'm sorry for my english) I find it really useful the KISS concept, but I'm not sure how feels the company about it. I also would like to ask, does objects calisthenics should have getters/setters? Since I find really easy to call to a get instead of creating a whole method for returning a simple attribute." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T18:02:33.863", "Id": "534029", "Score": "0", "body": "What do you think is the best approach for OOP? The approach my company is following is TDD + Objects calisthenics and some SOLID principles, they also don't do inheritance but works with interfaces. I don't know if you could gimme some tips or some advice to get better at this. Thanks in advance and again sorry for my English!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T18:17:55.360", "Id": "534033", "Score": "0", "body": "@Sharki, I’m not sure. Some people have very strong feelings about these rules. I would say to mostly go with the flow unless doing so turns your program into a cluttered mess." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T16:50:50.903", "Id": "270424", "ParentId": "270366", "Score": "2" } }, { "body": "<h2><code>Token</code></h2>\n<p>This class is an overkill. I mean I do understand that you want to follow this <em>Wrap All Primitives And Strings First Class Collections</em> rule. But I think you misunderstand the intent.</p>\n<p>Let's suppose you expect a valid e-mail address from your user. You create a wrapper around string to validate it and then be able to pass it along as an e-mail. So others don't have to perform any assessment, since there is a guarantee that whenever they receive an <code>Email</code> instance then it is valid.</p>\n<p>Your <code>Token</code> class does not perform any validation so it can not give any guarantee. It is just yet another layer of abstraction.</p>\n<p>If you really want to have it then create it as <code>struct</code> to express your immutable intent</p>\n<pre><code>public struct Token\n{\n public char Selected;\n\n public Token(char token)\n =&gt; Selected = token;\n}\n</code></pre>\n<h2><code>Player</code></h2>\n<p>If you need to pass the <code>Token</code> for each and every matrix methods then it is a good sign for refactoring. Pass the token as a constructor parameter instead.</p>\n<pre><code>public class Player\n{\n private readonly Matrix _matrix;\n \n public Player(Token token)\n =&gt; _matrix = new Matrix(3, 3, token.Selected);\n\n public void PutTokenAt(Coordinate coordinate)\n =&gt; _matrix.SetToken(coordinate);\n \n public bool CheckIfPlayerWon()\n =&gt; _matrix.CheckRow() ||\n _matrix.CheckColumn() ||\n _matrix.CheckSlashDiagonal() ||\n _matrix.CheckBackSlashDiagonal();\n}\n</code></pre>\n<h2><code>Coords</code></h2>\n<p>Yes, I've renamed your <code>Coords</code> class because that abbreviation just makes your code less understandable. Try to avoid abbreviations for your public API</p>\n<p>Also, I would encourage you to try to use the same terminology across your whole domain. From your code it is pretty channeling to understand how the following things relate to each other: <code>X</code>, <code>_n</code>, <code>column</code></p>\n<pre><code>public struct Coordinate\n{\n public int Column;\n public int Row;\n\n public Coordinate(int x, int y)\n =&gt; (Column, Row) = (x, y);\n}\n</code></pre>\n<ul>\n<li>Yet again this can be a <code>struct</code> to express immutability.\n<ul>\n<li>Since C# 9 you could use <code>record</code> for this purpose as well</li>\n</ul>\n</li>\n<li><code>(Column, Row) = (x, y)</code>: Here we take advantage of <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct\" rel=\"nofollow noreferrer\">ValueTuple's deconstruction</a></li>\n</ul>\n<h2><code>CoordsCollection</code></h2>\n<p>I've added an <code>AddRange</code> method to this class to be able to use LINQ inside the <code>Matrix</code> class</p>\n<pre><code>public class CoordinateCollection\n{\n private readonly List&lt;Coordinate&gt; collection = new List&lt;Coordinate&gt;();\n\n public void AddRange(IEnumerable&lt;Coordinate&gt; cords)\n =&gt; collection.AddRange(cords);\n\n public int Sum(int[,] magicSquare)\n =&gt; collection.Sum(cord =&gt; magicSquare[cord.Column, cord.Row]);\n}\n</code></pre>\n<ul>\n<li>Since C# 9 you can take advantage of <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/target-typed-new\" rel=\"nofollow noreferrer\">target-typed new expression</a>, which would simplify the initialization of <code>collection</code>:</li>\n</ul>\n<pre><code>private readonly List&lt;Coordinate&gt; collection = new ();\n</code></pre>\n<ul>\n<li>I've renamed your <code>_coordsList</code> to <code>collection</code>, because the latter does not tell anything about the type itself which helps evolution of your code</li>\n</ul>\n<h2><code>Matrix</code></h2>\n<p>Let's start with initialization:</p>\n<pre><code>public class Matrix\n{\n private const char initValue = '.';\n private readonly int columns;\n private readonly int rows;\n private readonly char[,] value;\n private readonly char token;\n private Coordinate lastMove;\n\n public Matrix(int n, int m, char selectedToken)\n {\n (columns, rows, token) = (n, m, selectedToken);\n value = new char[columns, rows];\n\n Initialize();\n }\n\n private void Initialize()\n {\n for (int column = 0; column &lt; columns; column++)\n for (int row = 0; row &lt; rows; row++)\n value[column, row] = initValue;\n }\n ...\n}\n</code></pre>\n<ul>\n<li>As I said earlier please try to use the same terminology across your domain</li>\n<li>The <code>CreateMatrix</code> is a really bad name for a private method\n<ul>\n<li>Since you are not creating a new matrix rather populating it with initial values</li>\n<li>Also suffixing a private method with a class seems unreasonable</li>\n<li><code>Initialize</code> is just fine</li>\n</ul>\n</li>\n</ul>\n<h3><code>SetToken</code></h3>\n<pre><code>public void SetToken(Coordinate coords)\n{\n if (value[coords.Column, coords.Row] != initValue) return;\n value[coords.Column, coords.Row] = token;\n lastMove = coords;\n}\n</code></pre>\n<ul>\n<li>Exposing the validation separately from the actual code is really error-prone\n<ul>\n<li>You can not enforce that <code>IsNotEmpty</code> is called prior <code>SetToken </code></li>\n</ul>\n</li>\n<li>If you reuse the same character across two different methods then put it into a constant\n<ul>\n<li>Without that if you update the <code>Initialize</code> to use <code>';'</code> from now on and you forget to change that inside the <code>IsNotEmpty</code> then your code is broken</li>\n</ul>\n</li>\n</ul>\n<h3><code>MagicSquare</code></h3>\n<ul>\n<li>If your method returns with a <code>bool</code> then please prefix it with <code>Is</code> or <code>Has</code></li>\n<li>I haven't dig into the details why do you need this square but it seems fragile\n<ul>\n<li>What if the matrix is 2x2 or 5x1 or 10X15? Will it work?</li>\n</ul>\n</li>\n<li>You can take advantage of collection initializer for multidimensional arrays as well</li>\n</ul>\n<pre><code>int[,] magicSquare = new int[3, 3]\n{\n { 2, 7, 6 },\n { 9, 5, 1 },\n { 4, 3, 8 }\n};\n</code></pre>\n<ul>\n<li>You should create this array only once rather than each and every time when you call this method</li>\n</ul>\n<pre><code>// https://en.wikipedia.org/wiki/Magic_square\nprivate static int[,] magicSquare = new int[3, 3]\n{\n { 2, 7, 6 },\n { 9, 5, 1 },\n { 4, 3, 8 }\n};\n\nprivate bool HasWinner(CoordinateCollection listCord)\n =&gt; listCord.Sum(magicSquare) == 15;\n</code></pre>\n<h3><code>CheckRow</code></h3>\n<p>I've rewritten it in the way to use LINQ instead of for loop</p>\n<pre><code>public bool CheckRow()\n{\n var rowCordList = new CoordinateCollection();\n rowCordList.AddRange(Enumerable.Range(0, columns)\n .Where(column =&gt; value[column, lastMove.Row] == token)\n .Select(column =&gt; new Coordinate(column, lastMove.Row)));\n\n return HasWinner(rowCordList);\n}\n</code></pre>\n<h3><code>CheckColumn</code></h3>\n<p>Here I think you have accidentally mixed the indexing parameters. According to my understanding it should look like this:</p>\n<pre><code>public bool CheckColumn()\n{\n var columnsCordList = new CoordinateCollection();\n columnsCordList.AddRange(Enumerable.Range(0, rows)\n .Where(row =&gt; value[lastMove.Column, row] == token)\n .Select(row =&gt; new Coordinate(lastMove.Column, row)));\n\n return HasWinner(columnsCordList);\n}\n</code></pre>\n<hr />\n<p><strong>UPDATE #1</strong>: reflect to questions</p>\n<blockquote>\n<p>If I get it correctly, every time that I want to give a home to a type that has not more logic than being a type itself I could use a struct instead of create a class, right?</p>\n</blockquote>\n<p>It is <a href=\"https://medium.com/@alexandre.malavasi/class-versus-struct-explained-c-e367e245e6c5\" rel=\"nofollow noreferrer\">not that simple</a>. <code>struct</code> is a value type and most of the time is stored on the stack. Whenever you make a modification then in reality you create a new instance with different value. So, the original value is immutable.</p>\n<p>In case of <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/records\" rel=\"nofollow noreferrer\">C# 9 records</a> are classes under the hood. By using the <code>with</code> keyword you can create a new instance with a different value. <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10#record-structs\" rel=\"nofollow noreferrer\">Since C# 10</a> you have more control over the <code>record</code> structure, for example you can define a <a href=\"https://anthonygiretti.com/2021/08/03/introducing-c-10-record-struct/\" rel=\"nofollow noreferrer\">record struct</a>.</p>\n<blockquote>\n<p>About the target-typed new expression how clean is to use it instead the whole name?</p>\n</blockquote>\n<p>It is basically the counterpart of the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var\" rel=\"nofollow noreferrer\">implicitly typed variable feature</a>.</p>\n<pre><code>var collection = new List&lt;int&gt;():\nList&lt;int&gt; collection = new();\n</code></pre>\n<p>In both cases you can abuse them, like <code>var result = GetExternalCall()</code>. But if you use them wisely then they can shorten your code without ruining legibility.</p>\n<p>I have found this feature pretty useful whenever I want to initialize <code>readonly</code> fields.</p>\n<blockquote>\n<p>I also saw you used a lot the expression bodied members (=&gt;), a lot of people told me not to use it because it makes the code less readable. Since you're using it, I'd like to ask you what do you think about it?</p>\n</blockquote>\n<p>Yet again if it is used wisely then it is not a problem. There are some methods which will never have longer implementation body than a single line then you can use it freely.</p>\n<p>The debate over this feature is similar to the <code>if (condition) return result;</code> vs <code>if (condition) { return result; }</code>. Conciseness vs easier extensibility</p>\n<blockquote>\n<p>Since MagicSquare is initialized out of methods as an attribute I was wondering if it could be marked as readonly (even as a const for this case)?</p>\n</blockquote>\n<p>You can't mark an array as <code>const</code> but you can mark it as a <code>readonly</code>. But it does not prevent you to add or remove items to/from the collection. It only avoids unintentional overwrite of the whole collection (to <code>collectionB</code> or <code>null</code>).</p>\n<p>If you want to prevent addition and removal then consider to use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutablearray?view=net-6.0\" rel=\"nofollow noreferrer\"><code>ImmutableArray</code></a></p>\n<blockquote>\n<p>Exposing the validation separately from the actual code is really error-prone. You can not enforce that IsNotEmpty is called prior SetToken. &lt;&lt; I did not get it and I'd like to know what you mean with that</p>\n</blockquote>\n<p>If you mark the <code>IsNotEmpty</code> method as <code>public</code> then you are exposing it to the users of the class. Even though your intention is that the caller of <code>SetToken</code> should call the <code>IsNotEmpty</code> prior, there is no guarantee that is is called at all</p>\n<pre><code>// Your Intention\nif (IsNotEmpty(...)) //guard expression\n SetToken(...) \n\n// Accidentally\nSetToken(...) //without guard expression\n</code></pre>\n<p>The compiler will not notify the caller of the <code>SetToken</code> that you should call the <code>IsNotEmpty</code> if you want to call <code>SetToken</code>.</p>\n<p>So, it is advisable to move your <a href=\"https://en.wikipedia.org/wiki/Guard_(computer_science)\" rel=\"nofollow noreferrer\">guard expression</a> into the to be called method. If you want to expose it that's fine but make sure it is <strong>also</strong> called inside the method as well (prefer double checks over zero check).</p>\n<blockquote>\n<p>I find LINQ an amazing feature of C# that I MUST to learn. Since explain how the AddRange works is kinda out of scope and I can just take the time enough to figure out for myself, could you maybe tell me a good site or resource to learn LINQ?</p>\n</blockquote>\n<p>The best way to get started with LINQ is the <a href=\"https://docs.microsoft.com/en-us/samples/dotnet/try-samples/101-linq-samples/\" rel=\"nofollow noreferrer\">101 LINQ Samples site</a>.</p>\n<p>In short the code does the following:</p>\n<ul>\n<li><code>Enumerable.Range(0, columns)</code>: It creates a number sequence from 0 to <code>columns</code> where the step is 1. For example, if <code>columns</code> is 5 then <code>0, 1, 2, 3, 4</code></li>\n<li><code>.Where(column =&gt; ...)</code>: It filters out items where the specified condition is not met</li>\n<li><code>.Select(column =&gt; new Coordinate(...))</code>: It creates a new instance for each item in the sequence which is not filtered out. Basically it maps the numbers to coordinates</li>\n</ul>\n<blockquote>\n<p>Also one last thing I forgot to ask, for the No Getters/Setters/Properties rule is it fine to have a public field instead of a property with a getter (notice coordinate class as an example of this) and why?</p>\n</blockquote>\n<p>Coordinate is not a <code>class</code> rather than a <code>struct</code>. In case of <code>struct</code> the members are initialized while the object is created. So it really does not matter whether they are fields or properties.</p>\n<p>Some people never use fields for <code>public</code> members. It is more like a personal preference. If you use auto-generated properties with public setter and getter then there is no real difference.</p>\n<p>Since C# 9 you can define <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init\" rel=\"nofollow noreferrer\">init only setters</a>, which emphasises immutability.</p>\n<hr />\n<p>Final thought: even though these rules/principles/guidance are good you don't have to take them too seriously. They are created to prevent common pitfalls, but if you understand the risk and the added overhead/complexity is greater than the benefit then you can violate the rules. If you document your decision (the <em>whys</em> and <em>why nots</em>) in comments then future maintainer of your code will also understand your code better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T19:23:54.203", "Id": "534094", "Score": "0", "body": "Thanks a lot for your feedback, I appreciate it so much. I have some questions; If I get it correctly, every time that I want to give a home to a type that has not more logic than being a type itself I could use a struct instead of create a class, right? I also didn't know that C# had desconstrucion. (Thanks for that tip)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T19:24:22.847", "Id": "534095", "Score": "0", "body": "About the `target-typed new expression` how clean is to use it instead the whole name? (Which I agree that the whole name feels kinda redundant). I also saw you used a lot the `expression bodied members (=>)`, a lot of people told me not to use it\nbecause it makes the code less readable. Since you're using it, I'd like to ask you what do you think about it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T19:25:06.513", "Id": "534096", "Score": "0", "body": "Since MagicSquare is initialized out of methods as an attribute I was wondering if it could be marked as readonly (even as a const for this case)? Also could you elaborate this? `Exposing the validation separately from the actual code is really error-prone You can not enforce that IsNotEmpty is called prior SetToken` I dind't get it and I'd like to know what you mean with that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T19:26:55.540", "Id": "534098", "Score": "0", "body": "And the last thing, I find LINQ an amazing feature of C# that I MUST to learn. Since explain how the AddRange works is kinda out of scope and I can just take the time enough to figure out for myself, could you maybe tell me a good site or resource to learn LINQ? Thanks in advance also for your time spent writing all this. Also sorry for all these questions! Have a good day! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T19:33:40.047", "Id": "534099", "Score": "1", "body": "@Sharki Good questions. Let me update my post to reflect to all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T20:01:41.357", "Id": "534100", "Score": "0", "body": "Thanks again!, Also one last thing I forgot to ask, for the `No Getters/Setters/Properties` rule is it fine to have a public field instead of a propriety with a getter (notice coordinate class as an example of this) and why? Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T20:06:20.613", "Id": "534101", "Score": "0", "body": "@Sharki I've already updated my post. 2 question remained :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T20:22:21.410", "Id": "534103", "Score": "0", "body": "@Sharki I hope my answers give you clarity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T20:35:37.620", "Id": "534106", "Score": "1", "body": "Thank you very much for your long answer, the feedback and the articles and resources you refer to. I really really really do appreciate a lot. Your reply help me so much and I've learned a lot of things through your whole post, it was pretty clear. Thanks so much! Have a good day :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T05:42:07.633", "Id": "534130", "Score": "2", "body": "In addition to `Coordinate` being a `struct` (in all versions of C#) or a `record` (starting with C# 9), starting with C# 10, it should arguably be a `record struct`." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T12:43:36.023", "Id": "270440", "ParentId": "270366", "Score": "4" } } ]
{ "AcceptedAnswerId": "270440", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T19:06:20.820", "Id": "270366", "Score": "3", "Tags": [ "c#", "object-oriented" ], "Title": "TicTacToe Objects calisthenics OOP" }
270366
<p>In this code the angle between the minute and hour hands of an analog clock are found and calculated and the smaller angle between them returned. This code works perfectly and I am getting back the results I expect.</p> <p>We were told to do this and any testing if necessary.</p> <p>I got asked this in an interview question and wanted to see if there was any way to improve what I came up with.</p> <p>Is there any way you could think to do all this better and shorten this. I am not exactly sure if the validation is the best either. I put in if statements to stop anyone from putting in a random number or more digits then needed but I am not sure if there is a better or more efficient way to do that.</p> <p>I thought about maybe trying to split it individually into every digit so I could validate the time that way but i was not sure it was worth doing it that way either.</p> <p>If there is something I should be doing better to make my code look better or anything that would earn more points within an interview would be great.</p> <p>Anything is appreciated as coding in interviews is difficult and I was wondering if there was anything I could of done better.</p> <p>Example input in main method</p> <pre><code> //valid input System.out.println(calcAngle(&quot;17:00&quot;)); //should return 150 System.out.println(calcAngle(&quot;15:15&quot;)); //should return 7.5 System.out.println(calcAngle(&quot;3:15&quot;)); //should return 7.5 System.out.println(calcAngle(&quot;9:30&quot;)); //should return 105 System.out.println(calcAngle(&quot;17:59&quot;)); //should return 174.5 System.out.println(calcAngle(&quot;11:15&quot;)); //should return 112.5 System.out.println(calcAngle(&quot;23:15&quot;) + &quot;\n&quot;); //should return 112.5 //invalid input should return error message System.out.println(calcAngle(&quot;24:60&quot;)); System.out.println(calcAngle(&quot;00:-1&quot;)); System.out.println(calcAngle(&quot;:00&quot;)); System.out.println(calcAngle(&quot;:&quot;)); System.out.println(calcAngle(&quot;25:00&quot;)); System.out.println(calcAngle(&quot;11:80&quot;)); </code></pre> <pre><code>public static String calcAngle(String time) { double hour=0; double min=0; //Seperating the string hour and minute to different array value String[] sep = time.split(&quot;:&quot;); /* * Two if statements to catch any errors * Stops any incorrect formatting of time causing an error or exception */ //stops any value if time has more than 5 or less than 3 if(time.length()&gt;5 || time.length()&lt;3) { return &quot;Time &quot; + time +&quot; is not formated correctly format as hh:mm with 14:00 or 2:00&quot;; } //getting values of array to check String checkHour = sep[0]; String checkMinute= sep[1]; //does not allow values to be read if they are empty or greater than 2 if(checkHour==&quot;&quot; || checkMinute==&quot;&quot; || checkMinute.length()&gt;2 || checkHour.length()&gt;2) { return &quot;Time &quot; + time + &quot; is not formated correctly format as hh:mm with 14:00 or 2:00&quot;; } //turning strings to doubles hour = Double.parseDouble(sep[0]); min = Double.parseDouble(sep[1]); //value check if(hour&lt;0 || hour&gt;24 || min&lt;0 || min&gt;59) { return &quot;Time &quot; + time + &quot; out of bounds for a 24 hour clock&quot;; } // handle 24-hour notation hour = hour % 12; // find the position of the hour's hand double hours = (hour * 360) / 12 + (min * 360) / (12 * 60); // find the position of the minute's hand double minute = (min * 360) / (60); // calculate the angle difference double angle = Math.abs(hours - minute); // consider the shorter angle and return it if (angle &gt; 180) { angle = 360 - angle; } //returns in The answer for 17:00 is 150.0 Degrees return &quot;The answer for &quot; + time + &quot; is &quot; + angle + &quot; Degrees &quot;; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T23:16:05.663", "Id": "533885", "Score": "1", "body": "`\"0930\"` will raise an `ArrayIndexOutOfBoundsException`. Also, `\"12:00:59\"` incorrectly returns 0.0 degrees." } ]
[ { "body": "<p>Declare variables close to where they're used. <code>hour</code> and <code>min</code> are declared and then ignored for half the body of the method. They can be assigned at declaration time, rather than being set to 0 first. And consider making them <code>final</code>, as they should not be reassigned. <code>sep</code> can also be assigned later.</p>\n<p>It is unclear to me why <code>hour</code> and <code>min</code> are doubles and not integers.</p>\n<p>Avoid abbreviations in names where possible. <code>min</code> should probably be <code>minute</code>. <code>sep</code> doesn't mean anything to me. Separation? Maybe <code>timeParts</code> would be better?</p>\n<p>Most of the comments don't provide information to the reader. Comments should be used to explain why something is done. Readers can tell what is being done by reading the code. If they can't, the code needs to be fixed. &quot;What&quot; comments tend to become stale and incorrect as code is modified.</p>\n<p>In idiomatic java, whitespace surrounds <code>&lt;</code> and <code>&gt;</code>. There is also whitespace between a control flow operator, such as <code>if</code>, and the opening parenthesis.</p>\n<p>Checking the length of the string is duplicated by later checks. Likewise, checking the length of the numbers duplicates work later which ensures they have good numeric values.</p>\n<p>It's not clear to me if the declaration of the <code>calcAngle</code> method can be changed. If it can, returning a <code>String</code> is probably not correct. Throw an exception on failure, and return a numeric angle on success.</p>\n<p>If the hour or minute is not a number, the code throws a NumberFormatException which doesn't clearly indicate which value is the problem.</p>\n<p>The validation code considers 2459 to be a valid hour/minute pairing. If supporting a 24-hour clock,\nit should roll from 2359 to 0000.</p>\n<p><code>hours</code> and <code>minute</code> are very confusing. <code>hourAngle</code> and <code>minuteAngle</code> would be strong improvements. <code>angleDifference</code> would be better than <code>angle</code>. Since the unit of measure is degrees, it would be\nnice if that was included in the variable names as well. Let's avoid crashing into Mars.</p>\n<p>If <code>minute</code> is computed before <code>hours</code>, its computed value can be used when computing <code>hours</code>.</p>\n<p>Using JUnit tests would be highly preferable to a battery of <code>System.out.println</code> calls and visual inspection of the results.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T22:51:16.747", "Id": "270370", "ParentId": "270367", "Score": "2" } }, { "body": "<ol>\n<li>Comments - there is too many of them, usually in places where you could extract code to the well-named method (or just remove comments), try to make the comments unnecessary by improving the code structure - leaving only the ones that explain something not obvious (not needed here) e.g. consider value of:</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>//turning strings to doubles\nhour = Double.parseDouble(sep[0]);\n</code></pre>\n<ol start=\"2\">\n<li><p>Consider actual unit tests instead of manual verification of code outputs. So instead of <code>System.out.println(calcAngle(&quot;17:00&quot;)); //should return 150</code> you can go with <code>assertEquals(calcAngle(&quot;17:00&quot;), &quot;150&quot;);</code> where <code>assertEquals</code> may come from your favorite testing library or you might write it on your own (given project's small scope) - so it throws exception on equality failure</p>\n</li>\n<li><p>Instead of returning strings describing how the program failed you probably want to simply throw exceptions (given small scope just <code>RuntimeException</code> or <code>IllegalArgumentException</code> with proper message should be fine)</p>\n</li>\n<li><p>Consider duplication of your validations (1st vs 2nd) - maybe you don't need to validate whole string if you are validating its parts (or the other way around)? Also current code will fail on missing &quot;:&quot; sign (in, importantly, not predicted, inconsistent way - failure in itself on incorrectly formatted input is expected behavior) - exceptions may help addressing this. Also I'd consider allowing the code to just fail during parsing - if errors are to be read by programmer default exceptions are usually descriptive enough</p>\n</li>\n<li><p>Duplication of checking <code>checkMinute</code> and <code>checkHour</code> length vs cheking values range (0-60 and 0-24) - if values are in range they automatically have proper length</p>\n</li>\n<li><p><code>checkHour</code> and <code>checkMinute</code> names are confusing - <code>check</code> is a verb and variables usually represent data - nouns with adjectives are usually more helpful describing it</p>\n</li>\n<li><p>It might be nitpicking but you might consider <code>Double</code> floating point precision - parsing input to <code>Integer</code> preserves more accurate representation of integer values for longer and you can still explicitly decide how you want to handle integer division (have you considered <code>BigInteger</code>s?) - which seems to be the reason for doubles usage</p>\n</li>\n<li><p><code>double hours</code> and <code>double minutes</code> variable names - these are already angles (between position at 12:00 and current), it would be nice to include this fact in names BTW: consider simplifying calculations to something like <code>hour * ONE_HOUR_ANGLE + minutes / 2;</code> where <code>ONE_HOUR_ANGLE = 360/12</code></p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T12:49:46.617", "Id": "270383", "ParentId": "270367", "Score": "1" } }, { "body": "<p>Eric Stein and Azahe have covered many points already. I won't repeat those here, although some of their points may be reflected in my code.</p>\n<h1>Decomposition</h1>\n<p>This code is made up of one large function. The function does a lot of things, any of which we might want to pull out and used separately. For example, both the hour and minute hand angles are computed and discarded. If we wanted to actually draw a clock with an hour and minute hand, we'd have to add more code with exactly the same internal calculations.</p>\n<p>Instead, we can break the function up into several smaller functions which determine the angles of the hour and minute (and second) hands, and use those functions in another function to calculate the angle between the hour and minute hands.</p>\n<pre><code>public class AnalogClock {\n private final static int FULL_CIRCLE_DEGS = 360;\n private final static int HALF_CIRCLE_DEGS = FULL_CIRCLE_DEGS / 2;\n\n public static double hourHandAngle(LocalTime time) { ... }\n public static double minuteHandAngle(LocalTime time) { ... }\n public static double secondHandAngle(LocalTime time) { ... }\n\n public static double angleBetweenHands(LocalTime time) {\n double hour_hand_degs = hourHandAngle(time);\n double minute_hand_degs = minuteHandAngle(time);\n\n double angle_diff_degs = Math.abs(hour_hand_degs - minute_hand_degs);\n if (angle_diff_degs &gt; HALF_CIRCLE_DEGS)\n angle_diff_degs = FULL_CIRCLE_DEGS - angle_diff_degs;\n\n return angle_diff_degs;\n }\n}\n</code></pre>\n<h1>Use built-in classes where possible</h1>\n<p>Java has many built-in class for working with times. The class <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html\" rel=\"nofollow noreferrer\"><code>LocalTime</code></a> is &quot;<em>a description of the local time as seen on a wall clock</em>&quot;, making it ideal for representing the time for your problem.</p>\n<p>The <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html#toSecondOfDay--\" rel=\"nofollow noreferrer\"><code>.toSecondOfDay()</code></a> method (or the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html#toNanoOfDay--\" rel=\"nofollow noreferrer\"><code>.toNanoOfDay()</code></a> method if you want sub-second accuracy) will return a value you can use to compute the hand angles from.</p>\n<p>It even has a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html#parse-java.lang.CharSequence-\" rel=\"nofollow noreferrer\"><code>.parse(CharSequence text)</code></a> method for converting a time string into a <code>LocalTime</code> object, which pretty much solves most of your parsing issues.</p>\n<pre><code> public static double angleBetweenHands(String time_string) {\n return angleBetweenHands(LocalTime.parse(time_string));\n }\n</code></pre>\n<p>You can use a <code>DateTimeFormatter</code> object for additional flexibility, if needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T00:04:52.253", "Id": "270399", "ParentId": "270367", "Score": "1" } } ]
{ "AcceptedAnswerId": "270370", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T19:31:41.757", "Id": "270367", "Score": "3", "Tags": [ "java", "interview-questions", "computational-geometry" ], "Title": "Find smaller angle between minute and hour hands of clock" }
270367
<p>I am currently working on a chess console app. However i feel like i got some inefficient code. For example: In order to find out whether an enemy is in check I start iteration over all pieces and all their possible moves. I am glad to get any advice regarding the structure syntax etc. on my project.</p> <p><a href="https://github.com/DerEddie/ChessConsoleApp" rel="nofollow noreferrer">https://github.com/DerEddie/ChessConsoleApp</a></p> <pre><code>sing System; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32; namespace OOPChessProject { class Controller { public Field stringToField(string s) { // String to Field Methode int c = (int)(col)Enum.Parse(typeof(col), s[0].ToString()); int r = (int)(row)Enum.Parse(typeof(row), &quot;_&quot; + s[1]); Field of = new Field(r, c); return of; } public void MainGameLoop() { //Init Game with the Players var cGame = new ChessGame(&quot;Eduard&quot;, &quot;Benjamin&quot;); cGame.GameState = gameState.Running; bool isCheck; Console.ReadKey(); //Game Loop do { #region Printing the board Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(&quot;_________________________________&quot;); Console.WriteLine(&quot;Iteration Nr.&quot; + cGame.TurnCounter); Console.WriteLine(cGame.currentChessBoard); Console.WriteLine(cGame.CurrentPlayer + &quot;'s turn!&quot;); Console.WriteLine(cGame.CurrentPlayer.Color); Console.WriteLine(&quot;_________________________________&quot;); #endregion region MyClass definition //check if there is a check //change color because we need to iter of opponents pieces isCheck = cGame.currentChessBoard.isChecked(Helper.ColorSwapper(cGame.CurrentPlayer.Color)); Console.WriteLine(&quot;Checked:&quot;); if (isCheck) { cGame.GameState = gameState.Check; Console.WriteLine(&quot;CHECK!&quot;); } if (cGame.GameState == gameState.Check) { //TODO function which returns true if mitigation of check found if (!cGame.ChessMitigationPossible()) { Console.WriteLine(&quot;Game Over!&quot;); Console.ReadKey(); } } else //if there is no check we need to see if there is a stalemate which will result in a draw { if (!cGame.movesAvailable()) { Console.WriteLine(&quot;Stalemate!&quot;); } } //Check if the check can be mitigated var OwnPieces = cGame.currentChessBoard.getAllPiecesOfColor(cGame.CurrentPlayer.Color); //Create Copy of the Board //Perform the the move and then check if the check is still there. Once Move was found we break out //var boardCopy #region Asking for 1st User Input //User Input --&gt; Another While Loop Console.WriteLine(&quot;Enter Origin Field: [A-H][1-8]&quot;); string s = Console.ReadLine(); var of = stringToField(s); #endregion #region Check for right color and if field is not empty //if the colors are not the same we need to prompt again for input, because not the right piece was chosen. if (!cGame.isPlayerAndPieceColorSame(cGame.CurrentPlayer, cGame.currentChessBoard.GetPieceFromField(of))) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(&quot;WRONG COLOR OR FIELD IS EMPTY!!!&quot;); Console.ForegroundColor = ConsoleColor.Yellow; continue; } #endregion //Lookup the possible Moves var p = cGame.currentChessBoard.GetPieceFromField(of); var listofMoves = p.getPossibleMoves(cGame.currentChessBoard); foreach (var f in listofMoves) { Console.WriteLine(f); } //Check if there is a Piece and the correct color //Get List Of Possible Moves for that Piece //cGame.currentChessBoard.GetPieceFromField(Field f); Console.WriteLine(&quot;Enter Destination Field: [A-H][1-8]&quot;); s = Console.ReadLine(); var df = stringToField(s); MovementType mtype = MovementType.moving; ; foreach (var move in listofMoves) { if (move.ToField.ToString() == df.ToString()) { mtype = move.movementType; } } //Move gets Performed cGame.currentChessBoard.MovePiece(of, df, mtype, cGame.TurnCounter); //After the move check whether this piece now attacks the enemy King //Change current Player cGame.CurrentPlayer= (cGame.CurrentPlayer == cGame.Player1) ? cGame.Player2: cGame.Player1; cGame.TurnCounter++; } while (true); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T13:41:34.337", "Id": "533915", "Score": "5", "body": "Please include all the code that you want to be reviewed in the body of the question. We can use links as references, but we can't review the code of the links." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T19:55:33.807", "Id": "270368", "Score": "0", "Tags": [ "c#", "performance", "object-oriented", "chess" ], "Title": "Thinking about the efficiency of my chess program" }
270368
<p><a href="https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem" rel="nofollow noreferrer">Climbing the Leaderboard</a></p> <blockquote> <p>An arcade game player wants to climb to the top of the leaderboard and track their ranking. The game uses Dense Ranking, so its leaderboard works like this:</p> <p>The player with the highest score is ranked number <span class="math-container">\$1\$</span> on the leaderboard. Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.</p> <h3>Example</h3> <p><span class="math-container">\$ranked = [100, 90, 90, 80]\$</span></p> <p><span class="math-container">\$player = [70, 80, 105]\$</span></p> <p>The ranked players will have ranks 1, 2, 2, and 3, respectively. If the player's scores are 70, 80 and 105, their rankings after each game are 4<sup>th</sup>, 3<sup>rd</sup> and 1<sup>st</sup>. Return <code>[4, 3, 1]</code>.</p> <h3>Function Description</h3> <p>Complete the climbingLeaderboard function in the editor below.</p> <p>climbingLeaderboard has the following parameter(s):</p> <ul> <li><code>int ranked[n]</code>: the leaderboard scores</li> <li><code>int player[m]</code>: the player's scores</li> </ul> <h3>Returns</h3> <ul> <li><code>int[m]</code>: the player's rank after each new score</li> </ul> <h3>Input Format</h3> <p>The first line contains an integer <span class="math-container">\$n\$</span>, the number of players on the leaderboard. The next line contains space-separated integers <span class="math-container">\$ranked[i]\$</span>, the leaderboard scores in decreasing order. The next line contains an integer, <span class="math-container">\$m\$</span>, the number games the player plays. The last line contains space-separated integers <span class="math-container">\$player[i]\$</span>, the game scores.</p> <h3>Constraints</h3> <ul> <li><span class="math-container">\$1 &lt;= n &lt;= 2 x 10^5\$</span></li> <li><span class="math-container">\$1 &lt;= m &lt;= 2 x 10^5\$</span></li> <li><span class="math-container">\$0 &lt;= ranked[i] &lt;= 10^9\$</span> for <span class="math-container">\$0 &lt;= i &lt; n\$</span></li> <li>The existing leaderboard, <span class="math-container">\$ranked\$</span>, is in descending order.</li> <li>The player's scores, <span class="math-container">\$scores\$</span>, are in ascending order.</li> </ul> <h3>Subtask</h3> <p>For <span class="math-container">\$60%\$</span> of the maximum score:</p> <ul> <li><span class="math-container">\$1 &lt;= n &lt;= 200\$</span></li> <li><span class="math-container">\$1 &lt;= m &lt;= 200\$</span></li> </ul> <h3>Sample Input 1</h3> <pre><code>7 100 100 50 40 40 20 10 4 5 25 50 120 </code></pre> <h3>Sample Output 1</h3> <p>6 4 2 1</p> </blockquote> <p>I keep getting timed out. I think my general logic is right but how can my code be optimized more?</p> <p>I know there are solutions using the bisect module but I've seen very simple ones without using that. From what I can think of, maybe using while loops will speed things up?</p> <pre><code>def climbingLeaderboard(ranked, player): ranked=[i for n, i in enumerate(ranked) if i not in ranked[:n]] #remove duplicates player_rank=[] ranking=len(ranked)+1 start=1 for pi,ps in enumerate(player[::-1]): for ri,r in enumerate(ranked,start=start): if ps&gt;=r: player_rank.append(ri) break else: ranked=ranked[1:] start+=1 else: player_rank.append(ranking) return player_rank[::-1] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T00:22:20.913", "Id": "533887", "Score": "0", "body": "Are you sure the code works at all?" } ]
[ { "body": "<p><strong>Removing duplicates efficiently</strong></p>\n<pre><code>ranked=[i for n, i in enumerate(ranked) if i not in ranked[:n]]\n</code></pre>\n<p>This line creates a copy of <code>ranked</code> at each iteration, which makes it inefficient.\nSince <code>ranked</code> is already sorted, create a new list and add elements one by one if different from the previous.</p>\n<p>Alternatively, you can use a dictionary that is ordered from Python 3.7.</p>\n<pre><code>ranked = list(dict.fromkeys(ranked))\n</code></pre>\n<p><strong>Rank assignment</strong></p>\n<p>The second part of the algorithm creates many copies of <code>ranked</code> in <code>ranked=ranked[1:]</code>, which might be the issue. As you said, using a while loop can speed things up. Refactored code:</p>\n<pre><code>def climbingLeaderboard(ranked, player):\n ranked = list(dict.fromkeys(ranked))\n player_rank = []\n ranking = len(ranked) + 1\n start = 0\n for pi, ps in enumerate(player[::-1]):\n j = start\n while j &lt; len(ranked):\n if ps &gt;= ranked[j]:\n player_rank.append(j + 1)\n break\n start += 1\n j += 1\n if j == len(ranked):\n player_rank.append(ranking)\n return player_rank[::-1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T22:47:29.377", "Id": "533949", "Score": "0", "body": "Thanks it worked! I think ranked=ranked[1:] was the problem. I'm a bit new to code optimization, can you explain more about how that creates many copies of ranked?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T01:39:02.710", "Id": "533956", "Score": "0", "body": "@MysteriousShadow I am glad I could help. `ranked=ranked[1:]` creates many copies because it's in the for-loop." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T06:18:31.200", "Id": "270377", "ParentId": "270371", "Score": "2" } } ]
{ "AcceptedAnswerId": "270377", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-24T23:02:08.233", "Id": "270371", "Score": "1", "Tags": [ "python", "programming-challenge", "time-limit-exceeded", "binary-search" ], "Title": "HackerRank - Climbing the Leaderboard: I don't understand why my code is exceeding the time limit" }
270371
<p>I have implemented few functions in C language that manipulate strings. These functions are not present in the standard C library.</p> <hr /> <h2>string_library.c</h2> <pre><code> #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &quot;string_library.h&quot; /* * get_input_from_stdin_and_discard_extra_characters(char *str, long size): * * Function get_input_from_stdin_and_discard_extra_characters() reads at most * 'size - 1' characters into 'str' from stdin and then appends the NULL * character ('\0'). In all cases, reading input stops after encountering a * newline ('\n') or EOF even if 'size - 1' characters have not been read. * If a newline ('\n') or EOF is read then these are replaced by NULL character * ('\0'). If there are extra characters in input, they are read and discarded. * In all cases, str is returned. * */ char *get_input_from_stdin_and_discard_extra_characters(char *str, long size) { char c = 0; long num_chars_to_read = size - 1; long i = 0; if (!str) return NULL; if (num_chars_to_read &lt;= 0) return NULL; for (i = 0; i &lt; num_chars_to_read; i++) { c = getchar(); if ((c == '\n') || (c == EOF)) { str[i] = 0; return str; } str[i] = c; } // end of for loop str[i] = 0; // discard rest of input while ((c = getchar()) &amp;&amp; (c != '\n') &amp;&amp; (c != EOF)); return str; } // end of get_input_from_stdin_and_discard_extra_characters int is_string_empty(const char *str) { if (!str) return 1; if (*str == 0) return 1; return 0; } // end of is_string_empty int is_string_all_whitespace(const char *str) { char *temp = (char *)(str); if (is_string_empty(str)) return 1; while (*temp) { if ((*temp != ' ') &amp;&amp; (*temp != '\t')) return 0; temp++; } return 1; } // is_string_all_whitespace /* * This function fills 'str' with 'len - 1' random characters and appends a null * byte at the end and returns 'str'. */ char *get_random_string(char *str, long len) { int min_num = 32; int max_num = 126; int i = 0; for (i = 0; i &lt; (len - 1); i++) { str[i] = (random() % (max_num - min_num + 1)) + min_num; } str[len - 1] = 0; return str; } /* * str_replace_chr(char *str, const char orig, const char new): * * Function str_replace_chr() replaces all occurrences of 'orig' character in * the string 'str' with the 'new' character. If 'str' is NULL then nothing is * done. In all cases, 'str' is returned. * */ char *str_replace_chr(char *str, const char orig, const char new) { char *orig_str = (str); if (!str) return orig_str; while (*str) { if (*str == orig) *str = new; str++; } return orig_str; } // end of str_replace_chr /* * substr(const char *str, long start_index, long end_index): * * Function substr() allocates memory and returns a pointer to a string / character * array which is a substring of 'str' starting from index 'start_index' till * 'end_index' (inclusive). This substring is terminated by NULL byte at the end. * If 'str' is NULL or 'start_index' is less than 0 or 'end_index' is less than 0 * or 'end_index' is less than 'start_index' then NULL is returned. * * The returned pointer points to a memory region containing the substring and this * memory region was allocated using malloc. So, it is the user's responsibility to * free the allocated memory. * */ char *substr(const char *str, long start_index, long end_index) { char *substring = NULL; long length = 0; long i = 0; if (!str) return NULL; if ((start_index &lt; 0) || (end_index &lt; 0) || (end_index &lt; start_index)) return NULL; length = end_index - start_index + 1; substring = malloc(length + 1); // extra 1 byte for NULL byte if (!substring) return NULL; for (i = 0; i &lt; length; i++) { substring[i] = str[i + start_index]; } substring[i] = 0; return substring; } // end of substr </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T09:28:40.407", "Id": "533909", "Score": "2", "body": "Would you show us the header too? I doubt it contains anything too controversial, but it's always helps, for a full review." } ]
[ { "body": "<h2><code>get_input_from_stdin_and_discard_extra_characters</code></h2>\n<blockquote>\n<pre><code> c = getchar();\n</code></pre>\n</blockquote>\n<p><code>c</code> is a <code>char</code>, so we lose the ability to distinguish <code>EOF</code> here. We need to use <code>int</code> for that.</p>\n<p>The whole function could be made much simpler: just use <code>fgets()</code>, then if the final character read was <code>\\n</code>, overwrite it, else discard the rest of the line with <code>scanf(&quot;%*[^\\n]&quot;),scanf(&quot;%*c&quot;)</code>.</p>\n<h2><code>is_string_empty</code></h2>\n<p>The name is very close to those reserved for standard library extension, but is legal because <code>is</code> is followed by underscore rather than a lower-case letter.</p>\n<p>It would be better named as <code>is_string_null_or_empty</code>, as a null pointer is quite different from an empty string. It could be simplified, too:</p>\n<pre><code>#include &lt;stdbool.h&gt;\n\nbool is_string_empty(const char *str)\n{\n return !str || !*str;\n}\n</code></pre>\n<h2><code>is_string_all_whitespace</code></h2>\n<p>Don't cast away <code>const</code> like that. <code>temp</code> can be a pointer to <code>const char</code>.</p>\n<p>I'm surprised that only space and tab are considered - why not everything that's <code>isspace()</code>?</p>\n<p>This too could be much simpler:</p>\n<pre><code>#include &lt;ctype.h&gt;\n\nbool is_string_null_or_all_whitespace(const char *s)\n{\n if (!s) { return true; }\n for (;;) {\n if (!*s) { return true; }\n if (!isspace((unsigned char)(*s++))) { return false; }\n }\n}\n</code></pre>\n<h2><code>get_random_string</code></h2>\n<p>Is there any value in returning the pointer that was passed? Consider a return type of <code>void</code> instead.</p>\n<p>The length should probably be a <code>size_t</code> rather than <code>long</code>.</p>\n<p>Those min and max values suggest that you're assuming the target is using ASCII - if so, that assumption should be documented (and preferably tested so that where it's untrue, users get a compilation error rather than random behaviour).</p>\n<p>Is there a good reason not to use the standard library <code>rand()</code> for this function?</p>\n<pre><code>#include &lt;assert.h&gt;\n\nvoid get_random_string(char *str, size_t len)\n{\n assert(' ' == 32); /* This function assumes ASCII */\n static const char min_num = 32;\n static const char max_num = 126;\n\n while (len--) {\n *str++ = (char)(rand() % (max_num - min_num + 1) + min_num);\n }\n *str = '\\0';\n}\n</code></pre>\n<h2><code>substr</code></h2>\n<p>If we passed the indices as <code>size_t</code>, we wouldn't need to check for negative values.</p>\n<p>In modern C, we don't need to declare all our variables at beginning of scope. It's better to wait until we can initialise them.</p>\n<p>We should use the standard <code>memcpy()</code> function to copy the contents. Good compilers will recognise the loop and replace with <code>memcpy()</code>, but it's easier to use the function than to write the loop correctly.</p>\n<p>We'll get undefined behaviour if we attempt to copy off the end of the array. We could use <code>strncpy()</code> to finish when we reach a null character, or we could measure the length and check that at the start of the function.</p>\n<p>I like the good handling for when <code>malloc()</code> returns a null pointer.</p>\n<pre><code>#include &lt;string.h&gt;\n\nchar *substr(const char *str, size_t start_index, size_t end_index)\n{\n if (!str || !*str ) {\n return NULL;\n }\n const char *end = memchr(str, '\\0', end_index);\n if (end) {\n end_index = end - str - 1;\n }\n if (end_index &lt; start_index) {\n return NULL;\n }\n\n const size_t length = end_index - start_index + 1;\n\n char *const substring = malloc(length + 1); // include terminating null char\n if (substring) {\n memcpy(substring, str + start_index, length);\n substring[length] = '\\0';\n }\n\n return substring;\n}\n</code></pre>\n<h2>Overall</h2>\n<p>I'm disappointed to see no unit tests of these functions. Including tests in the review helps us understand what's known to work, and often tells us about the anticipated use cases. I encourage you to include tests whenever possible!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T19:58:30.370", "Id": "534340", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/131920/discussion-on-answer-by-toby-speight-functions-in-c-language-that-manipulate-str)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T10:25:41.233", "Id": "270381", "ParentId": "270376", "Score": "8" } }, { "body": "<h1>substr</h1>\n<p>This function does not work as I expected it to. If I called it like in the following:</p>\n<pre><code>substr(&quot;abc&quot;, 1, 1);\n</code></pre>\n<p>I would have expected it to return an empty string <code>&quot;&quot;</code> and not <code>&quot;b&quot;</code>.</p>\n<p>You should try to limit your function to do a single task. <code>substr</code> allocates a new string and writes to it. You can leave the allocation up to the caller.</p>\n<p>Suggested replacement:</p>\n<pre><code>int substr(char* dst, size_t size, const char* src, size_t start, size_t length)\n{\n if (length &gt;= size || start + length &gt; strlen(src))\n return -1;\n memmove(dst, src + start, length);\n dst[length] = 0;\n return length;\n}\n</code></pre>\n<p>This has two advantages over your implementation:</p>\n<ol>\n<li>You do not have to remember to <code>free</code> the results</li>\n<li>It can be used on pre-existing buffers.</li>\n</ol>\n<p>Consider the following</p>\n<pre><code>struct ipaddress\n{\n char part1[4];\n char part2[4];\n char part3[4];\n char part4[4];\n};\n\nint main()\n{\n char* test = &quot;196.168.332.556&quot;;\n struct ipaddress adr;\n substr(adr.part1, 4, test, 0, 3);\n substr(adr.part2, 4, test, 4, 3);\n substr(adr.part3, 4, test, 8, 3);\n substr(adr.part4, 4, test, 12, 3);\n}\n</code></pre>\n<p>If you used your implementation, you would have had to do an extra <code>strcpy</code> and remembered to free the string.</p>\n<p>You will also be able to use the same buffer for the source and destination like so:</p>\n<pre><code>int main()\n{\n char test[] = &quot;123ABCDEF456&quot;; \n substr(test, sizeof(test), test, 3, 6);\n printf(&quot;%s\\n&quot;, test);\n}\n</code></pre>\n<h1>str_replace_chr</h1>\n<p>Here you could have used <code>strchr</code> to search for the occurrences of <code>orig</code>:</p>\n<pre><code>void str_replace_chr(char* str, const char orig, const char new)\n{\n while (str = strchr(str, orig))\n {\n *str++ = new;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T16:17:01.393", "Id": "533925", "Score": "0", "body": "Did you consider introducing the `restrict` keyword for the pointer arguments to your version of `substr`, to tell the compiler (and the user) that the destination won't overlap the source string? Was omitting them (and using `memmove()` rather than `memcpy()`) an intentional choice? Worth elaborating on in your answer..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T16:22:35.047", "Id": "533926", "Score": "1", "body": "@TobySpeight, I considered that it might be legal for the destination to overlap and that is why I used `memmove` instead of `memcpy`. Consider the following `char test[] = \"ABCD123\"; substr(test, sizeof(test), test, 2, 4);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T16:36:28.230", "Id": "533928", "Score": "0", "body": "Yep, makes sense. That looks like a reasonable use-case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T16:39:23.147", "Id": "533930", "Score": "0", "body": "@TobySpeight, updated. To you think there is any advantage to use `strchr` over manually looping?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T16:41:46.757", "Id": "533931", "Score": "0", "body": "Probably not, but I think it has educational value that makes that section worthwhile. It shows a different way to look at the problem, and I always find that useful in a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T16:43:41.283", "Id": "533932", "Score": "1", "body": "Actually, `strchr()` can be implemented more efficiently than the plain loop on many architectures, so it might have a small performance advantage, particularly when the string is long with few or no matches." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T23:38:28.267", "Id": "533951", "Score": "1", "body": "Maybe be explicit that closed-range indices are rare for good reason, and also say why you prefer and changed to index+length at least for this name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T00:12:13.680", "Id": "533953", "Score": "0", "body": "@Deduplicator, thanks, I'll do so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T05:44:44.673", "Id": "533964", "Score": "0", "body": "@jdt, In your code - \"substr(\"abc\", 1, 1);\" the function works the way I intended it too. May be your expectations were different. From my point of view, if the start_index and end_index are same, then it means that the user wants only 1 character which is at start_index. Also, I didn't leave the responsibility of allocation of memory to the caller because I wanted to make it easier for the caller. I wanted the caller to do as less work as possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T05:49:54.677", "Id": "533965", "Score": "0", "body": "I have not called any other C library function from my program because I wanted to save the time cost of calling a function - time taken in setting up stack, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T07:49:07.417", "Id": "533966", "Score": "0", "body": "@Amit, if you're concerned about performance, you really ought to be measuring rather than just guessing. Even experts find their intuition about performance is often out of line with reality. I'll be surprised if you can measure the overhead of calling a library function (especially as this will likely be inlined by any decent optimiser). But I won't say it's definitely not worth it until I see measurements!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T09:41:37.413", "Id": "533978", "Score": "0", "body": "FWIW, the start/end index interface is used by [GNU Make's `$(wordlist)` function](https://www.gnu.org/software/make/manual/html_node/Text-Functions.html#index-selecting-word-lists), and you're expected to pass (1, 0) to get the empty string. So there is _some_ precedent, albeit in an unrelated language." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T15:13:45.330", "Id": "534015", "Score": "0", "body": "@Amit re: `substr` I’m not saying that there is anything wrong with the way you are handling the indices but, for me at least, it is not intuitive. If you wanted the function to dynamically allocate memory you can also consider using `strndup`. For usage on pre-existing buffers, you could have considered `strncpy` or using `memmove` and setting the zero-termination character if there is a possibility that the source and destination may overlap. There are many ways to skin a cat as the saying goes :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T15:19:01.780", "Id": "534016", "Score": "0", "body": "@Amit re: `str_replace_chr` As Toby has already mentioned, it would be a good exercise to do some benchmarking to see which way is faster. I would guess that you may get slightly better results for small strings with lots of `orig` characters with a manual loop and a slight improvement for a large string with sparse occurrence of `orig` using `strchr`. This may be an interesting follow-up question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T02:30:44.820", "Id": "534049", "Score": "0", "body": "A few more tests in `substr()` would cope with pathological inputs where `start + length` overflows and `length > INT_MIN`, etc." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T15:52:16.930", "Id": "270388", "ParentId": "270376", "Score": "3" } }, { "body": "<p><strong>Functional difference from <code>fgets()</code></strong></p>\n<p>I'd expect <code>get_input_from_stdin_and_discard_extra_characters()</code> to perform like <code>fgets()</code> when there is no input. Instead <code>get_input_from_stdin_and_discard_extra_characters(str, ...)</code> returns <code>str</code>. <code>fgets(str, ...)</code> returns <code>NULL</code>.</p>\n<p><strong>Types</strong></p>\n<p>Size of buffer and array indexing is more idiomatic C as <code>size_t</code> than <code>long</code>. Even <code>int</code> has some precedent, but not <code>long</code>.</p>\n<p>Use <code>int c</code> to save result from <code>fgetc()</code> to well distinguish the 257 different responses. Avoid infinite loops when <code>char</code> is <em>unsigned</em> and <code>fgetc()</code> returns <code>EOF</code>.</p>\n<p><strong>Pedantic: signed math overflow</strong></p>\n<p>Perform <code>if (num_chars_to_read &lt;= 0)</code> before <code>long num_chars_to_read = size - 1;</code> to avoid signed math overflow.</p>\n<p><strong>Missing string_library.h</strong></p>\n<p><strong>Documentation</strong></p>\n<p>External functions deserve documentation in the .h file. Consider the user may not have access to the .c file (nor want it). Documentation in the .c file explains implementation. Overall functionality, higher level, is for the .h.</p>\n<p><strong>Name space</strong></p>\n<p><code>string_library.c</code> contains various functions that have no or little <em>name</em> connection to <code>string_library.*</code>. Consider a more uniform naming convention.</p>\n<p><code>get_input_from_stdin_and_discard_extra_characters()</code> is too long.</p>\n<p><strong>Pedantic: range</strong></p>\n<p><code>get_random_string(str,len)</code> is UB when <code>len &lt;= 0</code>.</p>\n<p><strong><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself#WET\" rel=\"nofollow noreferrer\">WET</a> <code>()</code></strong></p>\n<p><code>()</code> not needed in <code>char *orig_str = (str);</code>.</p>\n<p><strong><code>NULL</code> is for pointers</strong></p>\n<p>Rather then comment</p>\n<pre><code>// extra 1 byte for NULL byte\n// use \nextra 1 byte for null character\n// or\nextra 1 byte for \\0\n// or\nextra 1 byte for nul\n</code></pre>\n<p><code>NULL</code> is the <em>null pointer constant</em>. It may be a pointer type.</p>\n<p><em>null character</em> is what the C spec uses.</p>\n<p><code>'\\0'</code> is another good choice</p>\n<p><em>nul</em> is defined outside C in ASCII.</p>\n<p><strong>Well uniformly formatted</strong></p>\n<p><strong>No noticed spelling/grammar issues</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T17:32:56.653", "Id": "534164", "Score": "0", "body": "Chux, - \"\"\"\"get_random_string(str,len) is UB when len <= 0.\"\"\"\" - this is not unbounded because in the for loop, the condition 0 < some_negative_number will not be satisfied and the loop will exit. However, it will crash because of \"\"\"\"str[len - 1] = 0;\"\"\"\". So, I will fix the code to check 'len' for negative values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T17:34:56.957", "Id": "534165", "Score": "0", "body": "Chux, \"\"\"\"Perform if (num_chars_to_read <= 0) before long num_chars_to_read = size - 1; to avoid signed math overflow.\"\"\"\" - I don't see how will there be an overflow. Can you please give an example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T17:57:22.687", "Id": "534172", "Score": "0", "body": "Chux, , I have intentionally avoided size_t because it is unsigned. If by mistake user passes -1 then size_t will lead to a crash because -1 is ULONG_MAX and so str[ULONG_MAX] will crash. Also, malloc() will return NULL because it won't get memory of size ULONG_MAX." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T19:24:40.070", "Id": "534175", "Score": "0", "body": "@Amit \"fgets() never returns NULL.\" C spec has \"If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and _a null pointer is returned_. If a read error occurs during the operation, the array contents are indeterminate and _a null pointer is returned_. Unclear what code you used that had \"If the first character read is '\\n' or EOF then ... fgets() will return an empty string\". For some clarity, we are talking about the _return_ value which is either a _null pointer_ or a pointer to a string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T21:24:37.563", "Id": "534184", "Score": "0", "body": "@Amit \"These functions will return only when user presses enter or an EOF is read\" not quite. Other cases: file input buffer full, input error occurs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T21:27:35.960", "Id": "534185", "Score": "0", "body": "@Amit \"how will there be an overflow.\" --> Pathological case: `get_input_from_stdin_and_discard_extra_characters(str, LONG_MIN)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T21:32:35.063", "Id": "534186", "Score": "1", "body": "@Amit \"avoided size_t because it is unsigned. If by mistake user passes ....\" --> If the user makes a mistake, then all sorts of unavoidable problems occur. Using a signed type may give warnings when an proper `size_t` variable is passed as the _size_. `size_t` is the right size type to use for _all_ object sizing and array indexing - neither too narrow nor too wide. This tends to be a holy war, so in the end, follow your group's coding standards. C lib tends to use `size_t`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T09:13:52.300", "Id": "534282", "Score": "0", "body": "Chux, on all conditions that fgets() returns NULL, my function returns an empty string (the first character of str is made 0). But I will change my code to return NULL as fgets() does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T09:26:02.083", "Id": "534287", "Score": "0", "body": "@Amit Yes, \"the first character of str is made 0\", when able, is a good thing on end-of-file and input error. Even though it is not _needed_ when function returns `NULL` as calling code can switch on that and ignore the buffer, I do not like `fgets()` leaving the buffer unchanged on `NULL` return. I would prefer such input functions to do as your code does: always affect the buffer, even when returning `NULL`." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T02:25:07.110", "Id": "270435", "ParentId": "270376", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T05:18:41.920", "Id": "270376", "Score": "4", "Tags": [ "c", "strings" ], "Title": "Functions in C language that manipulate strings, not present in the standard C library" }
270376
<p>I have several products. A product can have 1 or more images. In each image, we have content slot. I don't want duplication per content slot in a product.</p> <p>My code works fine. I'm just wondering what will be a better way to do this or improvement on my code?</p> <p>Codesandbox is here <a href="https://codesandbox.io/s/redux-added-array-of-object-inside-another-aray-in-react-forked-uxqce?file=/src/components/MediaCard/index.js" rel="nofollow noreferrer">CLICK HERE</a></p> <pre><code> &lt;Autocomplete fullWidth size=&quot;small&quot; options={ Boolean(product.slot) &amp;&amp; product.slot.length &gt; 0 ? contentSlots.filter( (slot) =&gt; !product.slot.find((data) =&gt; data.value.id === slot.id) ) : contentSlots } renderInput={(params) =&gt; ( &lt;TextField {...params} label=&quot;Content Slots&quot; variant=&quot;outlined&quot; fullWidth /&gt; )} getOptionLabel={(option) =&gt; option.name || &quot;&quot;} disableClearable={true} onChange={(_, value) =&gt; onChangeContentSlot(value, product)} /&gt; </code></pre>
[]
[ { "body": "<p>The filtering of options logic can be simplified a bit. Instead of first checking that the product slot array exists and has a truthy length, just allow the array's <code>.find</code> method to handle empty arrays, using Optional Chaining to access this deeply into the <code>product</code> object. You can also merge the two logic branches by returning <code>true</code> when the conditions are not met and the currently iterated element should <em><strong>not</strong></em> be filtered out, which happens any time the optional chaining hits a null or undefined property <em><strong>or</strong></em> there are no matches found.</p>\n<pre><code>options={contentSlots.filter(\n (slot) =&gt; !product?.slot?.find((data) =&gt; data.value.id === slot.id)\n)}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T00:53:51.277", "Id": "534257", "Score": "0", "body": "How about on the reducer? appConstants.CHANGE_CONTENT_SLOTS. Was it structured and coded correctly? or there is a better way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T01:07:25.853", "Id": "534258", "Score": "0", "body": "@Joseph Oh, sorry, I thought you were only asking about the filtering of options. Yeah, the `CHANGE_CONTENT_SLOTS` reducer case looks good to me." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T17:11:25.453", "Id": "270498", "ParentId": "270379", "Score": "2" } } ]
{ "AcceptedAnswerId": "270498", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T08:51:38.317", "Id": "270379", "Score": "2", "Tags": [ "ecmascript-6", "react.js", "redux" ], "Title": "Filter Options in React" }
270379
<p>I'm learning rust (coming from C++) and playing around with different small algorithms to understand the ownership &amp; borrowing concepts better. Currently, I'm having difficulties finding the idiomatic way to reuse a Vector after iterating over it in a for-loop. This is the (very verbose) code I currently have:</p> <pre><code>fn build_trie(paths: &amp;Vec&lt;String&gt;) -&gt; TreeNode { let mut root = TreeNode::new('\0'); for path in paths { // start at the root node let mut current_node = &amp;mut root; for ch in path.as_bytes() { let ch = *ch as char; println!(&quot;Current char: {}&quot;, ch); let length: i32 = current_node.children.len() as i32; let mut found_child = false; // for each child of the current node, check if the current character matches for i in 0..length as usize { // found a match, descend into the tree if current_node.children[i].get_value() == ch { println!(&quot;Found matching char: {}&quot;, ch); found_child = true; // avoid adding a new child later current_node.children[i].increment_count(); current_node = &amp;mut current_node.children[i]; break; } found_child = false; } // no matching child found, add a new child // and descend into the tree if !found_child { let new_node = TreeNode::new(ch); current_node.children.push(new_node); current_node = current_node.children.last_mut().unwrap(); } } } root } </code></pre> <p>While this does seem to work, I wanted to replace the <code>for i in 0..length</code> header with <code>for child in current_node.children.iter_mut()</code>. The problem is that this does a mutable borrow of <code>current_node.children</code> which also happens in the last if-statement, which obviously isn't allowed twice. I have the feeling that I'm missing some simple detail. I did a lot of googling but couldn't find anything that answered my question.</p> <p>PS: I'm not sure if this question is for Code Review or StackOverflow. But since it might be opinion-based (and those get closed immediately...) I thought I'd try here first.</p>
[]
[ { "body": "<p>welcome to the Rust community.</p>\n<p>Rust's borrow checker analyzes the control flow of your code. However, it does not take into account the state of your variables (<code>current_node</code> and <code>found_child</code> in your example). That would be something like symbolic execution.</p>\n<p>Instead, the borrow checker is pessimistic and it checks your <code>if !found_child</code> for conflicts with the part that sets <code>found_child = true</code>.</p>\n<p>I suggest you use an iterator to find a child that the current character matches, and then work with indices to manipulate the trie. This way, you still get the performance benefits of iterators:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(Debug)]\nstruct TreeNode {\n ch: char,\n count: u32,\n children: Vec&lt;TreeNode&gt;,\n}\n\nimpl TreeNode {\n fn new(ch: char) -&gt; Self {\n Self {\n ch,\n count: 0,\n children: vec![],\n }\n }\n\n fn get_value(&amp;self) -&gt; char { self.ch }\n\n fn increment_count(&amp;mut self) { self.count += 1; }\n}\n\nfn build_trie(paths: &amp;Vec&lt;String&gt;) -&gt; TreeNode {\n let mut root = TreeNode::new('\\0');\n for path in paths {\n // start at the root node\n let mut current_node = &amp;mut root;\n for ch in path.as_bytes() {\n let ch = *ch as char;\n println!(&quot;Current char: {}&quot;, ch);\n // for each child of the current node, check if the current character matches\n let maybe_found = current_node.children.iter_mut().position(|child|\n child.get_value() == ch\n );\n match maybe_found {\n Some(index) =&gt; {\n println!(&quot;Found matching char: {}&quot;, ch);\n current_node.children[index].increment_count();\n current_node = &amp;mut current_node.children[index];\n }\n None =&gt; {\n let new_node = TreeNode::new(ch);\n current_node.children.push(new_node);\n current_node = current_node.children.last_mut().unwrap();\n }\n }\n }\n }\n root\n}\n\nfn main() {\n let paths = vec![&quot;abc&quot;.to_string(), &quot;abd&quot;.to_string()];\n let trie = build_trie(&amp;paths);\n println!(&quot;{:?}&quot;, trie);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T20:48:58.667", "Id": "534182", "Score": "0", "body": "That makes sense. I think I have to learn to make use of a more functional programming style. Thank you very much!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T08:59:16.313", "Id": "270463", "ParentId": "270380", "Score": "1" } } ]
{ "AcceptedAnswerId": "270463", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T09:59:37.053", "Id": "270380", "Score": "3", "Tags": [ "beginner", "rust", "trie" ], "Title": "Building a trie from a vector of strings in Rust" }
270380
<p>The following is a put controller I wrote to update a document.</p> <p>What I am updating is a particular array in the Model: The <code>issues</code> array. The schema for the Model is given below.</p> <p>It works and updates the <code>issues</code> array of the document.:</p> <ol> <li><p><strong>If the array gets very big</strong>, would using the <code>updateOne</code> method be, somehow, negatively affect the performance. I feel like updating the entire document just to update an object inside an array is not necessary.</p> </li> <li><p>If there is a better way to do this.</p> </li> </ol> <pre><code>app.route('/api/issues/:project') .put(async function (req, res){ let project = req.params.project; if (!req.body._id) { return res.status(200).json({ error: 'missing _id' }) } try{ // Find if project with this name exists let existingProject = await Project.findOne({name: project}).lean(); //If project does not exist, return if (!existingProject) { return res.status(200).json({ error: 'could not update', _id: req.body._id }) } // If project exists, get the issues from array let issues = existingProject.issues; // Find index of object in array let index = issues.findIndex(obj =&gt; obj._id.toString() == req.body._id); // If issue does not exist, return if (index === -1) { return res.status(200).json({ error: 'could not update', _id: req.body._id }) } // Filter req.body to remove fields that are empty let updateObj = {...req.body} Object.keys(req.body).map(key =&gt; { if (!req.body[key]) { delete updateObj[key] } }) // If the the only thing left after filtering is the id, return if (Object.keys(updateObj).length &lt;= 1 &amp;&amp; updateObj._id) { return res.status(200).json({ error: 'no update field(s) sent', _id: req.body._id }) } // Update object issues[index] = { ...issues[index], ...updateObj }; // Save the updated object await Project.updateOne({_id: existingProject._id}, existingProject); // If Project exists, return its issue array return res.status(200).json({ result: 'successfully updated', _id: req.body._id }); } catch(err) { // Return error return res.status(500).json(err); } }) </code></pre> <p>The Schema:</p> <pre><code>const ProjectSchema = new Schema({ name: { type: String, required: [true, &quot;Path `project name` is required.&quot;] }, issues: [ { _id: Schema.Types.ObjectId, issue_title: { type: String, required: [true, &quot;required field(s) missing&quot;] }, issue_text: { type: String, required: [true, &quot;required field(s) missing&quot;] }, created_on: String, updated_on: String, created_by: { type: String, required: [true, &quot;required field(s) missing&quot;] }, assigned_to: String, open: Boolean, status_text: String } ] }) const Project = mongoose.model('Project', ProjectSchema); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T11:22:22.300", "Id": "270382", "Score": "0", "Tags": [ "performance", "mongodb", "express.js", "mongoose" ], "Title": "Updating an array inside a document using Mongoose and ExpressJS" }
270382
<p>This is follow-up on <a href="https://codereview.stackexchange.com/questions/220557/sql-odbc-bind-to-c-classes-row-wise">SQL (ODBC) bind to C++ classes row-wise</a></p> <p>The main idea behind this code is to minimize the number of ODBC API calls, because profiling shows significant amount of time is spent in intermediate layers (not waiting for IO). <a href="https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/row-wise-binding?view=sql-server-ver15" rel="nofollow noreferrer">ODBC supports bulk processing</a>, but it requires all buffers to be in-place (see picture at link), so I can't bind to <code>std::string</code> directly and I need to transform my domain objects to flat memory layout.</p> <p>There are 3 minor problems with this code marked with <code>// (A)</code>, <code>// (B)</code> and <code>// (C)</code>:</p> <ul> <li>(A): this two fold expressions only compiles with GCC and pre-release MSVC. Any suggestions for Clang?</li> <li>(B): I didn't find an easy way to infer this type from parameter pack.</li> <li>(C): This class exists only to differentiate between SQL parameters and SQL columns parameters pack.</li> </ul> <pre><code>namespace details { enum class bind_type { defaultType, timestamp, }; template &lt;typename T, typename V&gt; struct bind_desc { // using owner_type = V; using type = T; std::size_t size/* = 1 / 0*/; T V::* value; bind_type odbcType; }; #pragma region dto struct ts_dto { SQL_TIMESTAMP_STRUCT buf; SQLLEN len; static constexpr SQLSMALLINT sql_c_type = SQL_C_TYPE_TIMESTAMP; static constexpr SQLSMALLINT sql_type = SQL_TYPE_TIMESTAMP; std::string toValue() const { return len == sizeof buf ? TimestampToString(buf) : (_ASSERT(len == SQL_NULL_DATA), std::string{}); } void fromValue(std::string_view v) { buf = StringToTimestamp(v); if (IsNullTimestamp(buf)) len = SQL_NULL_DATA; else len = sizeof (SQL_TIMESTAMP_STRUCT); } }; struct ts_nn_dto { SQL_TIMESTAMP_STRUCT buf; static constexpr SQLSMALLINT sql_c_type = SQL_C_TYPE_TIMESTAMP; static constexpr SQLSMALLINT sql_type = SQL_TYPE_TIMESTAMP; std::string toValue() const { return TimestampToString(buf); } void fromValue(std::string_view v) { buf = StringToTimestamp(v); } }; template &lt;std::size_t col_size&gt; struct string_dto { char buf[col_size]; SQLLEN len; static constexpr SQLSMALLINT sql_c_type = SQL_C_CHAR; static constexpr SQLSMALLINT sql_type = SQL_VARCHAR; std::string toValue() const { // bufferSize &gt;= gotlength or is null _ASSERTE(col_size - 1u &gt;= std::size_t(len) || len == SQL_NULL_DATA); std::string ret; if (len != SQL_NULL_DATA) { _ASSERT(len &gt;= 0); // len - the length of the data before truncation because of the data buffer being too small ret.assign(buf, std::clamp&lt;std::size_t&gt;(len, 0, col_size - 1u)); } return ret; } void fromValue(std::string_view v) { _ASSERT(sizeof buf &gt;= v.size()); // throw? len = v.copy(buf, sizeof buf); } }; struct long_nn_dto { long buf; static constexpr SQLSMALLINT sql_c_type = SQL_C_SLONG; static constexpr SQLSMALLINT sql_type = SQL_INTEGER; long toValue() const { return buf; } void fromValue(long v) { buf = v; } }; struct long_dto { long buf; SQLLEN len; static constexpr SQLSMALLINT sql_c_type = SQL_C_SLONG; long toValue() const { return len == sizeof buf ? buf : (_ASSERT(len == SQL_NULL_DATA), 0); } }; #pragma endregion template &lt;typename T, std::size_t col_size, bind_type odbcType&gt; consteval auto to_dto() { if constexpr (std::is_same_v&lt;T, std::string&gt;) { if constexpr (odbcType == bind_type::timestamp) { if constexpr (col_size == 0) return ts_nn_dto{}; else return ts_dto{}; } else return string_dto&lt;col_size + 1&gt;{}; // + '\0' } else if constexpr (std::is_same_v&lt;T, long&gt;) { if constexpr (col_size == 0) return long_nn_dto{}; else return long_dto{}; } else static_assert(dependent_false&lt;T&gt;, &quot;implement dto for T&quot;); } template &lt;bind_desc Col&gt; using to_dto_t = decltype(to_dto&lt;typename decltype(Col)::type, Col.size, Col.odbcType&gt;()); template&lt;typename x&gt; concept has_len_member = requires { &amp;x::len; }; template &lt;typename dto&gt; bool BindCol(SQLHSTMT stmt, SQLUSMALLINT n, dto&amp; dto_column) { SQLPOINTER buf_ptr = [&amp;] { if constexpr (std::is_array_v&lt;decltype(dto_column.buf)&gt;) return dto_column.buf; else return &amp;dto_column.buf; }(); SQLLEN* len_ptr = [&amp;]() -&gt; SQLLEN* { if constexpr (details::has_len_member&lt;dto&gt;) return &amp;dto_column.len; else return nullptr; }(); const SQLRETURN rc = ::SQLBindCol(stmt, n, dto::sql_c_type, buf_ptr, sizeof dto_column.buf, len_ptr); //show_v&lt;sizeof dto_column.buf&gt;{}; return rc == SQL_SUCCESS; } ///////////////////////////////////////////////////////////// template &lt;typename T, std::size_t col_size, bind_type odbcType&gt; consteval auto to_param_dto() { if constexpr (std::is_same_v&lt;T, std::string&gt;) { if constexpr (odbcType == bind_type::timestamp) { if constexpr (col_size == 0) return ts_nn_dto{}; else return ts_dto{}; } else return string_dto&lt;col_size&gt;{}; } else if constexpr (std::is_same_v&lt;T, long&gt;) { if constexpr (col_size == 0) return long_nn_dto{}; else static_assert(dependent_false&lt;T&gt;, &quot;nullable long param not implemented&quot;); } else static_assert(dependent_false&lt;T&gt;, &quot;implement dto for T&quot;); } template &lt;bind_desc Par&gt; using to_param_dto_t = decltype(to_param_dto&lt;typename decltype(Par)::type, Par.size, Par.odbcType&gt;()); template &lt;typename dto&gt; bool BindParam(SQLHSTMT stmt, SQLUSMALLINT n, dto&amp; dto_column) { SQLPOINTER buf_ptr = [&amp;] { if constexpr (std::is_array_v&lt;decltype(dto_column.buf)&gt;) return dto_column.buf; else return &amp;dto_column.buf; }(); SQLLEN* len_ptr = [&amp;] { if constexpr (details::has_len_member&lt;dto&gt;) return &amp;dto_column.len; else return nullptr; }(); const SQLRETURN rc = ::SQLBindParameter(stmt, n, SQL_PARAM_INPUT, dto::sql_c_type, dto::sql_type, /*col_size*/sizeof dto_column.buf, /*scale*/0, buf_ptr, 0, len_ptr); return rc == SQL_SUCCESS; } } template&lt;typename V = void, details::bind_desc... Cols&gt; class OdbcBinder // (C) { template&lt;typename P, details::bind_desc... Par&gt; static auto BindParams(COdbc&amp; odbc, SQLHSTMT stmt, const std::vector&lt;P&gt;&amp; v) { using DTOProw = tuple&lt;details::to_param_dto_t&lt;Par&gt;...&gt;; static_assert(std::is_trivial_v&lt;DTOProw&gt; &amp;&amp; std::is_standard_layout_v&lt;DTOProw&gt;); std::unique_ptr&lt;DTOProw[]&gt; res = std::make_unique_for_overwrite&lt;DTOProw[]&gt;(v.size()); constexpr auto ConvertParam = []&lt;std::size_t... I&gt; (DTOProw&amp; dto, const P&amp; t, std::index_sequence&lt;I...&gt;) { ((get&lt;I&gt;(dto).fromValue(t.*(Par.value))), ...); // (A) }; constexpr auto is = std::make_index_sequence&lt;sizeof...(Par)&gt;{}; for (std::size_t i = 0; i &lt; v.size(); ++i) ConvertParam(res[i], v[i], is); SQLUSMALLINT N = 0; apply( [&amp;](auto&amp;... dto_row) { if (!(details::BindParam(stmt, ++N, dto_row) &amp;&amp; ...)) throw ODBCException(&quot;OB: SQLBindParameter&quot;, SQL_ERROR, odbc.LogLastError(stmt)); }, res[0]); return res; } static void Exec(COdbc&amp; odbc, SQLHSTMT stmt, std::string_view query) { SQLRETURN rc = ::SQLExecDirect(stmt, (SQLCHAR*)query.data(), static_cast&lt;SQLINTEGER&gt;(query.size())); if (!SQL_SUCCEEDED(rc)) { throw ODBCException(&quot;OB: SQLExecDirect&quot;, rc, odbc.LogLastError(stmt)); } } static std::vector&lt;V&gt; GetQueryResultInternal(COdbc&amp; odbc, SQLHSTMT stmt, std::string_view query, SQLULEN limit, SQLULEN batchSize) { using DTOrow = tuple&lt;details::to_dto_t&lt;Cols&gt;...&gt;; //show&lt;DTOrow&gt;{}; constexpr SQLULEN default_batch_size = 32 * 1024 / sizeof(DTOrow); // 32 kb at least if (batchSize == 0) batchSize = limit != 0 &amp;&amp; limit &lt; default_batch_size ? limit : default_batch_size; static_assert(std::is_trivial_v&lt;DTOrow&gt; &amp;&amp; std::is_standard_layout_v&lt;DTOrow&gt;); static_assert(std::is_nothrow_move_constructible_v&lt;V&gt;); // for fast std::vector reallocation SQLRETURN rc; if (limit != 0) { rc = ::SQLSetStmtAttr(stmt, SQL_ATTR_MAX_ROWS, (SQLPOINTER)limit, SQL_IS_UINTEGER); _ASSERT(rc == 0); if (rc != SQL_SUCCESS) odbc.LogLastError(stmt); } Exec(odbc, stmt, query); const std::unique_ptr&lt;DTOrow[]&gt; mem = std::make_unique_for_overwrite&lt;DTOrow[]&gt;(batchSize); //std::span&lt;DTOrow&gt; rowArray(mem.get(), batchSize); SQLULEN numRowsFetched = 0; rc = ::SQLSetStmtAttr(stmt, SQL_ATTR_ROW_ARRAY_SIZE, (SQLPOINTER)batchSize, SQL_IS_UINTEGER); _ASSERT(rc == 0); rc = ::SQLSetStmtAttr(stmt, SQL_ATTR_ROW_BIND_TYPE, (SQLPOINTER)sizeof(DTOrow), SQL_IS_UINTEGER); _ASSERT(rc == 0); rc = ::SQLSetStmtAttr(stmt, SQL_ATTR_ROWS_FETCHED_PTR, &amp;numRowsFetched, SQL_IS_POINTER); _ASSERT(rc == 0); // Bind columns SQLUSMALLINT N = 0; apply( [&amp;](auto&amp;... dto_row) { if (!(details::BindCol(stmt, ++N, dto_row) &amp;&amp; ...)) throw ODBCException(&quot;OB: SQLBindCol&quot;, SQL_ERROR, odbc.LogLastError(stmt)); }, mem[0]); std::vector&lt;V&gt; results; results.reserve(batchSize); constexpr auto Convert = []&lt;std::size_t... I&gt;(const DTOrow &amp; t, std::index_sequence&lt;I...&gt;) -&gt; V { V value; ((value.*(Cols.value) = get&lt;I&gt;(t).toValue()), ...); // (A) return value; }; constexpr auto is = std::make_index_sequence&lt;sizeof...(Cols)&gt;{}; do { while (SQL_SUCCEEDED((rc = ::SQLFetch(stmt)))) { if (rc == SQL_SUCCESS_WITH_INFO) odbc.LogLastError(stmt); for (SQLUINTEGER i = 0; i &lt; numRowsFetched; ++i) { results.emplace_back(Convert(mem[i], is)); } } if (rc != SQL_NO_DATA) { throw ODBCException(&quot;OB: SQLFetch&quot;, rc, odbc.LogLastError(stmt)); } } while (SQL_SUCCEEDED((rc = ::SQLMoreResults(stmt)))); if (rc != SQL_NO_DATA) { throw ODBCException(&quot;OB: SQLMoreResults&quot;, rc, odbc.LogLastError(stmt)); } if (results.capacity() &gt; results.size() * 3) results.shrink_to_fit(); return results; } public: OdbcBinder() = delete; OdbcBinder(const OdbcBinder&amp;) = delete; OdbcBinder(OdbcBinder&amp;&amp;) = delete; template&lt;typename P, details::bind_desc... Par&gt; static void ExecuteWithParams(COdbc&amp; odbc, const std::vector&lt;P&gt;&amp; v, std::string_view query) { autoHSTMT stmt{ odbc.GetHstmt() }; auto pDto = BindParams&lt;P, Par...&gt;(odbc, stmt, v); Exec(odbc, stmt, query); SQLRETURN rc; while (SQL_SUCCEEDED((rc = ::SQLMoreResults(stmt)))) /* empty */; if (rc != SQL_NO_DATA) { throw ODBCException(&quot;OB: SQLMoreResults&quot;, rc, odbc.LogLastError(stmt)); } } template&lt;typename P, details::bind_desc... Par&gt; static std::vector&lt;V&gt; GetQueryResultWithParams(COdbc&amp; odbc, const std::vector&lt;P&gt;&amp; v, std::string_view query, SQLULEN limit = 0, SQLULEN batchSize = 0) { autoHSTMT stmt{ odbc.GetHstmt() }; auto pdto = BindParams&lt;P, Par...&gt;(odbc, stmt, v); return GetQueryResultInternal(odbc, stmt, query, limit, batchSize); } static std::vector&lt;V&gt; GetQueryResult(COdbc&amp; odbc, std::string_view query, SQLULEN limit = 0, SQLULEN batchSize = 0) { autoHSTMT stmt{ odbc.GetHstmt() }; return GetQueryResultInternal(odbc, stmt, query, limit, batchSize); } }; namespace details { template&lt;typename T&gt; concept not_varsize = std::integral&lt;T&gt; || std::floating_point&lt;T&gt; || std::same_as&lt;T, SQL_TIMESTAMP_STRUCT&gt;; } template &lt;typename V&gt; consteval auto sized(std::string V::* ptr, std::size_t col_size) { return details::bind_desc&lt;std::string, V&gt;{ col_size, ptr }; } template &lt;details::not_varsize T, typename V&gt; consteval auto not_null(T V::* ptr) { return details::bind_desc&lt;T, V&gt;{ 0, ptr }; } template &lt;details::not_varsize T, typename V&gt; consteval auto nullable(T V::* ptr) { return details::bind_desc&lt;T, V&gt;{ 1, ptr }; } template &lt;typename V&gt; consteval auto not_null_ts(std::string V::* ptr) { return details::bind_desc&lt;std::string, V&gt;{ 0, ptr, details::bind_type::timestamp }; } template &lt;typename V&gt; consteval auto nullable_ts(std::string V::* ptr) { return details::bind_desc&lt;std::string, V&gt;{ 1, ptr, details::bind_type::timestamp }; } </code></pre> <p>Usage example:</p> <pre class="lang-cpp prettyprint-override"><code>struct Incident { long id; std::string name; std::string comments; /* ... */ std::string timeSend; std::string timeClosed; long num; }; int main() { auto odbc = COdbc{}; // create connection, etc std::vector&lt;Incident&gt; vec = OdbcBinder&lt;Incident // (B) , not_null(&amp;Incident::id) , sized(&amp;Incident::name, 25) , sized(&amp;Incident::comments, 100) , not_null_ts(&amp;Incident::timeSend) , nullable_ts(&amp;Incident::timeClosed) , nullable(&amp;Incident::num) &gt;::GetQueryResult(odbc, &quot;select ID, COMMENTS, &quot; /* ... */ &quot;TIME_CLOSED from INCIDENTS&quot;); OdbcBinder&lt;&gt;::ExecuteWithParams&lt;Incident // (B) , not_null(&amp;Incident::id) , sized(&amp;Incident::name, 25) , sized(&amp;Incident::comments, 100) , not_null_ts(&amp;Incident::timeSend) , nullable_ts(&amp;Incident::timeClosed) &gt;(odbc, vec, &quot;insert into INCIDENTS values (?, ?, ?, ?, ?)&quot;); } </code></pre> <p>Full code with ODBC API stubs: <a href="https://godbolt.org/z/c9oxq7GMc" rel="nofollow noreferrer">https://godbolt.org/z/c9oxq7GMc</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T15:54:52.273", "Id": "533922", "Score": "0", "body": "Are there some missing `#include` lines that got missed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T19:03:48.607", "Id": "533933", "Score": "0", "body": "Which version of Clang did you try?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T22:37:46.770", "Id": "533946", "Score": "0", "body": "@TobySpeight Full code with includes and API stubs on godbolt link in the end. Odbc includes are platform dependant and std imports are namespace qualified and obvious (string/vector/type_traits). The only missing code is trivially constructible tuple (included in linked code), but have same API as `std::tuple` and irrelevant to the topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T22:44:39.603", "Id": "533948", "Score": "0", "body": "@G.Sliepen 13.0 and godbolt trunk (`clang version 14.0.0 (https://github.com/llvm/llvm-project.git 7bd87a03fdf1559569db1820abb21b6a479b0934)`). You can open clang tab on the right and look at errors. `<source>:518:27: error: member reference base type 'details::bind_desc' is not a structure or union\n ((value.*(Cols.value) = get<I>(t).toValue()), ...);` and `<source>:447:44: error: member reference base type 'details::bind_desc' is not a structure or union\n ((get<I>(dto).fromValue(t.*(Par.value))), ...); // (A)`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T14:51:29.310", "Id": "270384", "Score": "2", "Tags": [ "c++", "c++20", "odbc" ], "Title": "SQL (ODBC) bind to C++ classes row-wise (follow-up)" }
270384
<p>This question is a supplement to my previous question: <a href="https://codereview.stackexchange.com/questions/270323/counting-absolute-nesting-levels-of-an-iterable">Counting 'absolute' nesting levels of an iterable</a>.</p> <p>I would like to expand functionality of counting nests in order to get values from given nest. I created 2 examples:</p> <pre class="lang-py prettyprint-override"><code>dct_test = { &quot;a&quot;: {1: 2, 2: 3, 3: 4}, &quot;b&quot;: {&quot;x&quot;: &quot;y&quot;, &quot;z&quot;: [1, 2, 3, {7, 8}]}, &quot;c&quot;: {&quot;l&quot;: (2, 3, 5), &quot;j&quot;: {&quot;a&quot;: {&quot;k&quot;: 1, &quot;l&quot;: [1, 3, (2, 7, {&quot;x&quot;: 1})]}}}, &quot;d&quot;: [1, (2, 3)], &quot;e&quot;: 5 } tpl_test = (1, [3, 4, {5, 6, 7}], {&quot;a&quot;: 5, &quot;b&quot;: [9, 8]}, 2) </code></pre> <p>Picture below shows an algorithm of counting with values that should be returned from each level: <a href="https://i.stack.imgur.com/JzWHt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JzWHt.png" alt="Algorithm" /></a></p> <p>Here's code:</p> <pre class="lang-py prettyprint-override"><code>from collections.abc import Iterable from itertools import chain # EXAMPLES dct_test = { &quot;a&quot;: {1: 2, 2: 3, 3: 4}, &quot;b&quot;: {&quot;x&quot;: &quot;y&quot;, &quot;z&quot;: [1, 2, 3, {7, 8}]}, &quot;c&quot;: {&quot;l&quot;: (2, 3, 5), &quot;j&quot;: {&quot;a&quot;: {&quot;k&quot;: 1, &quot;l&quot;: [1, 3, (2, 7, {&quot;x&quot;: 1})]}}}, &quot;d&quot;: [1, (2, 3)], &quot;e&quot;: 5 } tpl_test = (1, [3, 4, {5, 6, 7}], {&quot;a&quot;: 5, &quot;b&quot;: [9, 8]}, 2) # FUNCTIONS # converting a collection to a list def ConvertIterableToList( coll: Iterable, ): # check if argument is a collection if isinstance(coll, (tuple, list, set, dict)): # if the argument is a tuple or set - convert to list if isinstance(coll, (tuple, set)): return list(coll) # if the argument is a dictionary - get values of a dictionary and convert them to list elif isinstance(coll, dict): return list(coll.values()) # if the argument is a list - return collection elif isinstance(coll, list): return coll else: raise TypeError(&quot;Given argument is not a list, tuple, set or dictionary&quot;) # author: FMc # https://codereview.stackexchange.com/a/270335/252081 def GetIterDepth( coll: Iterable, ): # returning coll if it's a tuple, list or set # returning values of dictionary if coll is dict # returning None if coll is not a collection iter_to_inspect = ( coll if isinstance(coll, (tuple, list, set)) else coll.values() if isinstance(coll, dict) else None ) # # 0 means coll is not a collection at all # # 1 means coll has no nests # # 1 + max(...) means coll has nested collections # iterate over iter_to_inspect in order to get one level deeper # recursion is needed to inspect deeper nests # max() stores result for each case of a collections inside a collection # 1 is a kind incrementator/counter for looping over collections inside a collection return ( 0 if iter_to_inspect is None else 1 if not iter_to_inspect else 1 + max(GetIterDepth(i) for i in iter_to_inspect) ) # returns a list of collections extracted from a collection def PeelIter( coll: Iterable ): if isinstance(coll, (tuple, list, set, dict)): return [i for i in ConvertIterableToList(coll) if isinstance(i, (tuple, list, set, dict))] else: raise TypeError(&quot;Given argument is not a list, tuple, set or dictionary&quot;) # returns a collection from a given level def GetItersFromLevel( coll: Iterable, level: int ): # argument must be a collection - error otherwise if not isinstance(coll, (tuple, list, set, dict)): raise TypeError(&quot;Given argument is not a list, tuple, set or dictionary&quot;) # maximum number of nests (levels) inside a collection n_levels = GetIterDepth(coll) # level cannot be equal to 0 or less if level &lt; 1: raise ValueError(f&quot;Given level ({level}) is not greater or equal 1.&quot;) # level cannot be greater than maximum number of levels if level &gt; n_levels: raise ValueError(f&quot;Given level ({level}) is bigger than maximum number of levels \ in a collection ({n_levels}).&quot;) # if level is 1 - no computation is needed - simply return a collection if level == 1: # if coll is dict return only values if isinstance(coll, dict): return list(coll.values()) else: return coll # if level if greater than one else: # assuming function needs to return at least 2nd level # we have to &quot;peel&quot; a collection at start iter_to_inspect = PeelIter(coll) # looping as many times as deep is a collection # in order to avoid recursion or indefinite while loop # we can start from 2 as there's no need to inspect 1st level # we have to add 1 to n_levels because range(from, to) ends at (to - 1) for i in range(2, n_levels + 1): # if i is less than given level we have to continue peeling if i &lt; level: # peeling iter_to_inspect as well as j is needed because: # 1. peeling iter_to inspect returns list of collections inside iter_to_inspect # 2. peeling j returns collections from elements inside list of collections # # from peeled iter_to_inspect # iter_to_inspect returns list of lists containing single collections # flattening is needed because otherwise function would constantly iterate # # over the same peeled collection iter_to_inspect = \ list(chain.from_iterable([PeelIter(j) for j in PeelIter(iter_to_inspect)])) else: return iter_to_inspect print(&quot;1st level: &quot;, GetItersFromLevel(dct_test, 1)) # returns dct_test.values() so it's correct print(&quot;2nd level: &quot;, GetItersFromLevel(dct_test, 2)) print(&quot;3rd level: &quot;, GetItersFromLevel(dct_test, 3)) print(&quot;4th level: &quot;, GetItersFromLevel(dct_test, 4)) print(&quot;5th level: &quot;, GetItersFromLevel(dct_test, 5)) print(&quot;6th level: &quot;, GetItersFromLevel(dct_test, 6)) print(&quot;7th level: &quot;, GetItersFromLevel(dct_test, 7)) print(&quot;8th level: &quot;, GetItersFromLevel(dct_test, 8), &quot;\n&quot;) # error print(&quot;1st level: &quot;, GetItersFromLevel(tpl_test, 1)) print(&quot;2nd level: &quot;, GetItersFromLevel(tpl_test, 2)) print(&quot;3rd level: &quot;, GetItersFromLevel(tpl_test, 3)) print(&quot;4th level: &quot;, GetItersFromLevel(tpl_test, 4)) #error </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code>1st level: [{1: 2, 2: 3, 3: 4}, {'x': 'y', 'z': [1, 2, 3, {8, 7}]}, {'l': (2, 3, 5), 'j': {'a': {'k': 1, 'l': [1, 3, (2, 7, {'x': 1})]}}}, [1, (2, 3)], 5] 2nd level: [{1: 2, 2: 3, 3: 4}, {'x': 'y', 'z': [1, 2, 3, {8, 7}]}, {'l': (2, 3, 5), 'j': {'a': {'k': 1, 'l': [1, 3, (2, 7, {'x': 1})]}}}, [1, (2, 3)]] 3rd level: [[1, 2, 3, {8, 7}], (2, 3, 5), {'a': {'k': 1, 'l': [1, 3, (2, 7, {'x': 1})]}}, (2, 3)] 4th level: [{8, 7}, {'k': 1, 'l': [1, 3, (2, 7, {'x': 1})]}] 5th level: [[1, 3, (2, 7, {'x': 1})]] 6th level: [(2, 7, {'x': 1})] 7th level: [{'x': 1}] Traceback (most recent call last): (...) ValueError: Given level (8) is bigger than maximum number of levels in a collection (7). 1st level: (1, [3, 4, {5, 6, 7}], {'a': 5, 'b': [9, 8]}, 2) 2nd level: [[3, 4, {5, 6, 7}], {'a': 5, 'b': [9, 8]}] 3rd level: [{5, 6, 7}, [9, 8]] Traceback (most recent call last): (...) ValueError: Given level (4) is bigger than maximum number of levels in a collection (3). </code></pre> <p>So, I reached my goal but I think this code, like code for counting nests, can be more neat (@FMc - big thanks). I would be grateful for any tips because I'm rather a beginner. Do you have any?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T19:48:48.973", "Id": "533934", "Score": "1", "body": "Too short for a review. But two minor nitpicks. Your use of Pascal Case is not idomatic to python (functions should use snake_case), nor is your overuse of comments. Please explain your code through 1 modules 2 functions 3 docstring 4 variable names 5 comments. Comments should explain why not how, the algorithm (if terse) _can_ be placed in the docstring." } ]
[ { "body": "<p>Your previous question dealt with counting the number of levels in a nested\ndata structure. This question deals with collecting values from a specific\nlevel (sort of). In both cases, your conceptualization of the problem strikes\nme as somewhat unintuitive, at least based on my experience with languages like\nPerl, Ruby, and Python.</p>\n<p>To help clarify things, let's pretty-print your <code>tpl_test</code> example. I would\nlabel the levels exactly in parallel with the indentation structure. In fact,\nan easy (albeit sloppy) algorithm for counting the levels or determining the\nlevel of any particular value would be to JSON-ify the data structure, pretty\nprint it, and count the spaces on the left margin. Level 0 would mean no\nindentation and would represent the top-level data structure. Level 1 would\nhave an indentation of 4 spaces. And the entire data structure goes up to Level\n3. By contrast, you were counting only two levels for this example. There's no\n&quot;right&quot; answer here, but the approach I'm suggesting seems more congruent with\nthe way that software engineers typically think about the topic. Also, as we\nsaw in my implementation of the <code>depth()</code> function in your previous question,\nthis way of counting the levels composes more simply within a recursive\ncontext.</p>\n<pre><code>( # Level 0\n 1, # Level 1\n [\n 3, # Level 2\n 4,\n {\n 5, # Level 3\n 6,\n 7,\n },\n ],\n {\n &quot;a&quot;: 5,\n &quot;b&quot;: [\n 9,\n 8,\n ],\n },\n 2,\n)\n</code></pre>\n<p>At first I thought that your current question was trying to collect all of the\nvalues at a given level. But that's not what your code is doing. Consider this\nquestion: <em>what are the values at Level 3</em>? My answer would be <code>[5, 6, 7, 9, 8]</code>, which is directly evident from the pretty-printed data structure above.\nYour code's answer is different, for two reasons. First, for the\ncurrent question you are labeling each\nlevel one higher than I am (your Level 3 is my Level 2). In addition, you are\nnot collecting all values at the requested level: all of the values at\nyour-Level-3 (ie, my-Level-2) are <code>[3, 4, {5,6,7}, 5, [9,8]]</code>. But your code\nreturns only a subset of those value -- namely, only the supported collection\ntypes at that level, or <code>[{5,6,7}, [9,8]]</code>. Again, neither approach is right or\nwrong; however, I do think that the approach I'm suggesting is a bit more\nidiomatic.</p>\n<p>So how would one collect the values from a level, as I have framed the problem?\nIt would have the same structure as my <code>depth()</code> implementation. First we have\nto distinguish between three cases: (a) tuple, list, set, (b) dict, or (c)\nsomething else. If something-else, we do nothing. If we're currently at the\ndesired level, we want to collect the values at that level. And if we are not\nyet at the desired level, we want to dive deeper into the structure, using\nrecursion. The tricky part is how to collect values from a recursively\nimplemented function? For example, values can reside at Level 3 in multiple\nplaces within the structure, and we need to collect them all. One easy way to\ndo that is to think of the function as emitting many values rather than\nreturning a single unified answer from one call. That's what Python's <code>yield</code>\ncan do. The function will yield/emit the desired data, and the code calling the\nfunction will glue all of that emitted data into a single list or tuple.</p>\n<pre><code>def get_vals_from_level(obj, level):\n xs = (\n obj if isinstance(obj, (tuple, list, set)) else\n obj.values() if isinstance(obj, dict) else\n None\n )\n if xs is not None:\n if level == 1:\n yield from xs\n else:\n for x in xs:\n yield from get_vals_from_level(x, level - 1)\n\nprint(list(get_vals_from_level(tpl_test, 3))) # [5, 6, 7, 9, 8]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T13:53:35.377", "Id": "534075", "Score": "0", "body": "Thanks. I should be more precise - I need all values from a level **but only if they're collections** and, also, to return **list of them without changing their original form**. That's why my implementation doesn't in fact return all values and doesn't 'flatten' nested collections (```[{5, 6, 7}, [9, 8]]```). Also, from my point of view, 'JSON' interpretation doesn't match with ```depth()``` function (```GetIterDepth()``` in my adjusted code). It counts all nests, so level 0 in 'JSON' interpretation means ```depth()``` equals to 1. Still, big thanks for showing me how to use ```yield```." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T20:22:00.463", "Id": "270393", "ParentId": "270386", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T15:09:40.070", "Id": "270386", "Score": "2", "Tags": [ "python", "beginner" ], "Title": "Getting values from a given level of a nested collection" }
270386
<p>I am new to react and I tried to implement a TODO application using react state and props. I need somebody to just review the code and suggest improvements in the code. Currently I have not added any CSS to it, I am focusing more on react practices. code sandbox link- <a href="https://codesandbox.io/s/adoring-archimedes-se4vm" rel="nofollow noreferrer">https://codesandbox.io/s/adoring-archimedes-se4vm</a></p> <p>App.jsx</p> <pre><code>import './App.css'; import InputForm from './InputForm'; import ShowTODO from './ShowTODO' import Choices from './Choices'; import {useState} from 'react' function App(props) { const [todoList, setTODOList] = useState([]); const [filterName, setFilterName] = useState(&quot;active&quot;); const addTODO = (event, todoInput) =&gt; { // if you do not do this then if form submit is clicked // then page will refresh and everything will go event.preventDefault(); var currentTODO = {&quot;state&quot;: &quot;active&quot;, &quot;data&quot;: todoInput}; var previousTODOList = [...todoList]; previousTODOList.push(currentTODO); setTODOList(previousTODOList); } const updateFilterName = (event) =&gt; { let newFilterName = event.target.value; setFilterName(newFilterName); console.log(todoList); } const updateTODOStatus = (index, newState) =&gt; { let previousTODOList = [...todoList]; previousTODOList[index][&quot;state&quot;] = newState; setTODOList(previousTODOList); } return ( &lt;div className=&quot;App&quot;&gt; &lt;InputForm onSubmit={addTODO}/&gt; &lt;Choices filterName={filterName} onChange={(e) =&gt; updateFilterName(e)}/&gt; &lt;p&gt; {filterName} &lt;/p&gt; &lt;ShowTODO filterName={filterName} todoList={todoList} updateStatus={updateTODOStatus}/&gt; &lt;/div&gt; ); } export default App; </code></pre> <p>Choices.jsx</p> <pre><code>function Choices(props) { return ( &lt;div&gt; &lt;select value={props.filterName} onChange={(event)=&gt;props.onChange(event)}&gt; &lt;option value=&quot;active&quot;&gt; Show active to do &lt;/option&gt; &lt;option value=&quot;completed&quot;&gt; Show completed to do &lt;/option&gt; &lt;option value=&quot;all&quot;&gt; Show all to do &lt;/option&gt; &lt;/select&gt; &lt;/div&gt; ); } export default Choices; </code></pre> <p>InputForm.jsx</p> <pre><code>import './App.css'; import {useState} from 'react' function InputForm(props) { const [todoInput, setTODOInput] = useState(&quot;&quot;); const addTODO = (event)=&gt;{ props.onSubmit(event, todoInput); } const updateInputValue = (event) =&gt; { setTODOInput(event.target.value); } return ( &lt;div className=&quot;InputForm&quot;&gt; &lt;form onSubmit={addTODO}&gt; &lt;input type=&quot;text&quot; name=&quot;todo-input&quot; id=&quot;todo-input&quot; value={todoInput} onChange={(event)=&gt;updateInputValue(event)} /&gt; &lt;button&gt; Add To Do &lt;/button&gt; &lt;/form&gt; &lt;/div&gt; ); } export default InputForm; </code></pre> <p>ShowTODO.jsx</p> <pre><code>function ShowTODO(props) { return ( &lt;div&gt; { props.todoList.map((todo, index) =&gt; { return ( &lt;div key={index}&gt; {todo.state === &quot;active&quot; &amp;&amp; props.filterName === &quot;active&quot; &amp;&amp; &lt;span&gt; {todo.data} Mark as complete &lt;input type=&quot;checkbox&quot; onClick={()=&gt;props.updateStatus(index, &quot;completed&quot;)}/&gt; &lt;/span&gt; } {todo.state === &quot;completed&quot; &amp;&amp; props.filterName === &quot;completed&quot; &amp;&amp; &lt;span&gt; {todo.data} Mark as active &lt;input type=&quot;checkbox&quot; onClick={()=&gt;props.updateStatus(index, &quot;active&quot;)}/&gt; &lt;/span&gt;} {props.filterName === &quot;all&quot; &amp;&amp; &lt;span&gt; {todo.data} &lt;/span&gt;} &lt;/div&gt; ); }) } &lt;/div&gt; ); } export default ShowTODO; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T19:39:32.150", "Id": "270392", "Score": "2", "Tags": [ "beginner", "react.js", "jsx", "to-do-list" ], "Title": "To-do application in React" }
270392
<p>I'm implementing some simple algorithms (e.g. two-sum) in OCaml and I am unsure why my OCaml solution is running much slower than the equivalent Python version.</p> <p>My OCaml version:</p> <pre class="lang-ml prettyprint-override"><code>open Base let two_sum_hash lst target = let rec loop tbl counter = function | [] -&gt; failwith &quot;No sum found&quot; | x :: xs -&gt; match Hashtbl.find tbl x with | None -&gt; Hashtbl.set tbl ~key:(target - x) ~data:counter; loop tbl (counter+1) xs | Some index -&gt; [index; counter] in loop (Hashtbl.create (module Int)) 0 lst </code></pre> <p>and the Python solution</p> <blockquote> <pre class="lang-py prettyprint-override"><code> def two_sum(lst, target): d = {} for i, x in enumerate(lst): if x in d: return [d[x], i] d[target - x] = I </code></pre> </blockquote> <p>The OCaml version runs in ~2.16 seconds and the Python solution runs in ~1.15 seconds for large inputs (e.g. list of 10⁷ elements).</p> <p>What is the reason for OCaml running slower? Am I doing something wrong in my OCaml solution?</p> <p>I know that dicts are heavily optimised in Python - I wonder how/whether can I make the OCaml code more performant.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T21:16:17.903", "Id": "270395", "Score": "0", "Tags": [ "performance", "algorithm", "ocaml", "k-sum" ], "Title": "OCaml implementation of two-sum" }
270395
<p><a href="https://i.stack.imgur.com/HEF6e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HEF6e.png" alt="example" /></a></p> <p>given a number and two dimensional array the method will check if the number is in the array the array is quadratic circular size n x n and each quarter of the array contains bigger numbers that the previous quarter(picture added)</p> <p>the code i wrote:</p> <pre><code> public static boolean search(int matrix[][], int key) { int start = 0; int ROWS = matrix.length; int COLS = matrix[0].length; int mid, row, col, value; int end = ROWS * COLS - 1; while (start &lt;= end) { mid = start + (end - start) / 2; row = mid / COLS; col = mid % COLS; value = matrix[row][col]; if (value == key) return true; if (value &gt; key) end = mid - 1; else start = mid + 1; } return false; } </code></pre> <p>my goal is to make this code as efficient as possible in terms of time complexity,can you help me to improve it? and what time complexity is it right now? (o)log n^2?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T02:39:20.150", "Id": "533959", "Score": "1", "body": "Given that the 2d array is not sorted either vertically or horizontally, how can a binary search that treats the input as a single array work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T03:44:41.153", "Id": "533960", "Score": "0", "body": "(@EricStein: looks trivial enough to successfully implement.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T03:49:22.477", "Id": "533961", "Score": "1", "body": "Welcome to Code Review@SE. Please implement a minimum of tests - Is each of the values present found? What's the result for a value *not* in the array? Please state whether array sizes always are powers of 2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T13:30:55.753", "Id": "534003", "Score": "0", "body": "iv`e said the array is quadratic circular size n x n ,you can close the question seems like i`m not getting any real help here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T15:12:14.840", "Id": "534014", "Score": "0", "body": "@greybeard comment indicates we would like to see the code that calls this code. We need to know that the code is working as intended, there are other [sites](https://meta.stackexchange.com/questions/129598/which-computer-science-programming-stack-exchange-sites-do-i-post-on) that can help you debug. If you add code that shows the testing this is a great question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T15:24:30.307", "Id": "534017", "Score": "0", "body": "Unfortunately, the code is not working as intended. For the suggested matrix, `search(matrix, 4)` returns false. So does `search(matrix, 6)`. The code has implemented a binary search, but the input matrix is not sorted. Binary search won't work on unsorted input. I think that this code can be modified to work in `O(n log n)` time, but it's not a one-line fix." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T15:41:34.120", "Id": "534019", "Score": "0", "body": "theoretically can you elaborate how to reach O(n log n)? , I need start from one quarter and based on the answer narrow to the other quarters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T15:53:21.653", "Id": "534020", "Score": "0", "body": "The data in each column is sorted vertically. Walk each column (O(n)) and binary search on it for your result (O(log n))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T15:57:28.487", "Id": "534021", "Score": "0", "body": "oh i understand,thank you" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T21:37:29.260", "Id": "270396", "Score": "0", "Tags": [ "java", "performance", "array" ], "Title": "finding a value in circular two dimensional array" }
270396
<p>take an array of two numbers who are not necessarily in order, and then add not just those numbers but any numbers in between. For example, [3,1] will be the same as 1+2+3 and not just 3+1.</p> <pre><code>function sumAll(arr) { let start = arr[0]; let end = arr[1]; if (start &gt; end) { let temp = start; start = end; end = temp; } return getSum(start, end); } function getSum(start, end) { if (start === end) return start; return end + getSum(start, end-1); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T09:27:43.393", "Id": "533977", "Score": "3", "body": "There's absolutely no reason to use recursion for this. What is this code used for? Is this a school assignment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T10:06:09.490", "Id": "533986", "Score": "1", "body": "For `[n,m]` the sum of all integers among `n` and `m` would be `(m-n+1) . (n+m) / 2` where `m > n`." } ]
[ { "body": "<h2>Recursion</h2>\n<p>Recursion in JavaScript is just a toy and should be avoided when ever possible.</p>\n<p><strong>Why?</strong></p>\n<ul>\n<li><p>Untrustable. JavaScript has a very limited call stack and recursive code can quickly consume the call stack. For example <code>getSum(1, 10000)</code> will overflow the call stack and throw an error.</p>\n<p>Example showing call-stack overflow.</p>\n</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> \nsumAll([0, 10000]);\nfunction getSum(start, end) {\n if (start === end) return start;\n return end + getSum(start, end-1);\n}\nfunction sumAll(arr) {\n let start = arr[0];\n let end = arr[1];\n if (start &gt; end) {\n let temp = start;\n start = end;\n end = temp;\n }\n return getSum(start, end);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ul>\n<li><p>Very Slow. JavaScript does not have proper tail calls, meaning each call requires a call stack operation that captures the call's new context. This is a very slow operation when compared to (in this case) adding two values.</p>\n<p>There is also the overhead of returning which requires yet another call stack (pop) operation</p>\n</li>\n<li><p>Memory hungry. It is very memory inefficient, as it has a minimum storage cost of <span class=\"math-container\">\\$O(n)\\$</span> which in this case is very bad as the task in this case has a storage cost of <span class=\"math-container\">\\$O(1)\\$</span></p>\n</li>\n<li><p>Because of the chance of a thrown error (That can not be predicted) you should always wrap recursive calls inside a <code>try catch</code>. Unfortunately JavaScript, inside and around the try catch (not just inside the <code>try</code>) can not be optimized. It is automatically marked (Do Not Optimize)</p>\n<p>As you are forced to use the try catch to avoid having your code crash the recursion is further degraded by the lack of active optimization.</p>\n</li>\n</ul>\n<h2>Example</h2>\n<p>The code below measures the performance of recursion with try catch, recursion without try catch and a simple while loop.</p>\n<p>The results speak for them selves.</p>\n<p>Recursion in JavaScript should be avoid when ever possible!!!</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getSum(start, end) {\n if (start === end) return start;\n return end + getSum(start, end-1);\n}\nfunction sumAll(arr) {\n let start = arr[0];\n let end = arr[1];\n if (start &gt; end) {\n let temp = start;\n start = end;\n end = temp;\n }\n return getSum(start, end);\n}\nfunction sumAll_Catches(arr) {\n let start = arr[0];\n let end = arr[1];\n if (start &gt; end) {\n let temp = start;\n start = end;\n end = temp;\n }\n try { return getSum(start, end); }\n catch(e) { console.log(e.message); }\n}\n\n/* Uses while loop to get sum */\nfunction sumAll_B([a, b]) { return a &gt; b ? getSum_B(b, a) : getSum_B(a, b) }\nfunction getSum_B(start, end) {\n var sum = start++;\n while (start &lt;= end) { sum += start++ }\n return sum;\n}\n/* for calibrating number of cycles needed to get good test data */\nfunction Calibrator([start, end]) {\n var sum = start++;\n while (start &lt;= end) { sum += start++ }\n return sum;\n}\n\nvar testCount = 500;\nconst testData = [0, 3000];\nfunction Test(name, call, ...data) {\n var i = testCount - 1;\n const now = performance.now();\n while (i--) { call(...data) }\n const res = call(...data);\n const time = performance.now() - now;\n name != \"\" &amp;&amp; console.log(\"Test: \" + name + \" Result: \" + res + \" Time: \" + (time / testCount).toFixed(3) + \"ms per call.\");\n return time;\n}\n\nwhile (Test(\"\", Calibrator, testData) &lt; 2.5) { testCount += 150; }\nconsole.log(\"Cycles per test: \" + testCount);\nconsole.log(\"Test data: [\" + testData + \"]\");\nTest(\"Recursion catch. \", sumAll_Catches, testData);\nTest(\"Recursion ...... \", sumAll, testData);\nTest(\"While loop...... \", sumAll_B, testData);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Summing consecutive numbers</h2>\n<p>There is no need to manually sum a list of numbers as the task has a time complexity of <span class=\"math-container\">\\$O(1)\\$</span> and using a loop is at best <span class=\"math-container\">\\$O(n)\\$</span></p>\n<h2>Rewrite</h2>\n<p>Time and storage <span class=\"math-container\">\\$O(1)\\$</span></p>\n<p>Note that the code is only for positive numbers, but can easily be adapted to include negative values.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function sumAll([a, b]) {\n a = Math.abs(a); /* Only for positive values */\n b = Math.abs(b);\n b &lt; a &amp;&amp; ([a, b] = [b, a]);\n a -= 1; /* To match your original code */\n return b * (b + 1) / 2 - a * (a + 1) / 2;\n}\nconsole.log(sumAll([2, 3000]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T16:48:22.807", "Id": "534023", "Score": "0", "body": "I mostly agree that recursion should be avoided in JS however sometimes it yields to [brilliant code](https://stackoverflow.com/a/55383423/4543207) in a few lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T22:25:35.550", "Id": "534039", "Score": "0", "body": "Kindly at your earliest convenience if you may, what do you think time complexity is [here](https://codereview.stackexchange.com/a/270430/105433)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T14:05:04.713", "Id": "270419", "ParentId": "270400", "Score": "3" } }, { "body": "<p>I am assuming this is a school assignment and an exercise in recursion.\nA short review;</p>\n<ul>\n<li>Its okay to have the recursive function be another function, but I imagine you get extra points for 1 single function</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">Destructuring assignment</a> helps with the signature function</li>\n<li>It's good that your first check in the recursive function is the exit condition</li>\n<li>Instead of swapping within the function, you can just call the function again with swapped arguments, super clear and 3 lines less of code</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function sumRange([a,b]){\n\n if(a==b){\n return a;\n }else if(a&gt;b){\n return sumRange([b,a]);\n }else{\n return b + sumRange([a,b-1]); \n }\n}\n\nconsole.log(sumRange([1,3]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T07:28:28.240", "Id": "270484", "ParentId": "270400", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T01:17:47.680", "Id": "270400", "Score": "2", "Tags": [ "javascript", "recursion" ], "Title": "Arithmetic progression using Recursion" }
270400
<p>This is my first real personal application and I'm just looking for some outside feedback. Completely built in Python, this is a Pokédex for the Pokémon Mystery Dungeon series. I hope to eventually publish to the Android app store. If you choose to check it out... don't be nice. Tell me how bad it is, (just make sure you tell me how to fix it too).</p> <pre><code>import os, json from assets.utilities.pokeapi import api from assets.data.models.pokemon import Pokemon class Version: def __init__(dex, name): dex.basepath = &quot;assets/data/storage/json/&quot; dex.name = name dex.version = dex.getversion() dex.pokemon = dex.version['pokemon'] dex.pokedex = [] def getversion(dex): versionpath = f&quot;{dex.basepath}versions/{dex.name}.json&quot; if os.path.exists(versionpath): with open(versionpath) as file: file = file.read() version = json.loads(file) return version def getpokemon(dex): count = 1 for pokemon in dex.pokemon: dexid = pokemon['dexid'] species = pokemon['species'] path = f&quot;{dex.basepath}pokemon/{species}.json&quot; with open(path) as file: file = file.read() pokemon = json.loads(file) try: typing = pokemon['typing'] abilities = pokemon['abilities'] moveset = pokemon['moveset'] except: stop = len(dex.pokemon) # stop = 9 if count &lt;= stop: data = api.pokemon(dexid, species) print(f'requesting {count} of {stop}') typing = data.typing() abilities = data.abilities() moveset = data.moveset() pokemon.update({'typing': typing, 'abilities': abilities, 'moveset': moveset}) pokemon = json.dumps(pokemon) with open(path, 'w') as file: file.write(pokemon) count += 1 else: break else: pokemon = Pokemon(pokemon) dex.pokedex.append(pokemon) return </code></pre> <p>The rest is GitHub repo: <a href="https://github.com/austenc-id/MysteonDex/tree/b30729041fc2d73df76fc4c574ab653c0ce46e34" rel="nofollow noreferrer">https://github.com/austenc-id/MysteonDex/</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T08:20:09.087", "Id": "533971", "Score": "2", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T09:01:22.323", "Id": "534065", "Score": "2", "body": "Welcome to Code Review! The site's rules require that you embed the code that you wish to be reviewed in the question itself. You can post a GitHub link for supplementary context, but you have posted so little code in the question that the reviews are unlikely to be meaningful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T15:50:45.640", "Id": "534081", "Score": "0", "body": "This question is incomplete, and even your GitHub repo is incomplete. There are no clear entry points, and the code that initializes `storage` is missing." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T04:41:34.333", "Id": "270403", "Score": "1", "Tags": [ "python", "beginner", "pokemon" ], "Title": "Pokédex by a Python novice" }
270403
<p>So to check my Python knowledge I am building a cricket scoreboard in Python. My scoreboard could be able to can be used to store previous matches ' scores. A work in progress as of now. But as of now, it is a 50/50 success. I might have done 50% of the work already, but I am can't move forward. I have my code on GitLab @ <a href="https://gitlab.com/AnantGupta/cricket-scoreboard" rel="nofollow noreferrer">https://gitlab.com/AnantGupta/cricket-scoreboard</a> where there is a python file named <code>main.py</code>. I have added what I have done in <code>README.md</code> and what I am aiming to do in the cricket scoreboard. I am adding comments for you all for having less problem in finding which code does what. Here is what I have done as of now</p> <pre><code>Start a game Can do toss Can calculate runs/wickets/extras/run rate Will store/read every previous score Can remove all the previous score </code></pre> <p>And here is what I am aiming to do</p> <pre><code>Adding batsman's name Add runs and bowls to the batsman Adding bowler name Add runs and wickets to the bowlers Change strike on even runs (1s, 3s, 5s, etc) Change strike after over ends (if the bowl is either dot ball, double, four, six, etc) </code></pre> <p>As of now, I am looking for hints on how I can do to accomplish this stuff. Also, you can look at the code, where you can improve my code. If I like the suggestion I will implement it in my code (You can check my commits on my GitLab).</p> <p>Also english is not my first language so please don't kill me :P</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T07:54:19.093", "Id": "533968", "Score": "1", "body": "Hello at Code Review@SE. Please heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T05:01:49.487", "Id": "270404", "Score": "0", "Tags": [ "python" ], "Title": "Building a Cricket Scoreboard from Python" }
270404
<p>My boss asked me, a <strong>Polar researcher</strong> whose major is biology (surprise!), to do a coding work which I am NOT really good at, for our satelite data processing module. (I'm not even sure why he asked me to do this in the first place...sigh...corporate culture)</p> <p>He said</p> <ol> <li><p>his codes have methods but no class so he'd appreciate if I &quot;assemble&quot; it under a class named nc_methods. (class nc_methods():)</p> </li> <li><p>He also asked me to add &quot; __ str __&quot; (what is this?)</p> </li> <li><p>He asked me finally to add &quot;try~except&quot; just like the first method.</p> </li> </ol> <p>I should finish this work by today but I still have no idea where to start.. Please help</p> <pre><code>import netCDF4 as nc import numpy as np # --- Read DAta modules def Read_NC4(filename, var): try: ds_set = nc.Dataset(filename) except IOError: print(' ...&gt; Fatal Error: unavailable file\n ', filename) dat = -1 else: dat = np.squeeze(ds_set.variables[var][:]) ds_set.close() return dat # Functions def read_nc(ifnm, ds_name): nc_file = nc.Dataset(ifnm, 'r') dat = nc_file.variables[ds_name][:] nc_file.close() return dat def nc_get_dtype(FILE, var): nc_file = nc.Dataset(FILE, 'r') Dat_Type = nc_file.variables[var].dtype nc_file.close() return Dat_Type def nc_variables_meta(FILE, verbose=False): try: nc_file = nc.Dataset(FILE) except OSError as e: print( e.errno ) return -1 # fmt = ' {:&lt;10} {:&lt;15} {:&lt;8} {}' dat_vars = [] for item in nc_file.variables.keys(): var = nc_file.variables[item] if verbose: print(fmt.format(item, str(var.shape), str(var.dtype), var.long_name)) if var.ndim == 3: dat_vars.append(item) # nc_file.close() return dat_vars def nc_dimensions(FILE): nc_file = nc.Dataset(FILE, 'r') dims = nc_file.dimensions #.keys() #size = [ nc_file.dimensions[key].size for key in keys ] out = {}.fromkeys(dims.keys()) for key in dims.keys(): out[key] = dims[key].size nc_file.close() return out def nc_attrs(FILE, var): nc_ds = nc.Dataset(FILE, 'r') attr = {} if var not in nc_ds.variables.keys(): for item in nc_ds.ncattrs(): #print(item, nc_ds.getncattr(item)) attr[item] = nc_ds.getncattr(item) else: for item in nc_ds[var].ncattrs(): attr[item] = getattr(nc_ds[var], item) #attr_keys = nc_ds[var].ncattrs() #target = nc_ds[var] # #attr = {} #for item in attr_keys: # attr[item] = getattr(target, item) nc_ds.close() return attr #def nc_append(var, attr, output): def nc_append(output, var_name, DAT, ATTR): try: dims = ('time','latitude','longitude') nc_ds = nc.Dataset(output, 'r+') N_var = nc_ds.createVariable(var_name, DAT.dtype, dims) N_var.setncatts(ATTR) N_var[:] = DAT nc_ds.close() return True except: return False </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T08:19:41.330", "Id": "533970", "Score": "2", "body": "We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//codereview.meta.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//codereview.meta.stackexchange.com/q/2436), rather than your concerns about the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T11:11:35.913", "Id": "533990", "Score": "0", "body": "(The instance method [`__str__()`](https://docs.python.org/3/reference/datamodel.html?highlight=__str__#object.__str__)) returns an object's human readable representation.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T11:27:49.160", "Id": "533996", "Score": "0", "body": "(`boss asked me…[due] today` Difficult. You seem to be experienced enough to know about asking for outside help, adding manpower to late projects, procrastination. So you have some processing, implemented in *module*s, and a bunch of methods. And a boss not using the usual practice for managing resources, suggesting to spread this over more code. Did they state a perceived advantage in introducing a class? I'm under the impression there is some whiteboard style improvement necessary before starting to change around code.)" } ]
[ { "body": "<p><code>try</code>/<code>except</code> are used for error handling,</p>\n<pre><code>try:\n do_something()\nexcept:\n # an error occured.\n pass\n</code></pre>\n<p>So that if <code>do_something()</code> throws an error (<a href=\"https://docs.python.org/3/tutorial/errors.html\" rel=\"nofollow noreferrer\">exception</a>), we may choose to do something else than crashing the program. This is usually referred to as <em>&quot;catching&quot;</em> the error/exception.</p>\n<p>Classes are a collection of data &amp; functions. (usually <em>&quot;methods&quot;</em> refer to functions inside a class).</p>\n<pre><code>class Thing:\n def __init__(self):\n pass\n</code></pre>\n<p>the taxonomy of a class is <code>class &lt;Name&gt;:</code> and a list of functions following it, with the first argument being <code>self</code> (eg <code>def __init__(self)</code>)</p>\n<p>You may notice a trend with <em>methods</em> beginning &amp; ending with <code>__</code>.\nThese are referred to as <em>&quot;magic&quot; methods.</em></p>\n<p>see: <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__str__\" rel=\"nofollow noreferrer\">str magic method</a></p>\n<p>Magic methods have special behaviors that would be difficult/tedious to implement yourself. when a class has a <code>__str__</code> method defined, when that class's object is passed into <code>str(obj)</code>, it will return whatever <code>__str__</code> returns.</p>\n<pre><code>class Foo:\n def __str__(self):\n return &quot;oops&quot;\n\na = Foo()\nprint(str(a)) # oops\n</code></pre>\n<p>The next magic method you seen me use, is <code>__init__</code>.\nRemember how I said classes are a collection of methods &amp; <strong>data</strong>? <code>__init__</code> stands for &quot;initialize object&quot;. This is generally where we put all of our data at.</p>\n<pre><code>class Bar:\n def __init__(self, input1, input2):\n self.arg_1 = input1\n self.arg_2 = input2;\n \n # Example of your own method\n def my_method(self):\n print(self.arg_1)\n \nx = Bar(1, 2) # calls __init__\nx.my_method() # calls Foo.my_method\nstr(x) # calls Foo.__str__\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T23:23:58.703", "Id": "270431", "ParentId": "270405", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T05:19:13.073", "Id": "270405", "Score": "0", "Tags": [ "error-handling", "classification" ], "Title": "classifying codes + adding __str__ and exception handling (try~except)" }
270405
<p>I have implemented a library which makes Java Swing programming easier. I am just posting the library. There is a program that uses this library to implement examples of many Swing components but I cannot include that program here because the total size will become more than the allowed limit of 65K characters. I will the examples program in another question.</p> <p>Can someone please do the code review.</p> <p>The code is below:</p> <hr /> <h2>SwingLibrary.java</h2> <pre><code> class SwingLibrary { // if width is 0 then the frame is maximized horizontally // if height is 0 then the frame is maximized vertically public static JFrame setupJFrameAndGet(String title, int width, int height) { int state = 0; JFrame tmpJF = new JFrame(title); if (width == 0) { state = state | JFrame.MAXIMIZED_HORIZ; } if (height == 0) { state = state | JFrame.MAXIMIZED_VERT; } if ((width != 0) || (height != 0)) { tmpJF.setSize(width, height); } tmpJF.setExtendedState(tmpJF.getExtendedState() | state); tmpJF.setLocationRelativeTo(null); tmpJF.setLayout(null); tmpJF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); return tmpJF; } // end of setupJFrameAndGet // width and height are the preferred width and height of JPanel public static ArrayList&lt;Object&gt; setupScrollableJFrameAndGetFrameAndPanel(String title, int width, int height) { JFrame tmpJF = new JFrame(title); tmpJF.setExtendedState(tmpJF.getExtendedState() | JFrame.MAXIMIZED_BOTH); tmpJF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //tmpJF.setLayout(null); JPanel tmpJP = new JPanel(); //tmpJP.setBounds(xpos, ypos, width + 1000, height + 1000); tmpJP.setPreferredSize(new Dimension(width, height)); tmpJP.setLayout(null); JScrollPane tmpJSPFrame = new JScrollPane(tmpJP, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); tmpJSPFrame.getHorizontalScrollBar().setUnitIncrement(10); tmpJSPFrame.getVerticalScrollBar().setUnitIncrement(10); tmpJF.add(tmpJSPFrame); ArrayList&lt;Object&gt; tmpA = new ArrayList&lt;&gt;(); tmpA.add((Object) (tmpJF)); tmpA.add((Object) (tmpJP)); return tmpA; } // end of setupScrollableJFrameAndGetFrameAndPanel // actLisObj: object which implements action listener public static JButton setupJButtonAndGet(String text, Object actLisObj, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JButton tmpJB = new JButton(text); if (setBoundsFlag == true) { tmpJB.setBounds(xpos, ypos, width, height); } tmpJB.addActionListener((ActionListener) actLisObj); return tmpJB; } // end of setupJButtonAndGet // halign: horizontal alignment of text, valign: vertical alignment of text public static JLabel setupJLabelAndGet(String text, boolean opaque, Color bg, int halign, int valign, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JLabel tmpJL = new JLabel(text); if (setBoundsFlag == true) { tmpJL.setBounds(xpos, ypos, width, height); } tmpJL.setOpaque(opaque); if (bg != null) { tmpJL.setBackground(bg); } tmpJL.setHorizontalAlignment(halign); tmpJL.setVerticalAlignment(valign); return tmpJL; } // end of setupJlabelAndGet public static JTextField setupJTextFieldAndGet(int xpos, int ypos, int width, int height) { JTextField tmpJTF = new JTextField(); tmpJTF.setBounds(xpos, ypos, width, height); return tmpJTF; } // end of setupJTextFieldAndGet public static JFormattedTextField setupJFormattedTextFieldAndGet(Format fmt, Object initialVal, Object propertyChangeLis, String propertyToListenFor, int xpos, int ypos, int width, int height) { JFormattedTextField tmpJFTF = new JFormattedTextField(fmt); tmpJFTF.setValue(initialVal); tmpJFTF.addPropertyChangeListener(propertyToListenFor, (PropertyChangeListener) propertyChangeLis); tmpJFTF.setBounds(xpos, ypos, width, height); return tmpJFTF; } // end of setupJFormattedTextFieldAndGet // itemLisObj: object which implements item listener public static JCheckBox setupJCheckBoxAndGet(String text, boolean state, Object itemLisObj, int xpos, int ypos, int width, int height) { JCheckBox tmpJCB = new JCheckBox(text, state); tmpJCB.setBounds(xpos, ypos, width, height); tmpJCB.addItemListener((ItemListener) itemLisObj); return tmpJCB; } // end of setupJCheckBoxAndGet // actLisObj: object which implements action listener public static JRadioButton setupJRadioButtonAndGet(String text, boolean state, Object actLisObj, int xpos, int ypos, int width, int height) { JRadioButton tmpJRB = new JRadioButton(text, state); tmpJRB.setBounds(xpos, ypos, width, height); tmpJRB.addActionListener((ActionListener) actLisObj); return tmpJRB; } // end of setupJRadioButtonAndGet public static ButtonGroup setupButtonGroupAndGet() { ButtonGroup tmpBG = new ButtonGroup(); return tmpBG; } // end of setupButtonGroupAndGet public static JPasswordField setupJPasswordFieldAndGet(int xpos, int ypos, int width, int height) { JPasswordField tmpJPF = new JPasswordField(); tmpJPF.setBounds(xpos, ypos, width, height); return tmpJPF; } // end of setupJPasswordFieldAndGet public static JTextArea setupJTextAreaAndGet(String text, int rows, int columns, boolean setEditableFlag, boolean setLineWrapFlag, boolean setWrapStyleWordFlag, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JTextArea tmpJTA = new JTextArea(text, rows, columns); tmpJTA.setEditable(setEditableFlag); tmpJTA.setLineWrap(setLineWrapFlag); tmpJTA.setWrapStyleWord(setWrapStyleWordFlag); if (setBoundsFlag == true) { tmpJTA.setBounds(xpos, ypos, width, height); } return tmpJTA; } // end of setupJTextAreaAndGet public static JScrollPane setupScrollableJTextAreaAndGet(JTextArea jta, int xpos, int ypos, int width, int height) { JScrollPane tmpJSP = new JScrollPane(jta); tmpJSP.setBounds(xpos, ypos, width, height); return tmpJSP; } // end of setupScrollableJTextAreaAndGet public static JList&lt;String&gt; setupJListAndGet(ListModel&lt;String&gt; lm, int selectionMode, int visibleRowCount, int initialSelectedIndex, Object listSelLisObj, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JList&lt;String&gt; tmpJList = new JList&lt;String&gt;(lm); tmpJList.setSelectionMode(selectionMode); tmpJList.setVisibleRowCount(visibleRowCount); if (initialSelectedIndex &gt;= 0) { tmpJList.setSelectedIndex(initialSelectedIndex); } tmpJList.addListSelectionListener((ListSelectionListener) listSelLisObj); if (setBoundsFlag == true) { tmpJList.setBounds(xpos, ypos, width, height); } return tmpJList; } // end of setupJListAndGet public static JScrollPane setupScrollableJListAndGet(JList jlist, int xpos, int ypos, int width, int height) { JScrollPane tmpJSP = new JScrollPane(jlist); tmpJSP.setBounds(xpos, ypos, width, height); return tmpJSP; } // end of setupScrollableJListAndGet public static JComboBox&lt;String&gt; setupJComboBoxAndGet(ComboBoxModel&lt;String&gt; cbm, int initialSelectedIndex, Object actLisObj, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JComboBox&lt;String&gt; tmpJComboBox = new JComboBox&lt;String&gt;(cbm); if (initialSelectedIndex &gt;= 0) { tmpJComboBox.setSelectedIndex(initialSelectedIndex); } tmpJComboBox.addActionListener((ActionListener) actLisObj); if (setBoundsFlag == true) { tmpJComboBox.setBounds(xpos, ypos, width, height); } return tmpJComboBox; } // end of setupJComboBoxAndGet public static JProgressBar setupJProgressBarAndGet(int orientation, int min, int max, int initialVal, boolean borderPaintedFlag, boolean stringPaintedFlag, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JProgressBar tmpJPB = new JProgressBar(orientation, min, max); tmpJPB.setValue(initialVal); tmpJPB.setBorderPainted(borderPaintedFlag); tmpJPB.setStringPainted(stringPaintedFlag); if (setBoundsFlag == true) { tmpJPB.setBounds(xpos, ypos, width, height); } return tmpJPB; } // end of setupJProgressBarAndGet public static JSlider setupJSliderAndGet(int orientation, int min, int max, int initialVal, int minorTickSpacing, int majorTickSpacing, boolean paintTicksFlag, boolean paintLabelsFlag, Object changeLisObj, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JSlider tmpJS = new JSlider(orientation, min, max, initialVal); tmpJS.setMinorTickSpacing(minorTickSpacing); tmpJS.setMajorTickSpacing(majorTickSpacing); tmpJS.setPaintTicks(paintTicksFlag); tmpJS.setPaintLabels(paintLabelsFlag); tmpJS.addChangeListener((ChangeListener) changeLisObj); if (setBoundsFlag == true) { tmpJS.setBounds(xpos, ypos, width, height); } return tmpJS; } // end of setupJSliderAndGet public static JTree setupJTreeAndGet(DefaultMutableTreeNode rootNode, int selectionMode, Object treeSelLisObj, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JTree tmpJTree = new JTree(rootNode); tmpJTree.getSelectionModel().setSelectionMode(selectionMode); tmpJTree.addTreeSelectionListener((TreeSelectionListener) treeSelLisObj); if (setBoundsFlag == true) { tmpJTree.setBounds(xpos, ypos, width, height); } return tmpJTree; } // end of setupJTreeAndGet public static JScrollPane setupScrollableJTreeAndGet(JTree jtree, int xpos, int ypos, int width, int height) { JScrollPane tmpJSP = new JScrollPane(jtree); tmpJSP.setBounds(xpos, ypos, width, height); return tmpJSP; } // end of setupScrollableJTreeAndGet public static JSpinner setupJSpinnerAndGet(SpinnerModel sm, boolean editableFlag, Object spinnerChangeLisObj, int xpos, int ypos, int width, int height) { JSpinner tmpJSPN = new JSpinner(sm); tmpJSPN.addChangeListener((ChangeListener) spinnerChangeLisObj); if (editableFlag == false) { JComponent editor = tmpJSPN.getEditor(); if (editor instanceof JSpinner.DefaultEditor) { ((JSpinner.DefaultEditor) editor).getTextField().setEditable(editableFlag); } else { System.out.println(&quot;Error: Could not set editableFlag for JSpinner.&quot;); } } tmpJSPN.setBounds(xpos, ypos, width, height); return tmpJSPN; } // end of setupJSpinnerAndGet public static JColorChooser setupJColorChooserAndGet(Color initialColor, boolean borderTitleFlag, String borderTitle, Object colorChooserChangeLisObj, int xpos, int ypos, int width, int height) { JColorChooser tmpJCC = new JColorChooser(initialColor); tmpJCC.getSelectionModel().addChangeListener((ChangeListener) colorChooserChangeLisObj); if (borderTitleFlag == true) { tmpJCC.setBorder(BorderFactory.createTitledBorder(borderTitle)); } tmpJCC.setBounds(xpos, ypos, width, height); return tmpJCC; } // end of setupJColorChooserAndGet public static JDialog setupJDialogAndGet(Frame owner, String title, boolean modal, int width, int height) { JDialog tmpJD = new JDialog(owner, title, modal); tmpJD.setSize(width, height); tmpJD.setLocationRelativeTo(null); tmpJD.setLayout(null); tmpJD.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); return tmpJD; } // end of setupJDialogAndGet public static ArrayList&lt;Object&gt; setupScrollableJDialogAndGetDialogAndPanel(Frame owner, String title, boolean modal, int dialogWidth, int dialogHeight, int panelWidth, int panelHeight) { JDialog tmpJD = new JDialog(owner, title, modal); tmpJD.setSize(dialogWidth, dialogHeight); tmpJD.setLocationRelativeTo(null); tmpJD.setLayout(null); tmpJD.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); JPanel tmpJP = new JPanel(); tmpJP.setPreferredSize(new Dimension(panelWidth, panelHeight)); tmpJP.setLayout(null); ScrollPane sp = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS); sp.getHAdjustable().setUnitIncrement(10); sp.getVAdjustable().setUnitIncrement(10); sp.add(tmpJP); tmpJD.getRootPane().setContentPane(sp); ArrayList&lt;Object&gt; tmpA = new ArrayList&lt;&gt;(); tmpA.add((Object) (tmpJD)); tmpA.add((Object) (tmpJP)); return tmpA; } // end of setupScrollableJDialogAndGetDialogAndPanel public static JToggleButton setupJToggleButtonAndGet(String text, Object itemLisObj, boolean opaque, Color bgcolor, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JToggleButton tmpJTB = new JToggleButton(text); if (setBoundsFlag == true) { tmpJTB.setBounds(xpos, ypos, width, height); } tmpJTB.addItemListener((ItemListener) itemLisObj); tmpJTB.setOpaque(opaque); tmpJTB.setBackground(bgcolor); return tmpJTB; } // end of setupJToggleButtonAndGet public static JSeparator setupJSeparatorAndGet(int orientation, Color bgcolor, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JSeparator tmpJS = new JSeparator(orientation); tmpJS.setBackground(bgcolor); if (setBoundsFlag == true) { tmpJS.setBounds(xpos, ypos, width, height); } return tmpJS; } // end of setupJSeparatorAndGet public static JMenuBar setupJMenuBarAndGet(Color fgcolor, Color bgcolor) { JMenuBar tmpJMB = new JMenuBar(); tmpJMB.setOpaque(true); tmpJMB.setForeground(fgcolor); tmpJMB.setBackground(bgcolor); return tmpJMB; } // end of setupJMenuBarAndGet public static JMenu setupJMenuAndGet(String text, Color fgcolor, Color bgcolor) { JMenu tmpJM = new JMenu(text); tmpJM.setOpaque(true); tmpJM.setForeground(fgcolor); tmpJM.setBackground(bgcolor); return tmpJM; } // end of setupJMenuAndGet public static JMenuItem setupJMenuItemAndGet(String text, Object actLisObj, KeyStroke k, Color fgcolor, Color bgcolor) { JMenuItem tmpJMI = new JMenuItem(text); tmpJMI.setOpaque(true); tmpJMI.setForeground(fgcolor); tmpJMI.setBackground(bgcolor); tmpJMI.setAccelerator(k); if (actLisObj != null) { tmpJMI.addActionListener((ActionListener) actLisObj); } return tmpJMI; } // end of setupJMenuItemAndGet } // end of SwingLibrary </code></pre>
[]
[ { "body": "<p>There's a lot of code here, so here's a few things to get started with...</p>\n<h2>Comments</h2>\n<ul>\n<li><p>Consider JavaDoc for function description comments that the clients of your library might want to know, such as <code>// if width is 0 then the frame is maximized horizontally</code>. There's a good chance that their IDE will pick them up and give them hints when they're calling your functions.</p>\n</li>\n<li><p>Don't leave commented out code laying around. Use source control. When you're done with code <code>//tmpJF.setLayout(null);</code>, delete it.</p>\n</li>\n<li><p>Do end section comments like <code>// end of setupJTextAreaAndGet</code> really add value, or do they just add noise to your code? For me, if a braced section of code is long enough that it would need a comment, it's usually an indication that the logic within it needs to be broken up a bit more.</p>\n</li>\n</ul>\n<h2>Arguments</h2>\n<blockquote>\n<pre><code>public static JSlider setupJSliderAndGet(int orientation, \n int min, \n int max, \n int initialVal,\n int minorTickSpacing, \n int majorTickSpacing, \n boolean paintTicksFlag, \n boolean paintLabelsFlag, \n Object changeLisObj, \n boolean setBoundsFlag, \n int xpos, \n int ypos, \n int width, \n int height) {\n</code></pre>\n</blockquote>\n<p>The <code>setupJSliderAndGet</code> has 14 arguments. That's a lot. To use the method, I'd be relying on my IDE to tell me what value to pass where, based on the argument name / javadoc. Do you always need to pass all of these arguments? It seems like, if <code>setBoundsFlag</code> is <code>false</code>, then the last 4 arguments are ignored. This doesn't seem easier to use. Would it be better two methods, one that sets it up with the bounds and one that doesn't? This removes arguments and simplifies the individual implementations. The x,y,width,height combo exists on other methods. Is this a type waiting to be discovered?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T16:18:16.403", "Id": "270423", "ParentId": "270406", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T06:52:38.143", "Id": "270406", "Score": "0", "Tags": [ "java", "swing" ], "Title": "Java Swing Library" }
270406
<p>This is in continuation of my previous post for code review of Java Swing Library: <a href="https://codereview.stackexchange.com/questions/270406/java-swing-library">Java Swing Library</a></p> <p>Since the limit on total number of characters is 65K, I split my program in two parts. The first was Java Swing Library and the second one is this one.</p> <p>I have implemented a program that uses my Java Swing Library to show examples of many Swing components.</p> <p>You can use code from this program in your code.</p> <p>Where applicable, appropriate listeners are also implemented.</p> <p>The code of the program is below:</p> <hr /> <h2>Examples_Of_Many_Swing_Components_In_One_Program.java</h2> <pre><code> import java.io.*; import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.List; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.text.*; import javax.swing.tree.*; import java.time.*; import java.time.format.*; public class Examples_Of_Many_Swing_Components_In_One_Program extends MouseAdapter implements ActionListener, ItemListener, ListSelectionListener, ChangeListener, PropertyChangeListener, TreeSelectionListener { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; int midScreenWidth = screenWidth / 2; int midScreenHeight = screenHeight / 2; int xMargin = screenWidth/10; int vGap = 25; // vertical gap between components int hGap = 15; // horizontal gap between components int lineLabelHeight = 10; int currentYPos = 0; int componentHeight = 25; int buttonWidth = 100; Color lightBlue = new Color(173, 216, 230); JFrame jf = null; JPanel jp = null; JButton jbButtonExample = null; JTextField jtfTextFieldExample = null; JButton jbTextFieldExample = null; JFormattedTextField jftfFormattedTextFieldExample = null; JButton jbFormattedTextFieldExample = null; JCheckBox jcb1CheckBoxExample = null; JCheckBox jcb2CheckBoxExample = null; JCheckBox jcb3CheckBoxExample = null; JCheckBox jcb4CheckBoxExample = null; JLabel jlCheckBoxExample = null; JRadioButton jrb1RadioButtonExample = null; JRadioButton jrb2RadioButtonExample = null; JRadioButton jrb3RadioButtonExample = null; JRadioButton jrb4RadioButtonExample = null; JLabel jlRadioButtonExample = null; JButton jbFileChooserExample = null; JTextField jtfFileChooserExample = null; JTextField jpfPasswordFieldExample = null; JButton jbPasswordFieldExample = null; JTextArea jtaTextAreaExample = null; JScrollPane jspScrollableTextAreaExample = null; JButton jbScrollableTextAreaExample = null; JList&lt;String&gt; jlistScrollableListExample = null; JScrollPane jspScrollableListExample = null; JLabel jlScrollableListExample = null; JComboBox&lt;String&gt; jcbComboBoxExample = null; JLabel jlComboBoxExample = null; JProgressBar jpbProgressBarExample = null; JButton jbProgressBarExample = null; JLabel jlProgressBarExample = null; boolean stopThreadProgressBarExample = false; JSlider jsSliderExample = null; JLabel jlSliderExample = null; JTree jtreeScrollableTreeExample = null; JScrollPane jspScrollableTreeExample = null; JLabel jlScrollableTreeExample = null; JSpinner jsSpinnerExample = null; JLabel jlSpinnerExample = null; JColorChooser jccColorChooserExample = null; JLabel jlColorChooserExample = null; JButton jbOptionPaneExamplesMessage = null; JButton jbOptionPaneExamplesInput = null; JButton jbOptionPaneExamplesConfirm = null; JButton jbOptionPaneExamplesOption = null; JDialog jdDialogExample = null; JComboBox jcbDialogExample = null; JFormattedTextField jftfDialogExample = null; JList jlistDialogExample = null; JButton jbDialogExample1 = null; JButton jbDialogExample2 = null; JDialog jdScrollableDialogExample = null; JPanel jpScrollableDialogPanel = null; JButton jbDisplayScrollableDialog = null; JButton jbCloseScrollableDialog = null; JPopupMenu jpmPopupMenuExample = null; JMenuItem jmiPopupMenuExample1 = null; JMenuItem jmiPopupMenuExample2 = null; JToggleButton jtbToggleButtonExample = null; JButton jbToolBarExample = null; JComboBox jcbToolBarExample = null; JMenuBar jmb = null; JMenu jm = null; JMenu jmSubMenu = null; JMenuItem jmiMenuItemExample = null; JCheckBoxMenuItem jcbmiCheckBoxMenuItemExample = null; JRadioButtonMenuItem jrbmiRadioButtonMenuItem1 = null; JRadioButtonMenuItem jrbmiRadioButtonMenuItem2 = null; public void actionPerformed(ActionEvent ae) { Object source = ae.getSource(); if (source == jbButtonExample) { JOptionPane.showMessageDialog(jf, &quot;You clicked the button!&quot;, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); } else if (source == jbTextFieldExample) { String text = &quot;You entered: &quot; + jtfTextFieldExample.getText(); JOptionPane.showMessageDialog(jf, text, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); } else if ((source == jrb1RadioButtonExample) || (source == jrb2RadioButtonExample) || (source == jrb3RadioButtonExample) || (source == jrb4RadioButtonExample)) { String text = &quot;You selected &quot; + &quot;\&quot;&quot; + ((JRadioButton)source).getText() + &quot;\&quot;.&quot;; jlRadioButtonExample.setText(text); } else if (source == jbFileChooserExample) { JFileChooser jfc = new JFileChooser(); if ((jfc.showOpenDialog(jf)) == JFileChooser.APPROVE_OPTION) { File selectedFile = jfc.getSelectedFile(); jtfFileChooserExample.setText(selectedFile.getAbsolutePath()); } } else if (source == jbPasswordFieldExample) { String text = &quot;You entered: &quot; + jpfPasswordFieldExample.getText(); JOptionPane.showMessageDialog(jf, text, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); } else if (source == jbScrollableTextAreaExample) { String text = &quot;You wrote: &quot; + jtaTextAreaExample.getText(); JOptionPane.showMessageDialog(jf, text, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); } else if (source == jcbComboBoxExample) { // source is used here to show that selected item can be gotten from source // instead of using jcbComboBoxExample. String text = (String)(((JComboBox)source).getSelectedItem()); if (text.isBlank() == true) { jlComboBoxExample.setText(text); } else { text = &quot;You selected \&quot;&quot; + text + &quot;\&quot;.&quot;; jlComboBoxExample.setText(text); } } else if (source == jbProgressBarExample) { String buttonText = jbProgressBarExample.getText(); if ((buttonText.equals(&quot;Start Task&quot;) == true) || (buttonText.equals(&quot;Start Task Again&quot;) == true)) { // example of anonymous subclass Thread thread = new Thread() { public void run() { int progress = 10; while (progress &lt;= 100) { if (stopThreadProgressBarExample == true) { stopThreadProgressBarExample = false; jpbProgressBarExample.setValue(0); jbProgressBarExample.setText(&quot;Start Task Again&quot;); jlProgressBarExample.setText(&quot;Task cancelled.&quot;); return; } // end of if stopThreadProgressBarExample jlProgressBarExample.setText(&quot;Task is running..&quot;); jpbProgressBarExample.setValue(progress); if (progress == 100) { break; } try { Thread.sleep(1000); } catch (Exception e) {} progress = progress + 10; } // end of while jbProgressBarExample.setText(&quot;Start Task Again&quot;); jlProgressBarExample.setText(&quot;Task completed.&quot;); } }; // end of new thread thread.start(); jbProgressBarExample.setText(&quot;Cancel Task&quot;); } else if (buttonText.equals(&quot;Cancel Task&quot;) == true) { stopThreadProgressBarExample = true; } // end of if else (comparing strings) } else if (source == jbToolBarExample) { JOptionPane.showMessageDialog(jf, &quot;You clicked Button 1.&quot;, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); } else if (source == jcbToolBarExample) { // source is used here to show that selected item can be gotten from source // instead of using jcbToolBarExample. String text = (String)(((JComboBox)source).getSelectedItem()); if (text.isBlank() == false) { text = &quot;You selected \&quot;&quot; + text + &quot;\&quot;.&quot;; JOptionPane.showMessageDialog(jf, text, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); } } else if (source == jmiMenuItemExample) { String text = &quot;This one program implements examples of many swing components.&quot;; JOptionPane.showMessageDialog(jf, text, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); } else if (source == jcbmiCheckBoxMenuItemExample) { if (jcbmiCheckBoxMenuItemExample.isSelected() == true) { JOptionPane.showMessageDialog(jf, &quot;You have selected check box menu item&quot;, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(jf, &quot;You have unselected check box menu item&quot;, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); } } else if (source == jrbmiRadioButtonMenuItem1) { jp.setBackground(Color.WHITE); } else if (source == jrbmiRadioButtonMenuItem2) { jp.setBackground(null); } else if (source == jmiPopupMenuExample1) { LocalTime time = LocalTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;hh:mm a&quot;); String text = time.format(formatter); JOptionPane.showMessageDialog(jf, text, &quot;Current Time&quot;, JOptionPane.INFORMATION_MESSAGE); } else if (source == jmiPopupMenuExample2) { LocalDate date = LocalDate.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;dd-LLL-yyyy&quot;); String text = date.format(formatter); JOptionPane.showMessageDialog(jf, text, &quot;Today's Date&quot;, JOptionPane.INFORMATION_MESSAGE); } else if (source == jbDialogExample2) { jcbDialogExample.setSelectedIndex(0); jftfDialogExample.setText(&quot;&quot;); jlistDialogExample.clearSelection(); jdDialogExample.setVisible(true); } else if (source == jbDialogExample1) { String text = &quot;&quot;; boolean error = false; String textMonth = &quot;&quot;; String textYear = &quot;&quot;; String textCountry = &quot;&quot;; textMonth = (String)(jcbDialogExample.getSelectedItem()); if (jftfDialogExample.getValue() != null) { textYear = jftfDialogExample.getText(); } if (jlistDialogExample.getSelectedValue() != null) { textCountry = (String)(jlistDialogExample.getSelectedValue()); } if (textMonth.isBlank() == true) { error = true; text = &quot;Please select your month of birth.\n&quot;; } if (textYear.isBlank() == true) { error = true; text = text + &quot;Please enter your year of birth.\n&quot;; } else if (Integer.valueOf(textYear) &lt;= 0) { error = true; text = text + &quot;Please enter a valid year of birth.\n&quot;; } if (textCountry.isBlank() == true) { error = true; text = text + &quot;Please select your country of birth.\n&quot;; } if (error == true) { JOptionPane.showMessageDialog(jf, text, &quot;Error&quot;, JOptionPane.ERROR_MESSAGE); } else { text = &quot;&quot;; text = &quot;Your month of birth is: &quot; + textMonth + &quot;\n&quot;; text = text + &quot;Your year of birth is: &quot; + textYear + &quot;\n&quot;; text = text + &quot;Your counry of birth is: &quot; + textCountry + &quot;\n&quot;; JOptionPane.showMessageDialog(jf, text, &quot;Your deatils&quot;, JOptionPane.INFORMATION_MESSAGE); } } else if (source == jbDisplayScrollableDialog) { jdScrollableDialogExample.setVisible(true); } else if (source == jbCloseScrollableDialog) { jdScrollableDialogExample.dispose(); } else if (source == jbOptionPaneExamplesMessage) { JOptionPane.showMessageDialog(jf, &quot;This is a Message Dialog Box.&quot;, &quot;Message Dialog Box&quot;, JOptionPane.INFORMATION_MESSAGE); } else if (source == jbOptionPaneExamplesInput) { String text = &quot;You entered: &quot;; String input = JOptionPane.showInputDialog(jf, &quot;Please input some text below:&quot;, &quot;Input Dialog Box&quot;, JOptionPane.PLAIN_MESSAGE); if (input != null) { text = text + input; JOptionPane.showMessageDialog(jf, text, &quot;Text you entered&quot;, JOptionPane.INFORMATION_MESSAGE); } } else if (source == jbOptionPaneExamplesConfirm) { JPasswordField jpf = new JPasswordField(); int result = JOptionPane.showConfirmDialog(jf, jpf, &quot;Please input your password&quot;, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { String text = &quot;Your password is: &quot; + new String(jpf.getPassword()); JOptionPane.showMessageDialog(jf, text, &quot;Your password&quot;, JOptionPane.INFORMATION_MESSAGE); } } else if (source == jbOptionPaneExamplesOption) { /* JRadioButton jrb1 = new JRadioButton(&quot;Proceed&quot;); JRadioButton jrb2 = new JRadioButton(&quot;Do not proceed, stop here&quot;); JRadioButton jrb3 = new JRadioButton(&quot;Do not proceed, revert back&quot;); Object[] objs = {jrb1, jrb2, jrb3, &quot;Submit&quot;}; */ Object[] objs = new Object[4]; objs[0] = new JRadioButton(&quot;Proceed&quot;); objs[1] = new JRadioButton(&quot;Do not proceed, stop here&quot;); objs[2] = new JRadioButton(&quot;Do not proceed, revert back&quot;); objs[3] = &quot;Submit&quot;; ButtonGroup bg = new ButtonGroup(); bg.add((JRadioButton)(objs[0])); bg.add((JRadioButton)(objs[1])); bg.add((JRadioButton)(objs[2])); int result = JOptionPane.showOptionDialog(jf, &quot;Please select a radio button&quot;, &quot;Option Dialog Box&quot;, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, objs, null); if (result == 3) { // 3 is the index of &quot;Submit&quot; String text = &quot;&quot;; // if-else-if should be used but I am using ifs only to see that whether // more than one radio button gets selected or not or whether something // wrong is happening in UI. if ((((JRadioButton)(objs[0]))).isSelected() == true) { text = text + &quot;You selected: \&quot;Proceed\&quot;.&quot;; } if ((((JRadioButton)(objs[1]))).isSelected() == true) { text = text + &quot;You selected: \&quot;Do not proceed, stop here\&quot;.&quot;; } if ((((JRadioButton)(objs[2]))).isSelected() == true) { text = text + &quot;You selected: \&quot;Do not proceed, revert back\&quot;.&quot;; } if (text.isBlank() == true) { text = &quot;Nothing selected.&quot;; } JOptionPane.showMessageDialog(jf, text, &quot;Your selected choice&quot;, JOptionPane.INFORMATION_MESSAGE); } //String text = &quot;Result is: &quot; + result; //JOptionPane.showMessageDialog(jf, text, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); } } // end of actionPerformed // for JCheckBox and JToggleButton public void itemStateChanged(ItemEvent ie) { String text = &quot;&quot;; Object source = ie.getItemSelectable(); if ((source == jcb1CheckBoxExample) || (source == jcb2CheckBoxExample) || (source == jcb3CheckBoxExample) || (source == jcb4CheckBoxExample)) { if (ie.getStateChange() == ItemEvent.SELECTED) { text = &quot;You selected &quot;; } else { text = &quot;You unselected &quot;; } text = text + &quot;\&quot;&quot; + ((JCheckBox)source).getText() + &quot;\&quot;.&quot;; jlCheckBoxExample.setText(text); } else if (source == jtbToggleButtonExample) { if (jtbToggleButtonExample.isSelected() == true) { jtbToggleButtonExample.setText(&quot;ON&quot;); jtbToggleButtonExample.setOpaque(true); jtbToggleButtonExample.setBackground(Color.GREEN); } else { jtbToggleButtonExample.setText(&quot;OFF&quot;); jtbToggleButtonExample.setOpaque(true); jtbToggleButtonExample.setBackground(Color.YELLOW); } } } // end of itemStateChanged // for JList public void valueChanged(ListSelectionEvent lse) { String text = &quot;&quot;; Object source = lse.getSource(); if (source == jlistScrollableListExample) { List&lt;String&gt; lst = jlistScrollableListExample.getSelectedValuesList(); if (lst.size() &lt;= 0) { jlScrollableListExample.setText(text); } else { text = &quot;Your selected items are: &quot;; boolean first = true; for (String str : lst) { if (first == false) { text = text + &quot;, &quot;; } text = text + str; first = false; } // end of for loop text = text + &quot;.&quot;; jlScrollableListExample.setText(text); } // end of if else } // end of if source } // end of valueChanged // for JSlider, JSpinner, and JColorChooser public void stateChanged(ChangeEvent ce) { String text = &quot;&quot;; Object source = ce.getSource(); if (source == jsSliderExample) { JSlider jsSource = (JSlider)source; if (!jsSource.getValueIsAdjusting()) { int value = (int)(jsSource.getValue()); text = &quot;The current value from slider is: &quot; + value; jlSliderExample.setText(text); } } else if (source == jsSpinnerExample) { JSpinner jspnSource = (JSpinner)source; SpinnerModel sm = jspnSource.getModel(); if (sm instanceof SpinnerNumberModel) { text = &quot;The current value from spinner is: &quot; + ((SpinnerNumberModel)(sm)).getNumber().intValue(); jlSpinnerExample.setText(text); } else { text = &quot;Something went wrong.&quot;; jlSpinnerExample.setText(text); } } else if (source == jccColorChooserExample.getSelectionModel()) { Color newColor = jccColorChooserExample.getColor(); jlColorChooserExample.setBackground(newColor); } } // end of stateChanged // for JFormattedTextField public void propertyChange(PropertyChangeEvent pce) { Object source = pce.getSource(); if (source == jftfFormattedTextFieldExample) { double amount = ((Number)(jftfFormattedTextFieldExample.getValue())).doubleValue(); String text = &quot;You entered amount: &quot; + amount; JOptionPane.showMessageDialog(jf, text, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); } } // end of propertyChange // for JTree public void valueChanged(TreeSelectionEvent tse) { String text = &quot;&quot;; Object source = tse.getSource(); if (source == jtreeScrollableTreeExample) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)(((JTree)source).getLastSelectedPathComponent()); if (node == null) { jlScrollableTreeExample.setText(text); } else { text = &quot;You selected: &quot; + node.getUserObject().toString(); jlScrollableTreeExample.setText(text); } } } // end of valueChanged // for JPopupMenu to show up public void mousePressed(MouseEvent e) { //JOptionPane.showMessageDialog(jf, &quot;Mouse Pressed&quot;, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); if (e.isPopupTrigger()) { jpmPopupMenuExample.show(e.getComponent(), e.getX(), e.getY()); } } // end of mousePressed // for JPopupMenu to show up public void mouseReleased(MouseEvent e) { //JOptionPane.showMessageDialog(jf, &quot;Mouse Released&quot;, &quot;Info&quot;, JOptionPane.INFORMATION_MESSAGE); if (e.isPopupTrigger()) { jpmPopupMenuExample.show(e.getComponent(), e.getX(), e.getY()); } } // end of mouseReleased //void createJFrameExample() { //jf = SwingLibrary.setupJFrameAndGet(&quot;Learn Java Swing GUI Programming By Examples&quot;, screenWidth, screenHeight); //jf = SwingLibrary.setupJFrameAndGet(&quot;Learn Java Swing GUI Programming By Examples&quot;, 0, 0); //jf.setVisible(true); //} // end of addJFrameExample void createScrollableJFrameExample() { ArrayList&lt;Object&gt; a = SwingLibrary.setupScrollableJFrameAndGetFrameAndPanel(&quot;Learn Java Swing GUI Programming By Examples&quot;, screenWidth, screenHeight + 4500); jf = (JFrame)(a.get(0)); jp = (JPanel)(a.get(1)); } // end of addScrollableJFrameExample void addJButtonExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Button Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; jbButtonExample = SwingLibrary.setupJButtonAndGet(&quot;Click Me!&quot;, this, true, midScreenWidth - 50, currentYPos, buttonWidth, componentHeight); jp.add(jbButtonExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJButtonExample void addJLabelExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Label Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;This is a label!&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJLabelExample void addToolTipExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Tool Tip Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Hover the mouse over me to see the tool tip!&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 150, currentYPos, 300, componentHeight); jl.setToolTipText(&quot;This is a tool tip!&quot;); // show tool tip immediately ToolTipManager.sharedInstance().setInitialDelay(0); // keep tool tip showing ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE); jp.add(jl); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addToolTipExample void addJTextFieldExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Text Field Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Enter some text in below field:&quot;, false, null, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight; jtfTextFieldExample = SwingLibrary.setupJTextFieldAndGet(xMargin, currentYPos, screenWidth - (xMargin*2), componentHeight); jp.add(jtfTextFieldExample); currentYPos = currentYPos + componentHeight + vGap; jbTextFieldExample = SwingLibrary.setupJButtonAndGet(&quot;Submit&quot;, this, true, midScreenWidth - 50, currentYPos, buttonWidth, componentHeight); jp.add(jbTextFieldExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJTextFieldExample void addJFormattedTextFieldExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Formatted Text Field Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Enter some number in below formatted field (it accepts numbers only):&quot;, false, null, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 200, currentYPos, 400, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight; jftfFormattedTextFieldExample = SwingLibrary.setupJFormattedTextFieldAndGet(NumberFormat.getNumberInstance(), 1000, this, &quot;value&quot;, xMargin, currentYPos, screenWidth - (xMargin*2), componentHeight); jp.add(jftfFormattedTextFieldExample); currentYPos = currentYPos + componentHeight + vGap; jbFormattedTextFieldExample = SwingLibrary.setupJButtonAndGet(&quot;Click to shift focus away from formatted field&quot;, this, true, midScreenWidth - 200, currentYPos, 400, componentHeight); jp.add(jbFormattedTextFieldExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJFormattedTextFieldExample void addJCheckBoxExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Check Box Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Select/Unselect a checkbox&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight; jcb1CheckBoxExample = SwingLibrary.setupJCheckBoxAndGet(&quot;One&quot;, false, this, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jcb1CheckBoxExample); currentYPos = currentYPos + componentHeight; jcb2CheckBoxExample = SwingLibrary.setupJCheckBoxAndGet(&quot;Two&quot;, false, this, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jcb2CheckBoxExample); currentYPos = currentYPos + componentHeight; jcb3CheckBoxExample = SwingLibrary.setupJCheckBoxAndGet(&quot;Three&quot;, false, this, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jcb3CheckBoxExample); currentYPos = currentYPos + componentHeight; jcb4CheckBoxExample = SwingLibrary.setupJCheckBoxAndGet(&quot;Four&quot;, false, this, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jcb4CheckBoxExample); currentYPos = currentYPos + componentHeight; jlCheckBoxExample = SwingLibrary.setupJLabelAndGet(&quot;&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jlCheckBoxExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJCheckBoxExample void addJRadioButtonExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Radio Button Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Select a radio button&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight; jrb1RadioButtonExample = SwingLibrary.setupJRadioButtonAndGet(&quot;A&quot;, false, this, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jrb1RadioButtonExample); currentYPos = currentYPos + componentHeight; jrb2RadioButtonExample = SwingLibrary.setupJRadioButtonAndGet(&quot;B&quot;, false, this, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jrb2RadioButtonExample); currentYPos = currentYPos + componentHeight; jrb3RadioButtonExample = SwingLibrary.setupJRadioButtonAndGet(&quot;C&quot;, false, this, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jrb3RadioButtonExample); currentYPos = currentYPos + componentHeight; jrb4RadioButtonExample = SwingLibrary.setupJRadioButtonAndGet(&quot;D&quot;, false, this, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jrb4RadioButtonExample); // add all radio buttons to a button group so that only one radio button // can be selected at a time ButtonGroup bg = SwingLibrary.setupButtonGroupAndGet(); bg.add(jrb1RadioButtonExample); bg.add(jrb2RadioButtonExample); bg.add(jrb3RadioButtonExample); bg.add(jrb4RadioButtonExample); currentYPos = currentYPos + componentHeight; jlRadioButtonExample = SwingLibrary.setupJLabelAndGet(&quot;&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jlRadioButtonExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJRadioButtonExample void addJFileChooserExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;File Chooser Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Select a file by clicking Browse button below:&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 150, currentYPos, 300, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight + 4; jbFileChooserExample = SwingLibrary.setupJButtonAndGet(&quot;Browse&quot;, this, true, midScreenWidth - 50, currentYPos, buttonWidth, componentHeight); jp.add(jbFileChooserExample); currentYPos = currentYPos + componentHeight + vGap; jl = SwingLibrary.setupJLabelAndGet(&quot;The path to file that you choose will appear below:&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 150, currentYPos, 300, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight + 4; jtfFileChooserExample = SwingLibrary.setupJTextFieldAndGet(xMargin, currentYPos, screenWidth - (xMargin*2), componentHeight); jp.add(jtfFileChooserExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJFileChooserExample void addJPasswordFieldExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Password Field Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Enter some text (password) in below field:&quot;, false, null, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 150, currentYPos, 300, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight; jpfPasswordFieldExample = SwingLibrary.setupJPasswordFieldAndGet(xMargin, currentYPos, screenWidth - (xMargin*2), componentHeight); jp.add(jpfPasswordFieldExample); currentYPos = currentYPos + componentHeight + vGap; jbPasswordFieldExample = SwingLibrary.setupJButtonAndGet(&quot;Submit&quot;, this, true, midScreenWidth - 50, currentYPos, buttonWidth, componentHeight); jp.add(jbPasswordFieldExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJPasswordFieldExample void addScrollableJTextAreaExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Scrollable Text Area Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Write something in Text Area below:&quot;, false, null, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 150, currentYPos, 300, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight; jtaTextAreaExample = SwingLibrary.setupJTextAreaAndGet(&quot;&quot;, 10, 100, true, true, true, false, 0, 0, 0, 0); jspScrollableTextAreaExample = SwingLibrary.setupScrollableJTextAreaAndGet(jtaTextAreaExample, (xMargin*5)/2, currentYPos, screenWidth - (xMargin*5), componentHeight*4); jp.add(jspScrollableTextAreaExample); currentYPos = currentYPos + componentHeight*4 + vGap; jbScrollableTextAreaExample = SwingLibrary.setupJButtonAndGet(&quot;Submit&quot;, this, true, midScreenWidth - 50, currentYPos, buttonWidth, componentHeight); jp.add(jbScrollableTextAreaExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addScrollableJTextAreaExample void addScrollableJListExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Scrollable List Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Select/Unselect item(s) from list&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight + 4; // add items to default list model DefaultListModel&lt;String&gt; dlm = new DefaultListModel&lt;String&gt;(); dlm.addElement(&quot;One&quot;); dlm.addElement(&quot;Two&quot;); dlm.addElement(&quot;Three&quot;); dlm.addElement(&quot;Four&quot;); dlm.addElement(&quot;Five&quot;); dlm.addElement(&quot;Six&quot;); dlm.addElement(&quot;Seven&quot;); dlm.addElement(&quot;Eight&quot;); dlm.addElement(&quot;Nine&quot;); dlm.addElement(&quot;Ten&quot;); jlistScrollableListExample = SwingLibrary.setupJListAndGet(dlm, ListSelectionModel.MULTIPLE_INTERVAL_SELECTION, 3, -1, this, false, 0, 0, 0, 0); jspScrollableListExample = SwingLibrary.setupScrollableJListAndGet(jlistScrollableListExample, xMargin*4, currentYPos, screenWidth - (xMargin*8), componentHeight*4); jp.add(jspScrollableListExample); currentYPos = currentYPos + componentHeight*4 + vGap; jlScrollableListExample = SwingLibrary.setupJLabelAndGet(&quot;&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, xMargin, currentYPos, screenWidth - (xMargin*2), componentHeight); jp.add(jlScrollableListExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addScrollableJListExample void addJComboBoxExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Combo Box Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Select an item from combo box&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight + 4; // add items to default list model DefaultComboBoxModel&lt;String&gt; dcbm = new DefaultComboBoxModel&lt;String&gt;(); dcbm.addElement(&quot;&quot;); dcbm.addElement(&quot;A&quot;); dcbm.addElement(&quot;B&quot;); dcbm.addElement(&quot;C&quot;); dcbm.addElement(&quot;D&quot;); dcbm.addElement(&quot;E&quot;); dcbm.addElement(&quot;V&quot;); dcbm.addElement(&quot;W&quot;); dcbm.addElement(&quot;X&quot;); dcbm.addElement(&quot;Y&quot;); dcbm.addElement(&quot;Z&quot;); jcbComboBoxExample = SwingLibrary.setupJComboBoxAndGet(dcbm, 0, this, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jcbComboBoxExample); currentYPos = currentYPos + componentHeight*4 + vGap; jlComboBoxExample = SwingLibrary.setupJLabelAndGet(&quot;&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jlComboBoxExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJComboBoxExample void addJProgressBarExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Progress Bar Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; jlProgressBarExample = SwingLibrary.setupJLabelAndGet(&quot;Task not started.&quot;, false, null, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jlProgressBarExample); currentYPos = currentYPos + componentHeight; jpbProgressBarExample = SwingLibrary.setupJProgressBarAndGet(SwingConstants.HORIZONTAL, 0, 100, 0, true, true, true, xMargin, currentYPos, screenWidth - (xMargin*2), componentHeight); jp.add(jpbProgressBarExample); currentYPos = currentYPos + componentHeight + vGap; jbProgressBarExample = SwingLibrary.setupJButtonAndGet(&quot;Start Task&quot;, this, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jbProgressBarExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJProgressBarExample void addJSliderExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Slider Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; jsSliderExample = SwingLibrary.setupJSliderAndGet(SwingConstants.HORIZONTAL, 0, 100, 20, 1, 10, true, true, this, true, xMargin, currentYPos, screenWidth - (xMargin*2), componentHeight*2); jp.add(jsSliderExample); currentYPos = currentYPos + componentHeight*2 + vGap; jlSliderExample = SwingLibrary.setupJLabelAndGet(&quot;The current value from slider is: 20&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 110, currentYPos, 220, componentHeight); jp.add(jlSliderExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJSliderExample void addScrollableJTreeExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Scrollable Tree Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;You can select any node in the tree.&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 110, currentYPos, 220, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight + 4; // create tree nodes DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(&quot;Names&quot;); DefaultMutableTreeNode j = new DefaultMutableTreeNode(&quot;J&quot;); DefaultMutableTreeNode james = new DefaultMutableTreeNode(&quot;James&quot;); DefaultMutableTreeNode jerrod = new DefaultMutableTreeNode(&quot;Jerrod&quot;); j.add(james); j.add(jerrod); rootNode.add(j); DefaultMutableTreeNode n = new DefaultMutableTreeNode(&quot;N&quot;); DefaultMutableTreeNode nathan = new DefaultMutableTreeNode(&quot;Nathan&quot;); DefaultMutableTreeNode nicholas = new DefaultMutableTreeNode(&quot;Nicholas&quot;); n.add(nathan); n.add(nicholas); rootNode.add(n); DefaultMutableTreeNode v = new DefaultMutableTreeNode(&quot;V&quot;); DefaultMutableTreeNode vincent = new DefaultMutableTreeNode(&quot;Vincent&quot;); v.add(vincent); rootNode.add(v); jtreeScrollableTreeExample = SwingLibrary.setupJTreeAndGet(rootNode, TreeSelectionModel.SINGLE_TREE_SELECTION, this, false, 0, 0, 0, 0); jspScrollableTreeExample = SwingLibrary.setupScrollableJTreeAndGet(jtreeScrollableTreeExample, xMargin*4, currentYPos, screenWidth - (xMargin*8), componentHeight*4); jp.add(jspScrollableTreeExample); currentYPos = currentYPos + componentHeight*4 + vGap; jlScrollableTreeExample = SwingLibrary.setupJLabelAndGet(&quot;&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 110, currentYPos, 220, componentHeight); jp.add(jlScrollableTreeExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addScrollableJTree example void addJSpinnerExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Spinner Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Click on up arrow or down arrow of the spinner to set a value.&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 200, currentYPos, 400, componentHeight); jp.add(jl); currentYPos = currentYPos + componentHeight*2; SpinnerNumberModel snm = new SpinnerNumberModel(20, 1, null, 1); jsSpinnerExample = SwingLibrary.setupJSpinnerAndGet(snm, false, this, xMargin*4, currentYPos, screenWidth - (xMargin*8), componentHeight); jp.add(jsSpinnerExample); currentYPos = currentYPos + componentHeight + vGap; jlSpinnerExample = SwingLibrary.setupJLabelAndGet(&quot;The current value from spinner is: 20&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 150, currentYPos, 300, componentHeight); jp.add(jlSpinnerExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJSpinnerExample void addJColorChooserExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Color Chooser Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; jlColorChooserExample = SwingLibrary.setupJLabelAndGet(&quot;Select a color and the background of this label will change to that color.&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 250, currentYPos, 500, componentHeight); jp.add(jlColorChooserExample); currentYPos = currentYPos + componentHeight*2; jccColorChooserExample = SwingLibrary.setupJColorChooserAndGet(Color.GREEN, true, &quot;Choose a color&quot;, this, xMargin*2, currentYPos, screenWidth - (xMargin*4), componentHeight*12); jp.add(jccColorChooserExample); currentYPos = currentYPos + componentHeight*12 + vGap; addLineLabel(currentYPos); } // end of addJColorChooserExample void addJOptionPaneExamples() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Option Pane Examples&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; jbOptionPaneExamplesMessage = SwingLibrary.setupJButtonAndGet(&quot;Click to see the Message Dialog Box&quot;, this, true, midScreenWidth - 150, currentYPos, 300, componentHeight); jp.add(jbOptionPaneExamplesMessage); currentYPos = currentYPos + componentHeight + vGap; jbOptionPaneExamplesInput = SwingLibrary.setupJButtonAndGet(&quot;Click to see the Input Dialog Box&quot;, this, true, midScreenWidth - 150, currentYPos, 300, componentHeight); jp.add(jbOptionPaneExamplesInput); currentYPos = currentYPos + componentHeight + vGap; jbOptionPaneExamplesConfirm = SwingLibrary.setupJButtonAndGet(&quot;Click to see the Confirm Dialog Box&quot;, this, true, midScreenWidth - 150, currentYPos, 300, componentHeight); jp.add(jbOptionPaneExamplesConfirm); currentYPos = currentYPos + componentHeight + vGap; jbOptionPaneExamplesOption = SwingLibrary.setupJButtonAndGet(&quot;Click to see the Option Dialog Box&quot;, this, true, midScreenWidth - 150, currentYPos, 300, componentHeight); jp.add(jbOptionPaneExamplesOption); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJOptionPaneExample void addJDialogExample() { int dialogWidth = 336; int dialogHeight = 350; int midDialogWidth = dialogWidth/2; int jdXPos = 10; int jdYPos = 10; currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Dialog Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + vGap; jdDialogExample = SwingLibrary.setupJDialogAndGet(jf, &quot;Details&quot;, true, dialogWidth, dialogHeight); JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;Select your month of birth from combo box:&quot;, false, null, SwingConstants.LEFT, SwingConstants.CENTER, true, jdXPos, jdYPos, 300, componentHeight); jdDialogExample.add(jl); DefaultComboBoxModel&lt;String&gt; dcbm = new DefaultComboBoxModel&lt;String&gt;(); dcbm.addElement(&quot;&quot;); dcbm.addElement(&quot;Jan&quot;); dcbm.addElement(&quot;Feb&quot;); dcbm.addElement(&quot;Mar&quot;); dcbm.addElement(&quot;Apr&quot;); dcbm.addElement(&quot;May&quot;); dcbm.addElement(&quot;Jun&quot;); dcbm.addElement(&quot;Jul&quot;); dcbm.addElement(&quot;Aug&quot;); dcbm.addElement(&quot;Sep&quot;); dcbm.addElement(&quot;Oct&quot;); dcbm.addElement(&quot;Nov&quot;); dcbm.addElement(&quot;Dec&quot;); jdYPos = jdYPos + componentHeight; jcbDialogExample = SwingLibrary.setupJComboBoxAndGet(dcbm, 0, null, true, jdXPos, jdYPos, 300, componentHeight); jdDialogExample.add(jcbDialogExample); jdYPos = jdYPos + componentHeight*2; jl = SwingLibrary.setupJLabelAndGet(&quot;Enter your year of birth in text field (4 digits):&quot;, false, null, SwingConstants.LEFT, SwingConstants.CENTER, true, jdXPos, jdYPos, 300, componentHeight); jdDialogExample.add(jl); jdYPos = jdYPos + componentHeight; NumberFormat format = NumberFormat.getIntegerInstance(); format.setGroupingUsed(false); format.setMinimumIntegerDigits(0); format.setMaximumIntegerDigits(4); jftfDialogExample = SwingLibrary.setupJFormattedTextFieldAndGet(format, null, null, null, jdXPos, jdYPos, 300, componentHeight); jdDialogExample.add(jftfDialogExample); jdYPos = jdYPos + componentHeight*2; jl = SwingLibrary.setupJLabelAndGet(&quot;Select your country of birth from list:&quot;, false, null, SwingConstants.LEFT, SwingConstants.CENTER, true, jdXPos, jdYPos, 300, componentHeight); jdDialogExample.add(jl); DefaultListModel&lt;String&gt; dlm = new DefaultListModel&lt;String&gt;(); dlm.addElement(&quot;USA&quot;); dlm.addElement(&quot;Outside USA&quot;); jdYPos = jdYPos + componentHeight; jlistDialogExample = SwingLibrary.setupJListAndGet(dlm, ListSelectionModel.SINGLE_SELECTION, 2, -1, null, true, jdXPos, jdYPos, 300, componentHeight*2 - 14); jdDialogExample.add(jlistDialogExample); jdYPos = jdYPos + componentHeight*3; jbDialogExample1 = SwingLibrary.setupJButtonAndGet(&quot;Submit&quot;, this, true, midDialogWidth - 50, jdYPos, 100, componentHeight); jdDialogExample.add(jbDialogExample1); currentYPos = currentYPos + componentHeight; jbDialogExample2 = SwingLibrary.setupJButtonAndGet(&quot;Click to see the dialog box&quot;, this, true, midScreenWidth - 150, currentYPos, buttonWidth*3, componentHeight); jp.add(jbDialogExample2); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJDialogExample void addScrollableJDialogExample() { int dialogWidth = 400; int dialogHeight = 400; int midDialogWidth = dialogWidth/2; int panelWidth = 420; int panelHeight = 570; int jdYPos = 10; currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Scrollable Dialog Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + vGap; ArrayList&lt;Object&gt; a = SwingLibrary.setupScrollableJDialogAndGetDialogAndPanel(jf, &quot;List of Labels&quot;, true, dialogWidth, dialogHeight, panelWidth, panelHeight); jdScrollableDialogExample = (JDialog)(a.get(0)); jpScrollableDialogPanel = (JPanel)(a.get(1)); JLabel jl = null; String text = null; for (int i = 0; i &lt; 15; i++) { text = &quot;This is label &quot; + (i + 1); jl = SwingLibrary.setupJLabelAndGet(text, true, Color.BLACK, SwingConstants.LEFT, SwingConstants.CENTER, true, 10, jdYPos, 400, componentHeight); jl.setForeground(Color.WHITE); jdYPos = jdYPos + 35; jpScrollableDialogPanel.add(jl); } jbCloseScrollableDialog = SwingLibrary.setupJButtonAndGet(&quot;Close&quot;, this, true, midDialogWidth - 50, jdYPos, 100, componentHeight); jpScrollableDialogPanel.add(jbCloseScrollableDialog); currentYPos = currentYPos + componentHeight; jbDisplayScrollableDialog = SwingLibrary.setupJButtonAndGet(&quot;Click to see the scrollable dialog box&quot;, this, true, midScreenWidth - 150, currentYPos, buttonWidth*3, componentHeight); jp.add(jbDisplayScrollableDialog); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addScrollableJDialogExample void addJPopupMenuExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Popup Menu Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jlPopupMenuExample = SwingLibrary.setupJLabelAndGet(&quot;Right click anywhere in the frame to the see the popup menu.&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 250, currentYPos, 500, componentHeight); jp.add(jlPopupMenuExample); jpmPopupMenuExample = new JPopupMenu(&quot;Popup Menu&quot;); jmiPopupMenuExample1 = SwingLibrary.setupJMenuItemAndGet(&quot;Show current time&quot;, this, null, null, null); jpmPopupMenuExample.add(jmiPopupMenuExample1); jpmPopupMenuExample.addSeparator(); jmiPopupMenuExample2 = SwingLibrary.setupJMenuItemAndGet(&quot;Show today's date&quot;, this, null, null, null); jpmPopupMenuExample.add(jmiPopupMenuExample2); // Add mouse listener on JPanel so that clicking anywhere on JPanel will bring up the popup menu. jp.addMouseListener(this); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJPopupMenuExample void addJToggleButtonExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Toggle Button Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; jtbToggleButtonExample = SwingLibrary.setupJToggleButtonAndGet(&quot;OFF&quot;, this, true, Color.YELLOW, true, midScreenWidth - 50, currentYPos, buttonWidth, componentHeight); jp.add(jtbToggleButtonExample); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJToggleButtonExample void addJSeparatorExample() { currentYPos = currentYPos + vGap; addHeadingLabel(&quot;Separator Example&quot;, 0, currentYPos, screenWidth, componentHeight); currentYPos = currentYPos + componentHeight + vGap; JLabel jlSeparatorExample = SwingLibrary.setupJLabelAndGet(&quot;Below are the separators.&quot;, true, Color.GREEN, SwingConstants.CENTER, SwingConstants.CENTER, true, midScreenWidth - 100, currentYPos, 200, componentHeight); jp.add(jlSeparatorExample); currentYPos = currentYPos + componentHeight + vGap; JSeparator sep1 = SwingLibrary.setupJSeparatorAndGet(SwingConstants.HORIZONTAL, Color.YELLOW, true, xMargin*2, currentYPos, screenWidth - (xMargin*4), componentHeight); jp.add(sep1); currentYPos = currentYPos + componentHeight + vGap; JSeparator sep2 = SwingLibrary.setupJSeparatorAndGet(SwingConstants.HORIZONTAL, Color.GREEN, true, xMargin*2, currentYPos, screenWidth - (xMargin*4), componentHeight); jp.add(sep2); currentYPos = currentYPos + componentHeight + vGap; addLineLabel(currentYPos); } // end of addJSeparatorExample void addJToolBarExample() { JToolBar jtbToolBarExample = new JToolBar(&quot;Tool Bar&quot;, SwingConstants.HORIZONTAL); jbToolBarExample = SwingLibrary.setupJButtonAndGet(&quot;Button 1&quot;, this, false, 0, 0, 0, 0); jtbToolBarExample.add(jbToolBarExample); jtbToolBarExample.addSeparator(); // Now, add a combo box to tool bar DefaultComboBoxModel&lt;String&gt; dcbm = new DefaultComboBoxModel&lt;String&gt;(); dcbm.addElement(&quot;&quot;); dcbm.addElement(&quot;Item 1&quot;); dcbm.addElement(&quot;Item 2&quot;); dcbm.addElement(&quot;Item 3&quot;); dcbm.addElement(&quot;Item 4&quot;); jcbToolBarExample = SwingLibrary.setupJComboBoxAndGet(dcbm, 0, this, false, 0, 0, 0, 0); jtbToolBarExample.add(jcbToolBarExample); //jtbToolBarExample.setBorderPainted(true); jf.add(jtbToolBarExample, BorderLayout.NORTH); } // end of addJToolBarExample void addJMenuItemsExample() { KeyStroke k = KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_DOWN_MASK); jmb = SwingLibrary.setupJMenuBarAndGet(null, Color.GREEN); jm = SwingLibrary.setupJMenuAndGet(&quot;Help&quot;, Color.BLACK, Color.YELLOW); jmSubMenu = SwingLibrary.setupJMenuAndGet(&quot;More Help&quot;, Color.BLUE, Color.YELLOW); jmiMenuItemExample = SwingLibrary.setupJMenuItemAndGet(&quot;About&quot;, this, k, null, Color.WHITE); jcbmiCheckBoxMenuItemExample = new JCheckBoxMenuItem(&quot;Show a message dialog box&quot;); jcbmiCheckBoxMenuItemExample.addActionListener(this); jrbmiRadioButtonMenuItem1 = new JRadioButtonMenuItem(&quot;Change background color to white&quot;); jrbmiRadioButtonMenuItem1.addActionListener(this); jrbmiRadioButtonMenuItem2 = new JRadioButtonMenuItem(&quot;Change background color to default&quot;); jrbmiRadioButtonMenuItem2.addActionListener(this); ButtonGroup bg = SwingLibrary.setupButtonGroupAndGet(); bg.add(jrbmiRadioButtonMenuItem1); bg.add(jrbmiRadioButtonMenuItem2); jmSubMenu.add(jmiMenuItemExample); jmSubMenu.addSeparator(); jmSubMenu.add(jcbmiCheckBoxMenuItemExample); jmSubMenu.addSeparator(); jmSubMenu.add(jrbmiRadioButtonMenuItem1); jmSubMenu.add(jrbmiRadioButtonMenuItem2); jm.add(jmSubMenu); jmb.add(jm); jf.setJMenuBar(jmb); } // end of addJMenuItemsExample void createAndShowSwingGUIExamples() { //createJFrameExample(); createScrollableJFrameExample(); addJButtonExample(); addJLabelExample(); addToolTipExample(); addJTextFieldExample(); addJFormattedTextFieldExample(); addJCheckBoxExample(); addJRadioButtonExample(); addJFileChooserExample(); addJPasswordFieldExample(); addScrollableJTextAreaExample(); addScrollableJListExample(); addJComboBoxExample(); addJProgressBarExample(); addJSliderExample(); addScrollableJTreeExample(); addJSpinnerExample(); addJColorChooserExample(); addJOptionPaneExamples(); addJDialogExample(); addScrollableJDialogExample(); addJPopupMenuExample(); addJToggleButtonExample(); addJSeparatorExample(); addJToolBarExample(); addJMenuItemsExample(); // Frame has been created, all examples have been added, now show the frame jf.setVisible(true); } // end of createAndShowSwingExamples void addHeadingLabel(String text, int xpos, int ypos, int width, int height) { //JLabel jl = SwingLibrary.setupJLabelAndGet(text, true, Color.YELLOW, SwingConstants.CENTER, SwingConstants.CENTER, true, xpos, ypos, width, height); JLabel jl = SwingLibrary.setupJLabelAndGet(text, true, lightBlue, SwingConstants.CENTER, SwingConstants.CENTER, true, xpos, ypos, width, height); jp.add(jl); } // end of addHeadingLabel void addLineLabel(int ypos) { JLabel jl = SwingLibrary.setupJLabelAndGet(&quot;&quot;, true, Color.BLACK, SwingConstants.CENTER, SwingConstants.CENTER, true, 0, ypos, screenWidth, lineLabelHeight); jp.add(jl); currentYPos = currentYPos + lineLabelHeight; } // end of addLineLabel public static void main(String[] args) { Examples_Of_Many_Swing_Components_In_One_Program eomsciop = new Examples_Of_Many_Swing_Components_In_One_Program(); eomsciop.createAndShowSwingGUIExamples(); } // end of main } // end of Examples_Of_Many_Swing_Components_In_One_Program </code></pre> <p>The components whose examples are given in the code are:</p> <ul> <li>JButton</li> <li>JLabel</li> <li>ToolTip</li> <li>JTextField</li> <li>JFormattedTextField</li> <li>JCheckBox</li> <li>JRadioButton</li> <li>JFileChooser</li> <li>JPasswordField</li> <li>Scrollable JTextArea</li> <li>Scrollable JList</li> <li>JComboBox</li> <li>JProgressBar</li> <li>JSlider</li> <li>Scrollable JTree</li> <li>JSpinner</li> <li>JColorChooser</li> <li>JOptionPane</li> <li>JDialog</li> <li>Scrollable JDialog</li> <li>JPopupMenu</li> <li>JToggleButton</li> <li>JSeparator</li> <li>JToolBar</li> <li>JMenuBar</li> <li>JMenu</li> <li>JMenuItem</li> <li>JCheckBoxMenuItem</li> <li>JRadioButtonMenuItem</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T07:01:59.443", "Id": "534201", "Score": "0", "body": "Is this a real code review or a trick question? all your code is named `example` - is it for real?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T07:42:58.447", "Id": "270408", "Score": "1", "Tags": [ "java", "swing" ], "Title": "Examples of many Java swing components in one program" }
270408
<p>Background:</p> <p>Hello, I'm a student (since 2 months) and I've created a small MVP of a weather application. So now I'm refactoring my code because it looks hideous and it is hard to work with.</p> <p>The problem:</p> <p>In the snippet I will provide you will see that I repeat code for a .map(), which I know is not the best practice. But I need help to know in which way I could combine the two loops to one, and still render the same result from my component.</p> <p>This is probably a simple problem, but I struggle right now with the nesting. I think it's actually more about the html table rather than the .js itself. But I just keep bashing my head here.</p> <p>What my code does:</p> <p>This is a html Table from a component that formats and renders weather data fetched from a public API, in 3 columns per row, date, time of day and weather data values.</p> <p>The loops themselves maps through a weather json object so I can render the timestamps and the weather data I want to show to the user.</p> <pre><code>&lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th className=&quot;date&quot;&gt;Date&lt;/th&gt; &lt;th className=&quot;time&quot;&gt;Time&lt;/th&gt; &lt;th className=&quot;values&quot;&gt;Value/Unit&lt;/th&gt; &lt;/tr&gt; {dates.map((weatherDate, index) =&gt; { if ( index === 0 || weather[weatherDate].length &lt; 4 ) { return null; } return weather[weatherDate] &amp;&amp; weather[weatherDate].length !== 0 ? ( &lt;React.Fragment key={&quot;thisWeek-&quot; + index}&gt; &lt;tr className=&quot;tr-content&quot;&gt; &lt;td className=&quot;date&quot;&gt;{weatherDate}&lt;/td&gt; &lt;td className=&quot;time&quot;&gt; {weather[weatherDate].map((weatherData, _index) =&gt; { const time = weatherData.validTime.slice( weatherData.validTime.indexOf(&quot;T&quot;) + 1, weatherData.validTime.length - 4 ); if (TIMES_TO_SHOW.indexOf(time) === -1) return null; return ( &lt;p key={&quot;weather-data-&quot; + _index}&gt; {time} &lt;/p&gt; ); })} &lt;/td&gt; &lt;td className=&quot;values&quot;&gt; {weather[weatherDate].map((weatherTime, index_) =&gt; { const time = weatherTime.validTime.slice( weatherTime.validTime.indexOf(&quot;T&quot;) + 1, weatherTime.validTime.length - 4 ); if (TIMES_TO_SHOW.indexOf(time) === -1) return null; return ( &lt;React.Fragment key={index_}&gt; Temperature: {weatherTime.parameters.t.values}° Windspeed: {weatherTime.parameters.ws.values} m/s Gusts: {weatherTime.parameters.gust.values} m/s Vind direction: {weatherTime.parameters.wd.values}° &lt;/React.Fragment&gt; ); })} &lt;/td&gt; &lt;/tr&gt; &lt;/React.Fragment&gt; ) : null; })} &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>I am aware of other problems in my code, feel free to adress them as well, but I'm mainly here for help with combining my loops :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T09:55:04.173", "Id": "533982", "Score": "0", "body": "Welcome to code review. Please check the [ask] page." } ]
[ { "body": "<h1>Hey Jonathan, welcome to Code Review!</h1>\n<p>There's an easy way to turn those two <code>map</code>s into one. I'm going to tell you how, and give you some general tips as a bonus. Buckle up!</p>\n<br/>\n<hr />\n<br/>\n<h1>➰ <a href=\"https://youtu.be/PGNiXGX2nLU?t=61\" rel=\"nofollow noreferrer\">Looping right round (like a record baby)</a></h1>\n<p>You asked how to prevent yourself from repeating your loops, which is <a href=\"https://reactjs.org/docs/fragments.html\" rel=\"nofollow noreferrer\">a perfect use case for a <code>Fragment</code></a>!</p>\n<p>Consider the following:</p>\n<pre><code>&lt;row&gt;\n &lt;column&gt;\n {data.map(item =&gt; /*...*/)}\n &lt;/column&gt;\n &lt;column&gt;\n {data.map(item =&gt; /*...*/)}\n &lt;/column&gt;\n&lt;/row&gt;\n</code></pre>\n<p>Assuming those two maps are over the same data, and use the same parameters, we can just wrap the <code>column</code>s in a fragment in a single loop:</p>\n<pre><code>&lt;row&gt;\n {data.map(item =&gt; (\n &lt;React.fragment&gt;\n &lt;column&gt;\n {item}\n &lt;/column&gt;\n &lt;column&gt;\n {item}\n &lt;/column&gt;\n &lt;/React.fragment&gt;\n ))}\n&lt;/row&gt;\n</code></pre>\n<p>So to answer your question:</p>\n<pre><code>{weather[weatherDate].map((weatherData, index) =&gt; {\n const time = weatherData.validTime.slice(\n weatherData.validTime.indexOf(&quot;T&quot;) + 1,\n weatherData.validTime.length - 4\n );\n if (TIMES_TO_SHOW.indexOf(time) === -1) return null;\n return (\n &lt;React.Fragment key={&quot;thisWeek-&quot; + index}&gt;\n &lt;td className=&quot;time&quot;&gt;\n &lt;p key={&quot;weather-data-&quot; + index}&gt;\n {time}\n &lt;/p&gt;\n &lt;/td&gt;\n &lt;td className=&quot;values&quot;&gt;\n &lt;React.Fragment key={index_}&gt;\n Temperature: {weatherData.parameters.t.values}°\n Windspeed: {weatherData.parameters.ws.values} m/s\n Gusts: {weatherData.parameters.gust.values} m/s\n Vind direction: {weatherData.parameters.wd.values}°\n &lt;/React.Fragment&gt;\n &lt;/td&gt;\n &lt;/React.fragment&gt;\n );\n})}\n</code></pre>\n<p>Okay, bye!</p>\n<br/>\n<br/>\n<p>...</p>\n<br/>\n<br/>\n<p>Kidding! There's more where that came from.</p>\n<br/>\n<hr />\n<br/>\n<h1>❓ To render or not to render</h1>\n<h2>️ Skipping unwanted values</h2>\n<p>When mapping over an array of values, you might run into values that you don't want to map. When something like that happens, you might want to return <code>null</code> instead of that value -- which is what you've done here.</p>\n<pre class=\"lang-js prettyprint-override\"><code>dates.map((weatherDate, index) =&gt; {\n if (\n weather[weatherDate].length &lt; 4\n ) {\n return null;\n }\n /* ... */\n);\n</code></pre>\n<p>Looking at the code and stepping back a bit, you're putting business logic into your view logic. This makes code more cryptic and thus more difficult to understand. We need to separate &quot;should we render this data?&quot; from &quot;how to render this data?&quot;.</p>\n<p>Instead of returning <code>null</code> which tells React not to render this data, surely one could just just... <em>not render those values in the array in the first place?</em> This is where <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">our great friend <code>Array.filter</code></a> comes in. It takes a function that returns a boolean for each element in an array, called a <em>predicate</em>. If that predicate returns <code>true</code>, the element in question is &quot;kept&quot; -- else the element is &quot;discarded&quot;:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const numbers = [1,2,3,4,5,6,7,8,9];\nconst isEven = number =&gt; number % 2 === 0;\nconst evenNumbers = numbers.filter(number =&gt; isEven(number));\n// &gt; [2, 4, 6, 8]\n</code></pre>\n<p>Side-note: <code>x =&gt; y(x)</code> is the same as just <code>y</code>, so the last line could be refactored:</p>\n<pre><code>const evenNumbers = numbers.filter(isEven);\n</code></pre>\n<p>How clean is that?!</p>\n<p>Applying this newfound knowledge, your code could look like this:</p>\n<pre><code>const isValidDate = date =&gt; weather[date].length &gt;= 4;\n// ...\nreturn dates\n .filter(isValidDate)\n .map(/*...*/);\n</code></pre>\n<p>In a later mapping, you check if some date is a member of the set <code>DATES_TO_SHOW</code>, and return <code>null</code> if it isn't:</p>\n<pre><code>weather[weatherDate].map((weatherTime, _index) =&gt; {\n const time = weatherTime.validTime.slice(\n weatherTime.validTime.indexOf(&quot;T&quot;) + 1,\n weatherTime.validTime.length - 4\n );\n if (TIMES_TO_SHOW.indexOf(time) === -1) return null;\n return (\n &lt;p key={&quot;weather-data-&quot; + _index}&gt;\n {time}\n &lt;/p&gt;\n );\n}\n</code></pre>\n<p>We just learned that we should filter out unwanted items before we render, so let's take a look at how we could solve this:</p>\n<pre><code>const weatherToTime = weatherTime =&gt; weatherTime.validTime.slice(\n weatherTime.validTime.indexOf(&quot;T&quot;) + 1,\n weatherTime.validTime.length - 4\n);\nconst shouldShowTime = time =&gt; TIMES_TO_SHOW.includes(time);\n// Notice how I used Array.includes instead of .indexOf(x) === -1\n// as .includes is much more autological\n\nweather[weatherDate]\n .map(weatherToTime)\n .filter(shouldShowTime)\n .map((time, _index) =&gt; (\n &lt;p key={&quot;weather-data-&quot; + _index}&gt;\n {time}\n &lt;/p&gt;\n );\n</code></pre>\n<br/>\n<br/>\n<h2> Slice it up</h2>\n<p>Sometimes you just don't care about the first <code>n</code> elements of an array.</p>\n<pre class=\"lang-js prettyprint-override\"><code>dates.map((weatherDate, index) =&gt; {\n if (\n index === 0\n ) {\n return null;\n }\n /* ... */\n);\n</code></pre>\n<p>You could check the index in every iteration and return <code>null</code> in iteration zero, but, again, <em>what if we could skip rendering that item completely?</em></p>\n<p>In some languages there's a function called <code>skip</code> or <code>drop</code>, and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice\" rel=\"nofollow noreferrer\">in javascript we have <code>Array.slice</code></a>. Since you used slice in your code, you might already know how it works so you might want to <em>skip</em> over the next codeblock.</p>\n<p>With <code>slice</code> you can skip some elements from the start of an array, and optionally drop some from its end:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const digitsAndLetters = [0, 1, 2, 3, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;];\nconst letters = digitsAndLetters.slice(4);\n// &gt; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]\nconst digits = digitsAndLetters.slice(0, 4);\n// &gt; [0, 1, 2, 3]\n</code></pre>\n<p>So in your case, to skip the first element of <code>dates</code>, we slice 1 item off the start:</p>\n<pre class=\"lang-js prettyprint-override\"><code>dates\n .slice(1)\n .filter(isValidDate)\n .map(/* ... */);\n</code></pre>\n<p><em>Ooh baby, look at that!</em> Not only does this just look nicer, it also reduces cognitive load when trying to understand what your code does. Again: separate &quot;<em>what</em> do we render?&quot; and &quot;<em>how</em> do we render?&quot; Separating <em>what</em> and <em>how</em> is actually a great refactoring for all code.</p>\n<br/>\n<hr />\n<br/>\n<h1>️ Meaningful keys</h1>\n<p><a href=\"https://robinpokorny.medium.com/index-as-a-key-is-an-anti-pattern-e0349aece318\" rel=\"nofollow noreferrer\">You really shouldn't be using the map index as a key.</a> Why? In short: React uses keys to identify elements between renders. This means that react assumes keys are <em>stable</em>, meaning the key to some data must always be the same. When using <code>index</code> as a key, you're coupling data to something <em>unrelated</em> (i.e. the iteration count) and thus unstable (sorting your list would change the order of data but not the order of <code>index</code> which might result in render bugs).</p>\n<p>In your case it's not directly a concern, but anything that <em>can</em> go wrong, <em>will</em> go wrong.</p>\n<p>A simple solution is to use some identifying property of your data. Maybe some property <code>id</code> exists? Or another property that differs from item to item? If you have a date, you could for example <code>.toString()</code> it. If it's a complex object <a href=\"https://en.wikipedia.org/wiki/Hash_function\" rel=\"nofollow noreferrer\">you could hash its contents to get a unique identifying value</a>.</p>\n<p>Depending on your data, you should be using one of these approaches (or something similar).</p>\n<pre><code>data.map(item =&gt; (\n &lt;div key={item.id}/&gt;\n &lt;div key={item.toString()}/&gt;\n &lt;div key={hash(item)}/&gt;\n))\n</code></pre>\n<br/>\n<hr />\n<br/>\n<h1> Embrace expressions</h1>\n<p>You write a lot of arrow functions with blocks, which kind of defeat their purpose. In most languages an arrow function (often called a lambda) is a syntactical construct to take one argument and transform it, returning the result of that transformation. In other words, there is an implicit <code>return</code> when you don't use blocks:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const double = (number) =&gt; {\n return number * 2;\n};\nconst numbers = [1, 2, 3];\nconst doubledNumbers = numbers.map(double);\n//&gt; [2, 4, 6];\n</code></pre>\n<p>can also be expressed as</p>\n<pre class=\"lang-js prettyprint-override\"><code>const double = number =&gt; number * 2;\n// Note that parentheses are optional when working\n// with a single parameter\nconst numbers = [1, 2, 3];\nconst doubledNumbers = numbers.map(double);\n//&gt; [2, 4, 6];\n</code></pre>\n<p>The following is a little rant so feel free to skip to the recap.</p>\n<p>I don't know why the people in the ECMAScript committee decided blocks should be allowed in arrow functions. We already had <code>function () {}</code>. Because blocks and object literals use the same characters in the grammar, we need to put parentheses around an object in an arrow function:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// You could be fooled into thinking this would return an object\nconst Person = name =&gt; {\n name: name,\n age: Math.random()\n};\n// But no, that's a syntax error -- javascript is trying to parse it\n// as a block. We need to put parentheses around it to tell javascript\n// we're definitely giving it an expression here.\nconst Person = name =&gt; ({\n name: name,\n age: Math.random()\n});\n</code></pre>\n<p>Arrgh!! </p>\n<br/>\n<hr />\n<br/>\n<h1> Recap</h1>\n<p>All right, we've done it! Hopefully you learned a thing or two. The main takeaways are:</p>\n<ul>\n<li>Use <code>Fragment</code>s to group data.</li>\n<li>Separate <em><strong>what</strong></em> from <em><strong>how</strong></em>.</li>\n<li>Use meaningful keys for jsx elements in React.</li>\n<li><a href=\"https://www.nhs.uk/conditions/repetitive-strain-injury-rsi/\" rel=\"nofollow noreferrer\">Don't get RSI</a>: (x) =&gt; { return y; } is the same as x =&gt; y.</li>\n<li><a href=\"https://en.wikipedia.org/wiki/Dieter_Rams#%22Good_design%22_principles\" rel=\"nofollow noreferrer\">To use a beautifully apt quote from Dieter Rams</a>: Less is more (<a href=\"https://www.youtube.com/watch?v=QHZ48AE3TOI\" rel=\"nofollow noreferrer\">unless you're Yngwie Malmsteen</a>).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T00:25:10.593", "Id": "270457", "ParentId": "270411", "Score": "1" } } ]
{ "AcceptedAnswerId": "270457", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T09:13:23.517", "Id": "270411", "Score": "1", "Tags": [ "javascript", "html", "hash-map", "react.js", "jsx" ], "Title": "React - Component rendering weather data" }
270411
<p>As already written in the title I want to count the numbers in the range (x+1, y) where x and y are integers, in which the sum of the digits in odd places have the same parity of the ones in even places. I made this code:</p> <pre><code>def findIntegers(x, y): count = 0 for k in range(int(x)+1, int(y)+1): odd_sum = 0 even_sum = 0 k = str(k) odd_sum += sum([int(k[i]) for i in range(1, len(k), 2) if i % 2 == 1]) even_sum += sum([int(k[i]) for i in range(0, len(k), 2) if i % 2 == 0]) if (odd_sum % 2) == (even_sum % 2): count += 1 return count </code></pre> <p>The code works but for very big range it's very slow. How can I improve my code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T11:23:41.837", "Id": "533994", "Score": "1", "body": "And clarify the task; is x excluded from the range and y included?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T02:45:23.210", "Id": "534053", "Score": "0", "body": "\"even places have same parity as odd places\" reduces to very simple rule: the mod 2 sum of **all** the digits equals 0. No need to break it into two pieces. Also, if you just look at some example ranges you'll notice a very simple pattern to the count, so you don't need to actually run through the values." } ]
[ { "body": "<h3>Use type hints and unit tests</h3>\n<p>They are simple and make your code better.</p>\n<h3>Some improvements and pythonification</h3>\n<p><code>odd_sum</code> and <code>even_sum</code> are initialized with zeroes before adding to them, so you can simply initialize them instead of adding:</p>\n<pre><code>for k in range(int(x)+1, int(y)+1):\n k = str(k)\n odd_sum = ...\n even_sum = ...\n</code></pre>\n<p><code>range</code> with step 2 already omits evens or odds, so the <code>if</code> part isn't needed:</p>\n<pre><code>odd_sum = sum([int(k[i]) for i in range(1, len(k), 2)])\n</code></pre>\n<p>Moreover, you don't need the index <code>i</code>, you need only digits, so you can use slice instead of <code>range</code>:</p>\n<pre><code>odd_sum = sum(int(digit) for digit in k[1::2])\n</code></pre>\n<h3>Better algorithm</h3>\n<p>If a number <code>x</code> has this property and adding 1 doesn't cause change in other digits except the last, <code>x+1</code> will don't have this property, <code>x+2</code> will have it once again etc. So among every 10 consecutive numbers staring with ...0 there will be 5 fitting numbers. You should check only starting and ending numbers, the half of the rest will do in any case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T13:18:37.177", "Id": "534001", "Score": "1", "body": "Sorry, I'm sure that this is correct but I don't understand the last sentence `You should check only starting and ending numbers, the half of the rest will do in any case`. Do you mean if `a=10` and`b=100` I should check only a and b or do you mean for every number I should check the starting and the ending digit?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T14:13:06.220", "Id": "534006", "Score": "0", "body": "Only 10 and 100. The answer should be somewhere around (100-10)/2 depending on whether 10 and 100 fit the condition (in fact, it's exactly 45)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T18:18:08.010", "Id": "534034", "Score": "0", "body": "one last question @PavloSlavynskyy, how did you come up to the solution? Is there some related problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T21:47:15.390", "Id": "534037", "Score": "0", "body": "Thnx @AJNeufeld, fixed.\n\n2DarkSkull No, just an observation." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T11:33:57.640", "Id": "270415", "ParentId": "270414", "Score": "3" } }, { "body": "<p>First some code simplifications and other adjustments. (1) Your sum\ncalculations don't need the conditional tests, because the ranges already\nensure compliance. (2) They also don't need to be wrapped in a <code>[]</code>. (3)\nEven better, if you switch from ranges to slices, you don't need to loop with\nin the sum calculations: just give a slice directly to <code>sum()</code>. In order to do\nthat, you can perform string-to-int conversion in one place, before summing.\n(4) Because <code>bool</code> is a subclass of <code>int</code>, your count-incrementing code does\nnot require conditional logic. (5) This function is difficult to describe and\nname compactly, but your current name is especially vague. Here's a possible\nrenaming. (6) Finally, and this is done purely to simplify the rest of the\ndiscussion, I have modified the function to do the counting over an inclusive\nrange.</p>\n<pre><code>def n_parity_balanced_integers(x, y):\n count = 0\n for number in range(x, y + 1):\n digits = tuple(map(int, str(number)))\n count += sum(digits[0::2]) % 2 == sum(digits[1::2]) % 2\n return count\n</code></pre>\n<p>Such edits improve the code, but they do not significantly affect the\nalgorithm's speed. It's still a brute-force solution. The key to making further\nprogress is to find a pattern that can be used to radically reduce the needed\ncomputation. One way to find these patterns is to experiment with the data. For\nexample:</p>\n<pre><code># A brief experiment.\nchecks = [\n (0, 9),\n (0, 99),\n (0, 999),\n (0, 9999),\n (10, 19),\n (20, 29),\n (10, 39),\n]\nfor lower, upper in checks:\n print(f'{lower}-{upper}:', n_parity_balanced_integers(lower, upper))\n\n# Output\n0-9: 5\n0-99: 50\n0-999: 500\n0-9999: 5000\n10-19: 5\n20-29: 5\n10-39: 15\n</code></pre>\n<p>In other words, over any inclusive range spanning an entire power-of-ten's\nworth of numbers (or any multiple of that, such as <code>10-39</code>), you can instantly\ncompute the answer without iterating over every discrete number in the range.\nSo the trick to this problem is to start with the full range, decompose it into\nsubcomponents that can be computed instantly, and then brute-force any\nstraggling bits. Give that a shot a see what you come up with.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T20:35:01.453", "Id": "270428", "ParentId": "270414", "Score": "5" } }, { "body": "<p>By making a few observations an O(1) algorithm can be devised. First note that the statement</p>\n<blockquote>\n<p>the sum of the digits in odd places have the same parity of the ones\nin even places</p>\n</blockquote>\n<p>is equivalent to the statement that the sum of all the digits equals 0 mod 2. Equivalently, the XOR of the low-order bit of all the digits equals 0. The following function implements this</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Sequence\n\ndef is_same_parity(digits: Sequence[int]) -&gt; bool:\n return sum(digits) % 2 == 0\n</code></pre>\n<p>The next observation is actually the only important one in term of algorithmic complexity. Every sequence of 10 contiguous integers that starts with a multiple of 10 always has exactly 5 values whose (base 10) digits sum to 0 mod 2. If the first value of the sub sequence <code>a</code> (<code>a mod 10 == 0</code>) has digits that sum to 0 then the five values are a, a+2, a+4, a+6, and a+8. Otherwise, the values are a+1, a+3,a+5, a+7, and a+9.</p>\n<p>We can therefore break our range into three pieces, a beginning piece that goes to the next multiple of 10, a trailing piece that goes from the last multiple of 10 to the end, and a third piece that is everything between the first and last multiple of 10 in the sequence.</p>\n<p>The following code implements this idea</p>\n<pre class=\"lang-py prettyprint-override\"><code>def find_integers_helper(x: int, y: int) -&gt; int:\n &quot;&quot;&quot;\n Counts integers whose base10 digits sum to 0 mod 2 in the range\n x &lt;= z &lt; y\n Break into 3 separate ranges:\n 1) x &lt;= z1 &lt; y1, where y1 = 10 * ceiling(x / 10), and\n 2) y1 &lt;= z2 &lt; y2, where y2 = 10 * floor(y / 10), and\n 3) y2 &lt;= z3 &lt; y\n :param x:\n :param y:\n :return:\n &quot;&quot;&quot;\n \n y1, y2 = 10 * ceil_div(x, 10), 10 * floor_div(y, 10)\n c1 = sum(1 for z1 in range(x, y1) if is_same_parity(to_digits(z1)))\n c2 = (y2 - y1) // 2\n c3 = sum(1 for z3 in range(y2, y) if is_same_parity(to_digits(z3)))\n\n return c1 + c2 + c3\n\n# some simple helper functions\n\ndef ceil_div(n: int, d: int) -&gt; int:\n return (n + d - 1) // d\n\n\ndef floor_div(n: int, d: int) -&gt; int:\n return n // d\n\n\ndef to_digits(x: int) -&gt; tuple[int]:\n return tuple(int(d) for d in str(x))\n\n\n</code></pre>\n<p>When I reason about ranges I have a strong preference to think about ranges that look like x &lt;= y &lt; z. It's just the way I've done it my whole life. Your code wants a slightly different range, so your method can call my method with a slight adjustment:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def find_integers(x: int, y: int) -&gt; int:\n return find_integers_helper(x + 1, y + 1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T16:07:02.690", "Id": "534083", "Score": "0", "body": "`to_digits` is not defined" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T16:59:31.257", "Id": "534091", "Score": "0", "body": "@DarkSkull: Whoops!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T15:11:35.533", "Id": "270448", "ParentId": "270414", "Score": "1" } } ]
{ "AcceptedAnswerId": "270428", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T10:25:13.987", "Id": "270414", "Score": "6", "Tags": [ "python", "performance", "integer", "interval" ], "Title": "Count the numbers in a range in which the sum of the odds digits have the same parity of the evens one" }
270414
<p>For a program I'm writing, it requires a lot of printing and receiving user input. I've found it cumbersome to keep specifying the type strings in <code>printf</code>, and having to write another <code>printf</code> before using <code>scanf</code> to receive input. I've decided to write two macros, <code>print</code> and <code>input</code>, that achieve exactly what I want. A simplified function call that prints the types I need to print, and an input macro that allows me to pass a prompt and a variable to the same function.</p> <p>Another concept I've included in the header file is pythons module-like structure. With specific defines, I can decide which functions I want to compile/use at a certain time. While there hasn't been a significant difference in compile speed when importing one function vs the entire file, my project will get exponentially large, so this might provide some time save. Is this something I should continue to implement? Or is the speed increase negligible to the point where it's a waste of time to write?</p> <p>I would like to know if this is the best way to go about this. Having more experience in <code>C++</code>, I've learned to appreciate the nuances of <code>C</code>. Some of it looks convoluted, but I've trying to cover all my bases to avoid duplicate declarations of macros and writing the safest code possible. Any and all input and recommendations are appreciated and considered.</p> <p><strong>IO.h</strong></p> <pre><code>#ifndef IO_H #define IO_H #ifdef IO_IMPORT_ALL #define PRINT #define INPUT #define TYPE_FINDER #endif #ifdef PRINT #include &lt;tgmath.h&gt; #include &lt;stdio.h&gt; #if !defined(TYPE_FINDER) || !defined(INPUT) #define TYPE_FINDER #endif #ifdef PRINT_NEWLINE #define print(value) do { \ printf(type_finder(value), value); \ printf(&quot;\n&quot;); \ } while (0) #else #define print(value) printf(type_finder(value), value) #endif #endif #ifdef INPUT #include &lt;stdio.h&gt; #include &lt;tgmath.h&gt; #if !defined(TYPE_FINDER) || !defined(PRINT) #define TYPE_FINDER #endif #define input(prompt, variable) do { \ printf(&quot;%s&quot;, prompt); \ scanf(type_finder(variable), &amp;variable); \ } while (0) #endif #ifdef TYPE_FINDER #define type_finder(type) _Generic((type), \ char: &quot;%c&quot;, \ int: &quot;%d&quot;, \ float: &quot;%f&quot;, \ unsigned int: &quot;%u&quot;, \ char*: &quot;%s&quot;, \ void*: &quot;%p&quot; \ ) #endif #endif // IO_H </code></pre> <p><strong>main.c</strong></p> <pre><code>#define IO_IMPORT_ALL #define PRINT_NEWLINE #include &quot;IO.h&quot; void PrintTest(void) { print((char)'c'); print(10); print(24.7f); print((unsigned int)24); print(&quot;test&quot;); print((void*)&quot;abcde&quot;); } void InputTest(void) { int number; input(&quot;Enter a number: &quot;, number); print(number); } int main() { PrintTest(); InputTest(); return 0; } </code></pre> <p>I'm specifically tagging <code>C11</code> because I need to use <code>_Generic</code> to distinguish the types passed to the macros.</p> <p>If you want to run this code, here's my <code>run.sh</code></p> <pre><code>gcc main.c -o main ./main rm main </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T13:56:23.407", "Id": "534005", "Score": "0", "body": "I don't think the C11 tag is necessary for code that works fine with current standard C (i.e. C17)." } ]
[ { "body": "<p>This looks like a missed opportunity. I was hoping to see something that would usefully handle re-trying when the input can't be parsed, but instead we have a macro that throws away the return value from <code>scanf()</code>, so that we have no idea whether it was successful or not.</p>\n<p>I'm not a fan of headers that change their behaviour according to what macros are earlier defined. This is especially worrying as only the macros that are defined the <em>first</em> time it's included will have any effect. I'm not sure that is a successful idea - if the namespace pollution is a problem, it's probably easier to <code>#include</code> the header and then <code>#undef</code> the problematic names.</p>\n<p>Talking of names, it's usual to use ALL_CAPS for macros - particularly ones like these, which expand arguments more than once. Macros don't behave like functions, and it's useful to be warned.</p>\n<p>This looks surprising:</p>\n<blockquote>\n<pre><code>#if !defined(TYPE_FINDER) || !defined(INPUT)\n #define TYPE_FINDER\n#endif\n</code></pre>\n</blockquote>\n<p>Why does <code>defined(INPUT)</code> need to be considered?</p>\n<p>I'd simplify further - just unconditionally define it:</p>\n<pre><code> #undef TYPE_FINDER\n #define TYPE_FINDER\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T18:10:12.763", "Id": "534031", "Score": "0", "body": "Thanks for the review! I totally overlooked error handling when `scanf` fails. I went about the header to reduce compile time if the user only wants to use a specific function in the header. That may be ignorant, but I figured it could provide some performance improvements. I used `print` and `input` not using all caps because it just looks like a simple function call, which is what I was trying to accomplish. Thanks for pointing out the convolution in the multiple `#defines` with `type_finder`! It looked messy, and I'm glad another person agreed with me and provided some solutions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T08:26:47.880", "Id": "534271", "Score": "0", "body": "I think that any difference in compile time is likely to be imperceptible. But if you care about it, don't just accept my guess - measure! And remember that debugging time is more expensive than compilation time..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T13:54:41.540", "Id": "270418", "ParentId": "270416", "Score": "2" } }, { "body": "<p>I found this very interesting and was not aware of the <code>_Generic</code> operation in C.</p>\n<p>The following are really more questions than suggestions.</p>\n<p>Is there any specific reason for including <code>tgmath.h</code>?</p>\n<p>The <code>do</code> ... <code>while(0)</code> construct seems odd to me. It looked like you used to force the inner part into a scope of its own. Is there any specific reason why you could not have simply used:</p>\n<pre><code>#define print(value) { \\\n printf(type_finder(value), value); \\\n printf(&quot;\\n&quot;); \\\n }\n</code></pre>\n<p><code>print</code> only allows some basic types. It will result in an error if you try to print for example a <code>double</code>. Is this by design or just to simplify the example code?</p>\n<hr>\n<p>I have tried to compile this with MSVC but it looks like its not happy with the <code>_Generic</code> operation. Most likely I'm just missing the correct build option.</p>\n<p>Intel C compiler generates some warnings, mostly about it not liking <code>scanf</code></p>\n<pre><code>note: 'scanf' has been explicitly marked deprecated here\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T18:13:22.947", "Id": "534032", "Score": "1", "body": "Thanks for the review! While writing the header, I thought I needed `tgmath.h` to actually use `_Generic`. Running it again just now, I realized the opposite. The `do-while` was my way of having multi-line macros, but looking at your proposition, that looks a lot cleaner. The `print` function was written based on types that I needed to print specifically, but I probably should expand it to print *all* types of variables. I compiled this using `gcc` on a Mac, and again with `-Wall` enabled, and I didn't get that compiler warning. Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T13:28:07.500", "Id": "534072", "Score": "0", "body": "Concerning \"tried to compile this with MSVC\" --> Are you compiling with a version that is C99, C11 or C17 compatible or are you using a compiler that only handles pre-C99 (22+ year old) code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T13:29:37.970", "Id": "534073", "Score": "0", "body": "The \"'scanf' has been explicitly marked deprecated here\" is not deprecated by the C spec, but by some other standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T14:31:03.910", "Id": "534076", "Score": "1", "body": "@chux-ReinstateMonica, yeah I missed the /std:c11 flag, compiles now with msvc except for the _CRT_SECURE_NO_WARNINGS crap." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T10:23:41.270", "Id": "534208", "Score": "1", "body": "Regarding do-while(0) macros and why we should (not) use them, see: [What is do { } while(0) in macros and should we use it?](https://software.codidact.com/posts/279576)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T12:39:11.817", "Id": "534212", "Score": "0", "body": "@Lundin interesting, thanks!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T18:02:01.103", "Id": "270426", "ParentId": "270416", "Score": "2" } }, { "body": "<blockquote>\n<p>I would like to know if this is the best way to go about this</p>\n</blockquote>\n<p>Over all: Good <a href=\"https://en.wikipedia.org/wiki/Journeyman\" rel=\"nofollow noreferrer\">journeyman</a> effort for printing. Unusable for reading.</p>\n<hr />\n<p><strong>Non-C syntax</strong></p>\n<p>Code <em>looks</em> wrong as it appears that <code>input()</code> takes 2 arguments: a <code>char *</code> and an (uninitialized) <code>int</code>. Instead, via the underlying macro, it is the <code>&amp; number</code> that is used. I suspect C++ influence here.</p>\n<pre><code>int number;\ninput(&quot;Enter a number: &quot;, number);\n</code></pre>\n<p>I'd expect the below and changes in the macro to support it.</p>\n<pre><code>input(&quot;Enter a number: &quot;, &amp;number);\n</code></pre>\n<p><strong>Input Woes</strong></p>\n<p>To input a <code>char</code> and function like the others, I'd expect <code>&quot; %c&quot;</code> rather than <code>&quot;%c&quot;</code>.</p>\n<p>Much is missing from input</p>\n<ol>\n<li><p>Error handing - how to convey input is bad?</p>\n</li>\n<li><p><code>stdin</code> recovery - what is the state of <code>stdin</code> with bad input? Is all the input line read? Consider challenging input for an <code>int</code> like <code>&quot;123xyz&quot;</code>, <code>&quot;123.0&quot;</code>, <code>&quot;\\n&quot;</code>, <code>&quot;123456789012345678901234567890&quot;</code>, <code>&quot;0x123&quot;</code>, ...</p>\n</li>\n<li><p><code>fgets()</code> is much more robust than <code>scanf()</code>. This <code>input()</code> leaves the trailing <code>'\\n'</code> in <code>stdin</code>, like typical <code>scanf()</code> usage, discouraging use with the good <code>fgets()</code>.</p>\n</li>\n</ol>\n<p><strong>Input Woes 2</strong></p>\n<p>Try below. I get <code>format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[80]' [-Wformat=]</code></p>\n<pre><code>char number[80];\ninput(&quot;Enter text: &quot;, number);\n</code></pre>\n<p><strong>Input Woes 3</strong></p>\n<p>Passing a <code>char *</code> to <code>input()</code> results in a <code>char **</code> passed to <code>scanf(&quot;%s&quot;, ...)</code> - mis-matched type leads to UB.</p>\n<pre><code>warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char **' [-Wformat=]\n</code></pre>\n<p><strong>Input strings</strong></p>\n<p><code>&quot;%s&quot;</code> is <em>not</em> for reading <em>strings</em>. At best <code>scanf(&quot;%s&quot;, ...</code> reads a <em>word</em> (text input without white-space). Consider</p>\n<pre><code>char *name = malloc(80);\ninput('Enter full name&quot;, name);\n</code></pre>\n<p>This is worse than <a href=\"https://stackoverflow.com/q/1694036/2410359\">gets</a> with no input limit, inability to read and save spaces and leaves <code>'\\n'</code> in <code>stdin</code>.</p>\n<p><strong>Competing goals</strong></p>\n<p>&quot;Simplified print and input&quot; or a header only solution?</p>\n<p>Use of macros loses type checking in the <code>prompt</code> and loss of return values.</p>\n<p>If a &quot;simplified print and input&quot; can be made better with a <code>IO.c</code>, I suspect it can, do not constrain the code to an IO.h only solution.</p>\n<p><strong><code>double</code> ?</strong></p>\n<p>Generically printing floating point with <code>&quot;%f&quot;</code> may be <em>safe</em>, yet it is not satisfactory with much of the range. Large <code>float</code> values have potentially dozens of uninformative digits and 40% of all <code>float</code> (the small ones) print <code>&quot;0.000000&quot;</code> or <code>&quot;-0.000000&quot;</code>. <code>&quot;%f&quot;</code> also does not distinctively print many different <code>float</code> values - use more precision.</p>\n<p>Instead keep the <em>floating</em> in floating point. In the <code>_Generic_</code> for output:</p>\n<pre><code> float: &quot;%.9g&quot;, \\\n double: &quot;%.17g&quot;, \\\n</code></pre>\n<p>... or other code that drives the 9,17 from <code>FLT_DECIMAL_DIG, DBL_DECIMAL_DIG</code>.</p>\n<p><strong>Avoid casts</strong></p>\n<pre><code>// print((unsigned int)24);\nprint(24u);\n</code></pre>\n<p><strong>Missing types</strong></p>\n<p>Certainly code is a concept, but to note there are <em>many</em> other types</p>\n<ul>\n<li><code>signed char</code>, <code>unsigned char</code></li>\n<li><code>short</code>, <code>unsigned char</code></li>\n<li><code>long</code>, <code>unsigned long</code></li>\n<li><code>long long</code>, <code>unsigned long long</code></li>\n<li><code>double</code>, <code>long double</code></li>\n<li><code>complex float</code>, <code>complex double</code>, <code>complex long double</code></li>\n</ul>\n<p>Types like <code>size_t</code>, <code>uint64_t</code>, <code>intmax_t</code>, <code>intptr_t</code>, <code>wchar_t</code>, etc. may or may not have been already listed above. It takes creative use of <code>_Generic</code> to handle these.</p>\n<p><strong>Name space</strong></p>\n<p>Including <code>io.h</code> surprisingly defines <code>print</code> and <code>input</code>. These very popular names can likely collide with other code. Perhaps <code>io_print, io_input</code> instead?</p>\n<p><strong>Lighter code</strong></p>\n<pre><code>// printf(&quot;%s&quot;, prompt);\nfputs(prompt, stdout);\n</code></pre>\n<hr />\n<p>See also: <a href=\"https://codereview.stackexchange.com/q/115143/29485\">Formatted print without the need to specify type matching specifiers using _Generic</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T12:45:14.873", "Id": "270441", "ParentId": "270416", "Score": "1" } } ]
{ "AcceptedAnswerId": "270418", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T11:47:57.413", "Id": "270416", "Score": "2", "Tags": [ "c", "macros", "c11" ], "Title": "Simplified print and input macros in C" }
270416
<p>Modules for FPGAs for generating a pseudo-random bit sequence are presented. The first module generates a bit sequence. The third module speeds up the generation by transferring the bus to, for example, a multiplexer which is controlled by a faster device. Hence this bus is serialized into a bit sequence.</p> <p>prbs.sv</p> <pre><code>`timescale 1ns / 1ps module prbs # ( parameter integer PN = 7 //3, 4, 5, 6, 7, 9, 11, 15, 17, 23, 31, 32, 36, 41 ) ( input logic i_clk, input logic i_s_rst_n, input logic i_en, output logic o_prbs, output logic o_prbs_n ); localparam integer TAP_1 = (PN == 3) ? 2 : (PN == 4) ? 3 : (PN == 5) ? 4 : (PN == 6) ? 5 : (PN == 7) ? 6 : (PN == 9) ? 7 : (PN == 11) ? 10 : (PN == 15) ? 14 : (PN == 17) ? 16 : (PN == 23) ? 22 : (PN == 31) ? 30 : (PN == 32) ? 31 : (PN == 36) ? 35 : (PN == 41) ? 40 : 0; localparam integer TAP_0 = (PN == 3) ? 0 : (PN == 4) ? 2 : (PN == 5) ? 2 : (PN == 6) ? 4 : (PN == 7) ? 0 : (PN == 9) ? 4 : (PN == 11) ? 8 : (PN == 15) ? 0 : (PN == 17) ? 2 : (PN == 23) ? 17 : (PN == 31) ? 27 : (PN == 32) ? 21 : (PN == 36) ? 24 : (PN == 41) ? 37 : 0; logic [PN - 1 : 0] lfsr; always_comb begin o_prbs = lfsr[PN - 1]; o_prbs_n = ~lfsr[PN - 1]; end always_ff @ (posedge i_clk) begin if (i_s_rst_n == 1'h0) begin lfsr &lt;= '1; end else if (i_en == 1'h1) begin lfsr &lt;= {lfsr[PN - 2 : 0], lfsr[TAP_1] ^ lfsr[TAP_0]}; end end endmodule </code></pre> <p>prbs_tb.sv</p> <pre><code>`timescale 1ns / 1ps module prbs_tb; localparam integer PN = 7; //3, 4, 5, 6, 7, 9, 11, 15, 17, 23, 31, 32, 36, 41 localparam integer PERIOD = 2 ** PN; localparam integer CLOCK_PERIOD = 100; localparam integer TEST_ITERATION = 1000; localparam integer CHANGE_EN_VAL = 100; logic clk = '0; logic s_rst_n = '0; logic en = '0; logic prbs = '0; logic prbs_n = '0; integer tick = 0; prbs # ( .PN (PN) ) prbs_dut ( .i_clk (clk ), .i_s_rst_n (s_rst_n), .i_en (en ), .o_prbs (prbs ), .o_prbs_n (prbs_n ) ); initial begin forever begin #( CLOCK_PERIOD / 2 ) clk = !clk; end end initial begin s_rst_n &lt;= '0; @(posedge clk); s_rst_n &lt;= '1; en &lt;= '1; @(posedge clk); for(int i = 0; i &lt; TEST_ITERATION; i++) begin if ((i % PERIOD) == (PERIOD - 1)) begin en &lt;= ~en; tick = 0; end else begin tick++; end @(posedge clk); end $finish; end endmodule </code></pre> <p>prbs_wide.sv</p> <pre><code> `timescale 1ns / 1ps module prbs_wide # ( parameter integer PN = 7, //3, 4, 5, 6, 7, 9, 11, 15, 17, 23, 31, 32, 36, 41 parameter integer WIDTH = 16 ) ( input logic i_clk, input logic i_s_rst_n, input logic i_en, output logic [WIDTH - 1 : 0] o_prbs, output logic [WIDTH - 1 : 0] o_prbs_n ); localparam integer TAP_1 = (PN == 3) ? 2 : (PN == 4) ? 3 : (PN == 5) ? 4 : (PN == 6) ? 5 : (PN == 7) ? 6 : (PN == 9) ? 7 : (PN == 11) ? 10 : (PN == 15) ? 14 : (PN == 17) ? 16 : (PN == 23) ? 22 : (PN == 31) ? 30 : (PN == 32) ? 31 : (PN == 36) ? 35 : (PN == 41) ? 40 : 0; localparam integer TAP_0 = (PN == 3) ? 0 : (PN == 4) ? 2 : (PN == 5) ? 2 : (PN == 6) ? 4 : (PN == 7) ? 0 : (PN == 9) ? 4 : (PN == 11) ? 8 : (PN == 15) ? 0 : (PN == 17) ? 2 : (PN == 23) ? 17 : (PN == 31) ? 27 : (PN == 32) ? 21 : (PN == 36) ? 24 : (PN == 41) ? 37 : 0; logic [PN - 1 : 0] lfsr; logic [PN - 1 : 0] r_lfsr; logic [WIDTH - 1 : 0] tmp; always_comb begin lfsr = r_lfsr; for (int i = WIDTH - 1; i &gt;= 0; i = i - 1) begin lfsr = {lfsr[PN - 2 : 0], lfsr[TAP_1] ^ lfsr[TAP_0]}; tmp[i] = lfsr[TAP_1] ^ lfsr[TAP_0]; end end always_ff @ (posedge i_clk) begin if (i_s_rst_n == 1'h0) begin r_lfsr &lt;= '1; o_prbs &lt;= '0; o_prbs_n &lt;= '1; end else if (i_en == 1'h1) begin r_lfsr &lt;= lfsr; o_prbs &lt;= tmp; o_prbs_n &lt;= ~tmp; end end endmodule </code></pre> <p>prbs_wide_tb.sv</p> <pre><code>`timescale 1ns / 1ps module prbs_wide_tb; localparam integer PN = 7; localparam integer PERIOD = 2 ** PN - 1; localparam integer WIDTH = 128; localparam integer CLOCK_PERIOD = 100; localparam integer TEST_ITERATION = 1000; localparam integer CHANGE_EN_VAL = 100; logic clk = '0; logic s_rst_n = '0; logic en = '0; logic [WIDTH - 1 : 0] prbs = '0; logic [WIDTH - 1 : 0] prbs_n = '0; prbs_wide # ( .PN (PN ), .WIDTH (WIDTH) ) prbs_wide_dut ( .i_clk (clk ), .i_s_rst_n (s_rst_n), .i_en (en ), .o_prbs (prbs ), .o_prbs_n (prbs_n ) ); initial begin forever begin #( CLOCK_PERIOD / 2 ) clk = !clk; end end initial begin s_rst_n &lt;= '0; @(posedge clk); s_rst_n &lt;= '1; en &lt;= '1; @(posedge clk); for(int i = 0; i &lt; TEST_ITERATION; i++) begin if ((i % PERIOD) == PERIOD - 1) begin en &lt;= ~en; end @(posedge clk); end $finish; end endmodule </code></pre>
[]
[ { "body": "<p>I get compile errors on 2 different simulators (Cadence and Synopsys) from these 2 lines in the testbench:</p>\n<pre><code>logic prbs = '0;\nlogic prbs_n = '0;\n</code></pre>\n<p>Since you connect those signals to the module instance output ports, you should not set them to any value in the declaration lines. Your code has multiple drivers of the signals:</p>\n<ol>\n<li>The module instance output port.</li>\n<li>The continuous driver of your <code>logic</code> declaration.</li>\n</ol>\n<p>Just declare the signals without an assignment:</p>\n<pre><code>logic prbs ;\nlogic prbs_n;\n</code></pre>\n<p>Aside from that, I do not see any other functional problems with your code. The layout follows good coding practices, and you make good use of parameters.</p>\n<p>In the testbench, you could take advantage of 2-state signal types. This could lead to better simulation performance, and it also better conveys the intent of your code. Since there is no need to drive <code>x</code> or <code>z</code> for your instance inputs, you can use <code>bit</code> instead of <code>logic</code>:</p>\n<pre><code>bit clk;\nbit s_rst_n;\nbit en;\n</code></pre>\n<p>Since all 2-state types default to 0, there is no need to explicitly initialize them to 0 in the declaration or elsewhere. This is purely a matter of convenience and preference. The situation is similar for your testbench counter:</p>\n<pre><code>int tick;\n</code></pre>\n<p>You could simplify your clock using a single line of code:</p>\n<pre><code>always #( CLOCK_PERIOD / 2 ) clk = !clk;\n</code></pre>\n<p>In your design, you could simplify the combinational logic as follows. Change:</p>\n<pre><code>always_comb begin\n o_prbs = lfsr[PN - 1];\n o_prbs_n = ~lfsr[PN - 1];\nend \n</code></pre>\n<p>to the equivalent:</p>\n<pre><code>assign o_prbs = lfsr[PN - 1];\nassign o_prbs_n = ~o_prbs;\n</code></pre>\n<p>This avoids repeating the <code>lfsr</code> expression.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T13:03:31.307", "Id": "270442", "ParentId": "270417", "Score": "4" } } ]
{ "AcceptedAnswerId": "270442", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T12:59:20.153", "Id": "270417", "Score": "2", "Tags": [ "verilog", "fpga", "hdl", "prbs", "systemverilog" ], "Title": "pseudo-random binary sequence (prbs)" }
270417
<p>I want to simplify some code I have written but not sure how to go about doing it. When my workbook opens it checks the current date and compares it to dates I have on a sheet. If the current date is &lt;= date on sheet it writes the date range to a cell. My issue is I have 13 If statements and would like to simply/neaten it up.</p> <p>I know there is a better way to go about if/then statements I just can't remember what it is or how to implement it.</p> <p>Here is my code:</p> <pre><code>Private Sub Workbook_Open() If ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C15&quot;).Value &lt; Date Then ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C3&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C15&quot;) + 28 End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C15&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B15&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C15&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B15&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C15&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C14&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B14&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C14&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B14&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C14&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C13&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B13&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C13&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B13&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C13&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C12&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B12&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C12&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B12&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C12&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C11&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B11&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C11&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B11&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C11&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C10&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B10&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C10&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B10&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C10&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C09&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B09&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C09&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B09&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C09&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C08&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B08&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C08&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B08&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C08&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C07&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B07&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C07&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B07&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C07&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C06&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B06&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C06&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B06&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C06&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C05&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B05&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C05&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B05&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C05&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C04&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B04&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C04&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B04&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C04&quot;).Value End If If Date &lt;= ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C03&quot;).Value Then ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B03&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C03&quot;).Value ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;B03&quot;).Value &amp; &quot; - &quot; &amp; ActiveWorkbook.Sheets(&quot;Period Dates&quot;).Range(&quot;C03&quot;).Value End If End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T14:51:09.843", "Id": "534009", "Score": "2", "body": "Welcome to CodeReview. Your current title applies to virtually every question on this site, so the usual practice is to title your post with what the code is doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T15:00:37.127", "Id": "534010", "Score": "2", "body": "Welcome to the Code Review Community. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask). It will give you a hint on who to title the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T15:03:05.413", "Id": "534011", "Score": "0", "body": "@Teepeemm When a new comer to the site doesn't know that we are looking for a description of what the code does in the title, it is best to send them to the help page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T20:20:35.730", "Id": "534036", "Score": "0", "body": "Is there any known/guaranteed relation between the values in C03…15?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T21:56:20.547", "Id": "534038", "Score": "0", "body": "So the dates are a period of time, C03 is the start date and C15 is the end date" } ]
[ { "body": "<p><strong>DRY</strong></p>\n<p>There is an important software principle called &quot;Don't Repeat Yourself&quot; (DRY). Writing software with frequent use of Copy-Paste is the antithesis of DRY. Not only does it cause repeated expressions with minor differences per copy - it results in code that is difficult to change, debug, and maintain. The purpose of the code is lost in all the <em>typing</em>.</p>\n<p><strong>Code-Behind/Error Handling</strong></p>\n<p>The code provided is initiated by the <code>Open_Workbook</code> event. When your users open this workbook, the Excel application/workbook becomes the initial User-Interface. It is usually a best practice to have as little logic as possible (other than UI logic) in these objects. The code in UI objects is generally referred to as the 'code-behind'. If it is important, in general, to have as little code as possible in the code-behind...then it is especially important when the Workbook object acts as a UI.</p>\n<p>The more code/logic within the Workbook object (or any object for that matter), the greater the chance of errors and exceptions. If simply opening the workbook is going to 'kick-off' any kind of operation, then it would seem especially prudent to gracefully handle startup errors.</p>\n<p>So, it would be advisable to move all the initialization code to a dedicated Standard Module. Call this module from the <code>Workbook_Open</code> event and protect against any errors/exceptions propagating back to the Workbook object without a handler. Further, the call to the dedicated module can take Date object as a parameter. Doing so makes it easy to test or initiate the setup code without having to close and re-open the workbook (example provided below).</p>\n<p>The objects below implement the suggestions above.</p>\n<p><em>ThisWorkbook</em></p>\n<pre><code>Option Explicit\n\nPrivate Sub Workbook_Open()\n If Not SetupModule.TrySetupWorksheets(Date) Then\n MsgBox &quot;Error encountered during startup&quot;\n End If\nEnd Sub\n</code></pre>\n<p><em>SetupModule.bas</em></p>\n<pre><code>Option Explicit\n\n'Initiate the process for test/debugging by calling this macro from Developer -&gt; Macros\nPublic Sub Test()\n If TrySetupWorksheets(Date) Then\n MsgBox &quot;TestFailed&quot;\n End If\nEnd Sub\n\nPublic Function TrySetupWorksheets(ByVal currentDate As Date) As Boolean\n\n TrySetupWorksheets = False\n \nOn Error GoTo ErrorExit\n Dim periodDatesSheet As Worksheet\n Set periodDatesSheet = ActiveWorkbook.Sheets(&quot;Period Dates&quot;)\n \n SetupPeriodDates currentDate, periodDatesSheet\n \n Dim columnCValue As Variant\n \n Dim rowNumber As Long\n For rowNumber = 15 To 3 Step -1\n columnCValue = periodDatesSheet.Range(&quot;C&quot; &amp; CStr(rowNumber)).Value\n If currentDate &lt;= columnCValue Then\n WriteDateExpressionToCells periodDatesSheet.Range(&quot;B&quot; &amp; CStr(rowNumber)).Value &amp; &quot; - &quot; &amp; columnCValue\n End If\n Next\n TrySetupWorksheets = True\n \nErrorExit:\nEnd Function\n\nPrivate Sub SetupPeriodDates(ByVal currentDate As Date, ByVal periodDatesSheet As Worksheet)\n If periodDatesSheet.Range(&quot;C15&quot;).Value &lt; currentDate Then\n periodDatesSheet.Range(&quot;C3&quot;).Value = periodDatesSheet.Range(&quot;C15&quot;) + 28\n End If\nEnd Sub\n\nPrivate Sub WriteDateExpressionToCells(ByVal dateExpression As Variant)\n ActiveWorkbook.Sheets(&quot;North Reading&quot;).Range(&quot;B2&quot;).Value = dateExpression\n ActiveWorkbook.Sheets(&quot;Chelmsford St&quot;).Range(&quot;B2&quot;).Value = dateExpression\nEnd Sub\n \nEnd Sub\n\n<span class=\"math-container\">```</span> \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T21:03:19.750", "Id": "270429", "ParentId": "270421", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T14:38:29.170", "Id": "270421", "Score": "3", "Tags": [ "vba", "excel" ], "Title": "Checking if date falls within a date range then write the date range to a cell" }
270421
<p>Is this the correct way to calculate leap years in a range of [y,x) ?</p> <pre><code>def bis(y1,y2): mas = max(y1,y2) mini = min(y1,y2) k=0 for i in range(mini,mas): if i % 4 == 0 and i % 100 != 0: if i % 400 != 0: k=k+1 return k print(bis(1904,1957)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T17:24:36.913", "Id": "534025", "Score": "3", "body": "No. Consider the year 2000 and compare your code to [StackOverflow](https://stackoverflow.com/a/30714165/55857) on this topic." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T16:52:01.040", "Id": "270425", "Score": "-4", "Tags": [ "python" ], "Title": "Leap year in python brief code" }
270425
<p>This project is based off the shunting yard algorithm and has additional features such as negative value parsing. It's like a scientific calculator. I am looking to improve this project by getting rid of potential errors and optimizing code. I have tried many cases and have fixed the broken ones I've seen. However, although this works, I am aware that the code is quite messy and may potentially have bugs</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;stack&gt; #include &lt;queue&gt; #include &lt;map&gt; #include &lt;cmath&gt; #include &lt;functional&gt; #include &lt;complex&gt; using std::cout; using std::string; using std::getline; using std::complex; using std::abs; using std::vector; using std::stack; using std::queue; using std::transform; using std::invalid_argument; using std::map; using std::function; using namespace std::literals; using std::isinf; using std::isnan; using std::cin; using std::exception; typedef complex&lt;double&gt; cmpd; constexpr unsigned int str2int(const char* str, int h = 0) //string to int conversion for switch case purposes { return !str[h] ? 5381 : (str2int(str, h + 1) * 33) ^ str[h]; } bool isNumber(const string&amp; s) //check if a string is a number { if(s.empty() || ::isspace(s[0]) || isalpha(s[0])) { return false; } char *p; strtod(s.c_str(), &amp;p); return (*p == 0); } cmpd operation(string s, cmpd v1, cmpd v2 = 0, bool deg = false) //operations { switch (str2int(s.c_str())) { case str2int(&quot;+&quot;): return v1 + v2; case str2int(&quot;-&quot;): return v1 - v2; case str2int(&quot;*&quot;): return v1 * v2; case str2int(&quot;#&quot;): //for negative powers return v1 * v2; case str2int(&quot;/&quot;): return v1 / v2; case str2int(&quot;^&quot;): return pow(v1, v2); default: return tgamma(v1.real() + 1); //factorial, technically it is a function but it is conveninent to treat it as an operator here } } cmpd func(string s, cmpd v, cmpd v2 = 0, bool deg = false) //functions, radians { double toRad = acos(-1) / 180.0; double toDeg = 180.0 / acos(-1); if (deg) { switch (str2int(s.c_str())) { case str2int(&quot;sin&quot;): return sin(v * toRad); case str2int(&quot;cos&quot;): return cos(v * toRad); case str2int(&quot;tan&quot;): return tan(v * toRad); case str2int(&quot;sec&quot;): return 1.0 / cos(v * toRad); case str2int(&quot;csc&quot;): return 1.0 / sin(v * toRad); case str2int(&quot;cot&quot;): return 1.0 / tan(v * toRad); case str2int(&quot;asin&quot;): return asin(v) * toDeg; case str2int(&quot;acos&quot;): return acos(v) * toDeg; case str2int(&quot;atan&quot;): return atan(v) * toDeg; case str2int(&quot;asec&quot;): return acos(1.0 / v) * toDeg; case str2int(&quot;acsc&quot;): return asin(1.0 / v) * toDeg; default: //acot return atan(1.0 / v) * toDeg; } } switch (str2int(s.c_str())) { case str2int(&quot;sin&quot;): return sin(v); case str2int(&quot;cos&quot;): return cos(v); case str2int(&quot;tan&quot;): return tan(v); case str2int(&quot;sec&quot;): return 1 / cos(v.real()); case str2int(&quot;csc&quot;): return 1 / sin(v.real()); case str2int(&quot;cot&quot;): return 1 / tan(v.real()); case str2int(&quot;ln&quot;): if (v.real() &lt; 0) { return log(-1 * v.real()) + 3.142i; } if (v.real() == 0) { return INFINITY; //returning INFINITY for domain errors } return log(v); case str2int(&quot;log10&quot;): if (v.real() &lt; 0) { return (3.142i + log(-1 * v.real())) / log(10); } if (v.real() == 0) { return INFINITY; } return log10(v); case str2int(&quot;log&quot;): if (v.real() == 0 || v.real() == 1 || v2.real() == 0) { return INFINITY; } if (v.real() &lt; 0) { if (v2.real() &lt; 0) { return (log(-1 * v2.real()) + 3.142i) / (log(-1 * v.real()) + 3.142i); } return log(v2.real()) / (log(-1 * v.real()) + 3.142i); } if (v2.real() &lt; 0) { return (log(-1 * v2.real()) + 3.142i) / log(v); } return log(v2) / log(v); case str2int(&quot;exp&quot;): return exp(v); case str2int(&quot;sqrt&quot;): return sqrt(v); case str2int(&quot;cbrt&quot;): return pow(v, 1.0 / 3); case str2int(&quot;root&quot;): if (v == 0.0) { return INFINITY; } return pow(v2, 1.0 / v); case str2int(&quot;abs&quot;): return abs(v); case str2int(&quot;asin&quot;): return asin(v); case str2int(&quot;acos&quot;): return acos(v); case str2int(&quot;atan&quot;): return atan(v); case str2int(&quot;asec&quot;): return acos(1.0 / v); case str2int(&quot;acsc&quot;): return asin(1.0 / v); default: //acot return atan(1.0 / v); } } bool isOperator(string s) //checks if string is operator { vector&lt;string&gt; v {&quot;+&quot;, &quot;-&quot;, &quot;*&quot;, &quot;/&quot;, &quot;^&quot;, &quot;#&quot;, &quot;!&quot;}; return find(v.begin(), v.end(), s) != v.end(); } bool isFunction(string s) //checks if string is function { vector&lt;string&gt; v {&quot;sin&quot;, &quot;cos&quot;, &quot;tan&quot;, &quot;sec&quot;, &quot;csc&quot;, &quot;cot&quot;, &quot;ln&quot;, &quot;log10&quot;, &quot;exp&quot;, &quot;sqrt&quot;, &quot;!&quot;, &quot;cbrt&quot;, &quot;abs&quot;, &quot;asin&quot;, &quot;acos&quot;, &quot;atan&quot;, &quot;asec&quot;, &quot;acsc&quot;, &quot;acot&quot;, &quot;log&quot;, &quot;root&quot;}; return find(v.begin(), v.end(), s) != v.end(); } int paramamnt(string s) //checks parameter amount of a function { vector&lt;string&gt; v1 {&quot;sin&quot;, &quot;cos&quot;, &quot;tan&quot;, &quot;sec&quot;, &quot;csc&quot;, &quot;cot&quot;, &quot;ln&quot;, &quot;log10&quot;, &quot;exp&quot;, &quot;sqrt&quot;, &quot;cbrt&quot;, &quot;abs&quot;, &quot;asin&quot;, &quot;acos&quot;, &quot;atan&quot;, &quot;asec&quot;, &quot;acsc&quot;, &quot;acot&quot;}; vector&lt;string&gt; v2 {&quot;log&quot;, &quot;root&quot;}; return find(v1.begin(), v1.end(), s) != v1.end() ? 1 : 2; } void newval(int n, stack&lt;cmpd&gt; &amp;s, queue&lt;string&gt; &amp;q, function&lt;cmpd(string o, cmpd a, cmpd b, bool deg)&gt; func, bool isdeg) //evaluates using either the operate or the func function { if (s.size() &lt; n) { throw invalid_argument(&quot;Error: invalid expression&quot;); } cmpd a = s.top(); s.pop(); if (n == 1) { s.push(func(q.front(), a, 0, isdeg)); } else { cmpd b = s.top(); s.pop(); s.push(func(q.front(), b, a, isdeg)); } q.pop(); } cmpd evaluate(queue&lt;string&gt; q, bool isdeg) //evaluates reverse polish notation given by parse function { stack&lt;cmpd&gt; valstack; const int qsize = q.size(); for (int i = 0; i &lt; qsize; ++i) { if (isNumber(q.front())) { if (q.front() == &quot;3.142&quot;) { valstack.push(acos(-1)); } else if (q.front() == &quot;2.718&quot;) { valstack.push(exp(1)); } else { valstack.push(stod(q.front())); } q.pop(); } else if (isOperator(q.front())) { q.front() == &quot;!&quot; ? newval(1, valstack, q, operation, isdeg) : newval(2, valstack, q, operation, isdeg); } else if (isFunction(q.front())) { paramamnt(q.front()) == 1 ? newval(1, valstack, q, func, isdeg) : newval(2, valstack, q, func, isdeg); } } return valstack.top(); } queue&lt;string&gt; parse(vector&lt;string&gt; tokens) //converts vector of tokens to reverse polish notation { map&lt;string, int&gt; m {{&quot;+&quot;, 1}, {&quot;-&quot;, 1}, {&quot;*&quot;, 2}, {&quot;/&quot;, 2}, {&quot;^&quot;, 3}, {&quot;!&quot;, 4}, {&quot;#&quot;, 5}}; //operator precedence map&lt;string, char&gt; assoc {{&quot;+&quot;, 'l'}, {&quot;-&quot;, 'l'}, {&quot;*&quot;, 'l'}, {&quot;/&quot;, 'l'}, {&quot;^&quot;, 'r'}, {&quot;!&quot;, 'r'}, {&quot;(&quot;, 'l'}, {&quot;)&quot;, 'l'}}; //operator and parenthesis associativity stack&lt;string&gt; operate; queue&lt;string&gt; que; for (int i = 0; i &lt; tokens.size(); ++i) { //checking the vector of tokens cout &lt;&lt; &quot;\&quot;&quot; &lt;&lt; tokens[i] &lt;&lt; &quot;\&quot; &quot;; } for (int i = 0; i &lt; tokens.size(); ++i) { string s = tokens[i]; if (isNumber(s)) { que.push(s); } else if (isFunction(s) || s == &quot;(&quot;) { operate.push(s); } else if (isOperator(s)) { while (operate.size() != 0 &amp;&amp; operate.top() != &quot;(&quot; &amp;&amp; (m[operate.top()] &gt; m[s] || (m[s] == m[operate.top()] &amp;&amp; assoc[s] == 'l'))) { que.push(operate.top()); operate.pop(); } operate.push(s); } else if (s == &quot;)&quot;) { if (operate.size() &lt; 1) { throw invalid_argument(&quot;Error: right parenthesis at start of expression&quot;); } while (operate.top() != &quot;(&quot;) { que.push(operate.top()); operate.pop(); } operate.pop(); if (isFunction(operate.top())) { que.push(operate.top()); operate.pop(); } } else { throw invalid_argument(&quot;Error: invalid token&quot;); } } const int osize = operate.size(); for (int i = 0; i &lt; osize; ++i) { que.push(operate.top()); operate.pop(); } cout &lt;&lt; &quot;\n&quot;; queue&lt;string&gt; q2 = que; const int q2size = q2.size(); for (int i = 0; i &lt; q2size; ++i) { //checking queue here cout &lt;&lt; q2.front() &lt;&lt; &quot; &quot;; q2.pop(); } return que; } vector&lt;string&gt; lex(string input) //tokenizes input { for (int i = 0; i &lt; input.length() - 1; ++i) { //checks if a number is next to a function in order to multiply them if (isdigit(input[i]) &amp;&amp; isalpha(input[i + 1])) { input = input.substr(0, i + 1) + &quot;*&quot; + input.substr(i + 1); } } string buffer = &quot;&quot;; vector&lt;string&gt; output {&quot;0&quot;, &quot;+&quot;}; for (int i = 0; i &lt; input.length(); ++i) { if (input[i] == '-') { output.push_back(buffer); if (output.size() != 0 &amp;&amp; (output[output.size() - 1] == &quot;)&quot; || isNumber(output[output.size() - 1]))) { //subtraction output.push_back(input.substr(i, 1)); } else { //negative val string a = &quot;&quot;; if (output.size() &gt;= 2) { string a = output[output.size() - 2]; } output.push_back(&quot;-1&quot;); if (a == &quot;^&quot;) { output.push_back(&quot;#&quot;); } else { output.push_back(&quot;*&quot;); } } buffer = &quot;&quot;; } else if (isOperator(input.substr(i, 1)) || input[i] == '(' || input[i] == ')') { //operator or parenthesis output.push_back(buffer); output.push_back(input.substr(i, 1)); buffer = &quot;&quot;; } else if (input[i] == ',') { //comma output.push_back(buffer); output.push_back(&quot;,&quot;); buffer = &quot;&quot;; } else if (input[i] == 'e' &amp;&amp; (input[i + 1] != 'x' &amp;&amp; input[i + 1] != 'c' || i == input.length() - 1)) { //e output.push_back(&quot;2.718&quot;); } else if (input[i] == 'p' &amp;&amp; input[i + 1] == 'i') { //pi input = input.substr(0, i) + input.substr(i + 1); output.push_back(&quot;3.142&quot;); } else if (input[i] == 'i' &amp;&amp; (i == 0 || input[i - 1] != 's')) { output.push_back(&quot;sqrt&quot;); output.push_back(&quot;(&quot;); output.push_back(&quot;-1&quot;); output.push_back(&quot;)&quot;); } else { //number or function buffer += input.substr(i, 1); } } output.push_back(buffer); output.erase(remove(output.begin(), output.end(), &quot;&quot;), output.end()); if (count(output.begin(), output.end(), &quot;(&quot;) != count(output.begin(), output.end(), &quot;)&quot;)) { throw invalid_argument(&quot;Error: mismatched parentheses&quot;); } for (int i = 1; i &lt; output.size(); ++i) { if (output[i] == &quot;(&quot; &amp;&amp; (isNumber(output[i - 1]) || output[i - 1] == &quot;)&quot; || output[i - 1] == &quot;!&quot;)) { output.insert(output.begin() + i, &quot;*&quot;); } else if (output[i] == &quot;)&quot; &amp;&amp; isNumber(output[i + 1])) { output.insert(output.begin() + i + 1, &quot;*&quot;); ++i; } else if (isNumber(output[i]) &amp;&amp; (isNumber(output[i - 1]))) { output.insert(output.begin() + i, &quot;*&quot;); ++i; } } output.erase(remove(output.begin(), output.end(), &quot;,&quot;), output.end()); return output; } int main() { cout &lt;&lt; &quot;This calculator has experimental support with complex numbers.\n&quot;; cout &lt;&lt; &quot;3.142 and 2.718 are assumed as pi and e respectively (type 3.1420 for example if you want 3.142 instead of pi).\n&quot;; cout &lt;&lt; &quot;If the absolute value of a number is &lt;= 0.0001, it will be rounded to 0.\n&quot;; cout &lt;&lt; &quot;\nRadians or Degrees? Enter rad or deg. (default is radians): &quot;; string measure; cin &gt;&gt; measure; transform(measure.begin(), measure.end(), measure.begin(), ::tolower); if (measure != &quot;rad&quot; &amp;&amp; measure != &quot;deg&quot;) { cout &lt;&lt; &quot;defaulting to rad...\n&quot;; measure = &quot;rad&quot;; } bool isdeg = measure != &quot;rad&quot;; cin.ignore(); cout &lt;&lt; &quot;\nEnter (use parenthesis for functions like ln()): \n&quot;; string input; getline(cin, input); input.erase(remove_if(input.begin(), input.end(), ::isspace), input.end()); //removes spaces from input cmpd val; try { val = evaluate(parse(lex(input)), isdeg); } catch (const exception&amp; e) { cout &lt;&lt; e.what(); return 1; } cout.precision(16); cout &lt;&lt; &quot;\nanswer: \n&quot;; if (isnan(val.real()) || isinf(val.real())) { cout &lt;&lt; &quot;undefined&quot;; } else { if (abs(val.real()) &lt;= 0.0001) { //used a tolerance value here because for some reason sqrt(-1)^2 evaluated into -1 + a very small constant times i so... if (abs(val.imag()) &lt;= 0.0001) { //lots of if statements for formatting purposes cout &lt;&lt; 0; } else { if (val.imag() == 1) { cout &lt;&lt; &quot;i&quot;; } else if (val.imag() == -1) { cout &lt;&lt; &quot;-i&quot;; } else { cout &lt;&lt; val.imag() &lt;&lt; &quot;i&quot;; } } } else if (abs(val.imag()) &lt;= 0.0001) { cout &lt;&lt; val.real(); } else { cout &lt;&lt; val.real() &lt;&lt; &quot; + &quot; &lt;&lt; val.imag() &lt;&lt; &quot;i&quot;; } } } </code></pre> <p>How would you improve this program?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T05:56:12.287", "Id": "534059", "Score": "1", "body": "Hello at Code Review@SE. Applying an unnamed tolerance to decide outputting `0`, but not `±i` without a numerical value looks paradox. Please explicitly state what you think *redundant* in the code presented for review. See [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) for *why* a review needs context. Here I, for one, can't discern detrimental redundancy - is it in a repetition with code in some \"outer else-statement\"?" } ]
[ { "body": "<p>Well, stop passing <code>string</code> <strong>by value</strong>.<br />\nActually, use <code>string_view</code> for parameters (by value).<br />\nWhy does str2int take a <code>const char*</code> rather than a <code>string</code> or <code>string_view</code>? Again, just make it take a <code>string_view</code>.</p>\n<p><code>isNumber</code> does all the work of obtaining the number, just to throw it away (and presumably do it all over again when you do want the number).</p>\n<p>I see what you're doing with <code>str2int</code>... you need to make sure you don't have a clash. Really, you should tokenize the input as a separate step, then pass the token ID around rather than the original token as a string.</p>\n<pre><code>bool isOperator(string s) //checks if string is operator\n{\n vector&lt;string&gt; v {&quot;+&quot;, &quot;-&quot;, &quot;*&quot;, &quot;/&quot;, &quot;^&quot;, &quot;#&quot;, &quot;!&quot;};\n \n return find(v.begin(), v.end(), s) != v.end();\n}\n</code></pre>\n<p>again, <strong>string by value?</strong><br />\nThe list of allowed values should be <code>constexpr</code> and can be a plain array, not a <code>vector</code>. Use <code>std::any_of</code> rather than writing your own.</p>\n<p>Every time you call one of these functions, it creates the vector from scratch! It allocates the memory, and allocates memory for <em>each string</em> and copies the literal into it. Then it frees it all again.</p>\n<p>So use a <code>constexpr string_view[] = { ... };</code> instead, and it will all be fixed at compile time. Furthermore, it will remember the length of each string (unlike using the <code>const char*</code>), but not have the space overhead of the <code>std::string</code> type.</p>\n<p><code>paramamnt</code>'s local variable <code>v2</code> is not used.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:48:53.500", "Id": "270516", "ParentId": "270433", "Score": "1" } }, { "body": "<p>Why are there so many <code>using</code>s at file scope? That makes it a lot harder to see where identifiers have come from. I'm sure the code doesn't need so many standard identifiers in global scope.</p>\n<p>Here, we use <code>::isspace</code> without a definition (it's in the deprecated <code>&lt;ctype.h&gt;</code> rather than <code>&lt;cctype&gt;</code>):</p>\n<pre><code> if(s.empty() || ::isspace(s[0]) || isalpha(s[0])) {\n</code></pre>\n<p>Not only that, but we're passing (possibly signed) <code>char</code> to a character-classification function. We need to convert to <code>unsigned char</code> before its promotion to <code>int</code>.</p>\n<p><code>str2int()</code> is a confusing name for a <em>hash</em> function. And there's a risk of your program failing to compile with a very unhelpful diagnostic when built on a platform where the character coding leads to collisions with the values you've used. Which encodings have you tried? I'm guessing only ASCII and EBCDIC?</p>\n<p>It's much more reliable to just use a <code>std::map</code> to map strings to an <code>enum class</code> type - and this will help your compiler to warn about any missing <code>case</code> labels.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T11:35:56.530", "Id": "270535", "ParentId": "270433", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T00:13:04.847", "Id": "270433", "Score": "2", "Tags": [ "c++", "performance", "algorithm", "math-expression-eval", "complex-numbers" ], "Title": "Shunting Yard Calculator - Extended to negative, complex, etc" }
270433
<p>All 3 ids are basically the same button but different divs, but I had to rename them to accomplish what I was looking for. Is there a way to write this better? Any help is much appreciated.</p> <pre><code>$(document).ready(function(){ $(&quot;#open_iptvbasic&quot;).click(function(){ $(&quot;#iptv-channel-slideout_skinny&quot;).toggleClass(&quot;expand&quot;); $(&quot;.letju&quot;).css(&quot;opacity&quot;, &quot;1&quot;); $(&quot;.letju&quot;).css(&quot;display&quot;, &quot;block&quot;); }); $(&quot;#open_iptvloaded&quot;).click(function(){ $(&quot;#iptv-channel-slideout_loaded&quot;).toggleClass(&quot;expand&quot;); $(&quot;.letju&quot;).css(&quot;opacity&quot;, &quot;1&quot;); $(&quot;.letju&quot;).css(&quot;display&quot;, &quot;block&quot;); }); $(&quot;#open_iptvfully&quot;).click(function(){ $(&quot;#iptv-channel-slideout_fully-loaded&quot;).toggleClass(&quot;expand&quot;); $(&quot;.letju&quot;).css(&quot;opacity&quot;, &quot;1&quot;); $(&quot;.letju&quot;).css(&quot;display&quot;, &quot;block&quot;); }); $(&quot;#tv-channel-close, .letju&quot;).click(function(){ $(&quot;#iptv-channel-slideout_skinny, #iptv-channel-slideout_loaded, #iptv-channel-slideout_fully-loaded&quot;).removeClass(&quot;expand&quot;); $(&quot;.letju&quot;).fadeOut(); }); }); </code></pre> <p><a href="https://i.stack.imgur.com/PDZJv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PDZJv.png" alt="these are the services boxes" /></a></p> <p><a href="https://i.stack.imgur.com/T5OcR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T5OcR.png" alt="this is the modal that shows the respective channels" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T02:41:53.973", "Id": "534052", "Score": "6", "body": "Welcome to CodeReview. On this site, every question falls into \"can I write this better\", so we generally want titles to reflect the code in the question. See [ask]. Specific to your post, are you able to adjust the html? If \"basic\" became \"skinny\", you could probably do a simple substitution on the id to get the next id (also, how are the ids related in the DOM?)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T03:14:24.677", "Id": "534055", "Score": "0", "body": "Its ok how it is, its small amount of code and simple to read, simple to extend, thats not worth of refactoring and overcomplicating" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T03:54:08.710", "Id": "534057", "Score": "4", "body": "Is this [tag:jquery]? Also, be sure to mention what your program/code does. It's likely there are ways to rewrite your code, but it's best for us to know some context at the very least." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T04:38:01.540", "Id": "534058", "Score": "0", "body": "Hi, thanks for your feedback. yes, it is jquery. I'm new to these forums. not sure if I can upload images to show my purpose. this is a tv service card based on availability and each package has different channels. but I'd like to use the same div to show all 3 packages but change its channels based on selection. this is just my start. not sure if I'm clear enough. thanks in advance for any help you can provide :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T08:53:25.947", "Id": "534064", "Score": "2", "body": "It's quite possible that there's a way to write generalized code to handle all three cases, but it's hard to advise you without seeing the corresponding HTML. I suggest that you post a demo by [edit]ing the question and pressing Ctrl-M to make a live Stack Snippet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T08:47:04.857", "Id": "534134", "Score": "1", "body": "Still missing the HTML." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T23:12:17.823", "Id": "534189", "Score": "1", "body": "We would love to see additional details of your code. If you need a hint, take a look at those three `click` functions that look basically the same except for the first line in each. You can try to extract the common lines of code into a separate function and call that function in each case or try to use just ONE function for all three cases. Then you just need to figure out how to apply the `toggleClass` to the appropriate element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T08:48:49.623", "Id": "534618", "Score": "3", "body": "Given the first revision of the code, I see a \"How-To\" question not well suited for code review." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T02:05:01.373", "Id": "270434", "Score": "-2", "Tags": [ "javascript", "jquery", "html", "css" ], "Title": "Is there a way to write this better?" }
270434
<p>I'm developing a REST API using Azure Functions with .NET 5 (Isolated) and I want to add an OpenAPI spec for each route. But it looks like this:</p> <pre class="lang-csharp prettyprint-override"><code>namespace AzureFunctionsREST.API.Functions { public class ReporterFunction : BaseFunction { private readonly IReporterRepository _reporterRepository; public ReporterFunction(IReporterRepository reporterRepository) { this._reporterRepository = reporterRepository; } [Function(&quot;ReporterList&quot;)] [OpenApiOperation(tags: new[] { &quot;reporter&quot; }, Summary = &quot;Retrieve all reporters&quot;)] [OpenApiSecurity(&quot;function_key&quot;, SecuritySchemeType.ApiKey, Name = &quot;code&quot;, In = OpenApiSecurityLocationType.Query)] [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: &quot;application/json&quot;, bodyType: typeof(Reporter[]), Description = &quot;All reporters&quot;)] public async Task&lt;HttpResponseData&gt; List([HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;, Route = &quot;reporter&quot;)] HttpRequestData req, FunctionContext executionContext) { // List reporters } [Function(&quot;ReporterGet&quot;)] [OpenApiOperation(tags: new[] { &quot;reporter&quot; }, Summary = &quot;Retrieve reporter&quot;)] [OpenApiSecurity(&quot;function_key&quot;, SecuritySchemeType.ApiKey, Name = &quot;code&quot;, In = OpenApiSecurityLocationType.Query)] [OpenApiParameter(name: &quot;reporterId&quot;, In = ParameterLocation.Path, Required = true, Type = typeof(string))] [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: &quot;application/json&quot;, bodyType: typeof(Reporter), Description = &quot;Reporter&quot;)] public async Task&lt;HttpResponseData&gt; Get([HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;, Route = &quot;reporter/{reporterId:required}&quot;)] HttpRequestData req, FunctionContext executionContext) { // Get reporter } [Function(&quot;ReporterPost&quot;)] [OpenApiOperation(tags: new[] { &quot;reporter&quot; }, Summary = &quot;Create a new reporter&quot;)] [OpenApiSecurity(&quot;function_key&quot;, SecuritySchemeType.ApiKey, Name = &quot;code&quot;, In = OpenApiSecurityLocationType.Query)] [OpenApiRequestBody(contentType: &quot;application/json&quot;, bodyType: typeof(ReporterRequest))] [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: &quot;application/json&quot;, bodyType: typeof(Reporter), Description = &quot;Created reporter&quot;)] public async Task&lt;HttpResponseData&gt; Post([HttpTrigger(AuthorizationLevel.Function, &quot;post&quot;, Route = &quot;reporter&quot;)] HttpRequestData req, FunctionContext executionContext) { // Create reporter } [Function(&quot;ReporterPut&quot;)] [OpenApiOperation(tags: new[] { &quot;reporter&quot; }, Summary = &quot;Update a reporter&quot;)] [OpenApiSecurity(&quot;function_key&quot;, SecuritySchemeType.ApiKey, Name = &quot;code&quot;, In = OpenApiSecurityLocationType.Query)] [OpenApiParameter(name: &quot;reporterId&quot;, In = ParameterLocation.Path, Required = true, Type = typeof(string))] [OpenApiRequestBody(contentType: &quot;application/json&quot;, bodyType: typeof(ReporterRequest))] [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: &quot;application/json&quot;, bodyType: typeof(Reporter), Description = &quot;Updated reporter&quot;)] public async Task&lt;HttpResponseData&gt; Put([HttpTrigger(AuthorizationLevel.Function, &quot;put&quot;, Route = &quot;reporter/{reporterId:required}&quot;)] HttpRequestData req, FunctionContext executionContext) { // Update reporter } [Function(&quot;ReporterDelete&quot;)] [OpenApiOperation(tags: new[] { &quot;reporter&quot; }, Summary = &quot;Delete a reporter&quot;)] [OpenApiParameter(name: &quot;reporterId&quot;, In = ParameterLocation.Path, Required = true, Type = typeof(string))] [OpenApiSecurity(&quot;function_key&quot;, SecuritySchemeType.ApiKey, Name = &quot;code&quot;, In = OpenApiSecurityLocationType.Query)] [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: &quot;application/json&quot;, bodyType: typeof(Reporter), Description = &quot;Deleted reporter&quot;)] public async Task&lt;HttpResponseData&gt; Delete([HttpTrigger(AuthorizationLevel.Function, &quot;delete&quot;, Route = &quot;reporter/{reporterId:required}&quot;)] HttpRequestData req, FunctionContext executionContext) { // Delete reporter } } } </code></pre> <p>All five methods are just routes for simple CRUD operations. As you can see these lines are duplicated in every function (route):</p> <pre class="lang-csharp prettyprint-override"><code>[OpenApiOperation(tags: new[] { &quot;reporter&quot; }, Summary = &quot;Retrieve all reporters&quot;)] [OpenApiSecurity(&quot;function_key&quot;, SecuritySchemeType.ApiKey, Name = &quot;code&quot;, In = OpenApiSecurityLocationType.Query)] [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: &quot;application/json&quot;, bodyType: typeof(Reporter[]), Description = &quot;All reporters&quot;)] </code></pre> <p>I'm using a single class for interaction with each model (e.g. 10 models = 10 classes) so in each class:</p> <ul> <li>Tags will all be the same</li> <li>Security will be the same</li> <li>Response body will all be the same (except <code>[GET] /api/reporter</code> which will return as an array)</li> </ul> <p>And also parameter name is also duplicated (see <code>reporterId</code>):</p> <pre class="lang-csharp prettyprint-override"><code>[OpenApiParameter(name: &quot;reporterId&quot;, In = ParameterLocation.Path, Required = true, Type = typeof(string))] public async Task&lt;HttpResponseData&gt; Put([HttpTrigger(AuthorizationLevel.Function, &quot;put&quot;, Route = &quot;reporter/{reporterId:required}&quot;)] HttpRequestData req, FunctionContext executionContext) { } </code></pre> <p>I've tried something like putting values in a variable and using it in the attributes (<a href="https://stackoverflow.com/a/2827821/7405706">which is not possible</a>). So, I'm wondering is there a way to refactor this so these lines won't get duplicated all over?</p> <hr /> <p>Additional Info:</p> <ul> <li>GitHub - <a href="https://github.com/phwt/azure-functions-rest/tree/feature/mongo" rel="nofollow noreferrer">https://github.com/phwt/azure-functions-rest/tree/feature/mongo</a> <ul> <li>The functions will be inside <code>AzureFunctionsREST.API/Functions</code></li> <li>This project is a PoC for REST API + OpenAPI + MongoDB + repository pattern on Azure Functions. So, there might be a lot of unrelated codes.</li> </ul> </li> <li>Related documentations on OpenAPI with Azure Functions <ul> <li><a href="https://github.com/Azure/azure-functions-openapi-extension/blob/main/docs/openapi-core.md" rel="nofollow noreferrer">https://github.com/Azure/azure-functions-openapi-extension/blob/main/docs/openapi-core.md</a></li> <li><a href="https://docs.microsoft.com/en-us/azure/azure-functions/openapi-apim-integrate-visual-studio" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/azure-functions/openapi-apim-integrate-visual-studio</a></li> </ul> </li> </ul> <hr /> <p>The updated version is available <a href="https://gist.github.com/phwt/7728bab1483bc4cf8cfb5d10ad3bdc51" rel="nofollow noreferrer">here</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T16:10:35.843", "Id": "534084", "Score": "0", "body": "Please do not update your question after an answer has been posted. See https://codereview.stackexchange.com/help/someone-answers ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T16:11:34.080", "Id": "534085", "Score": "0", "body": "@BCdotWEB Can you suggest a way on how do I share my implementations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T16:13:24.490", "Id": "534086", "Score": "0", "body": "Read the link, that is why I posted it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T16:14:55.597", "Id": "534088", "Score": "1", "body": "@BCdotWEB Okay, I didn't see your updated link." } ]
[ { "body": "<p>The sad truth is there is no nice solution for this (at least according to my knowledge).</p>\n<p>But there are some tiny tricks which you can apply to make your code more concise:</p>\n<ul>\n<li>Use type alias to abbreviate attribute names</li>\n<li>Use constant classes to capture constant values</li>\n<li>Avoid named arguments whenever it's unambiguous</li>\n</ul>\n<h3><code>OpenApiOperationAttribute</code></h3>\n<ol>\n<li>Abbreviate it to <code>Op</code></li>\n</ol>\n<pre><code>using Op = Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes.OpenApiOperationAttribute;\n</code></pre>\n<ol start=\"2\">\n<li>Define a <code>Resource</code> and a <code>Summary</code> classes</li>\n</ol>\n<pre><code>private static class Resource\n{\n public const string Name = &quot;reporter&quot;;\n}\n\nprivate static class Summary\n{\n private const string resource = Resource.Name;\n public const string List = &quot;Retrieve all &quot; + resource + &quot;s&quot;;\n}\n</code></pre>\n<ol start=\"3\">\n<li>Take advantage of the <code>tags</code> parameter definition (<code>params string[] tags</code>)</li>\n</ol>\n<pre><code>[Op(tags: Resource.Name, Summary = Summary.List)]\n</code></pre>\n<ul>\n<li>Because it was defined as a <code>params</code> that's why we can omit the array declaration <code>new [] { ... }</code></li>\n<li>If we omit <code>tags</code> then we define the <code>operationId</code> parameter instead, so we have to use here the named argument feature of C#</li>\n</ul>\n<h3><code>OpenApiSecurityAttribute</code></h3>\n<ol>\n<li>Abbreviate it to <code>Sec</code></li>\n</ol>\n<pre><code>using Sec = Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes.OpenApiSecurityAttribute;\n</code></pre>\n<ol start=\"2\">\n<li>Define a <code>Security</code> class</li>\n</ol>\n<pre><code>private static class Security\n{\n public const string Name = &quot;code&quot;;\n public const OpenApiSecurityLocationType In = OpenApiSecurityLocationType.Query;\n public const string SchemeName = &quot;function_key&quot;;\n public const SecuritySchemeType SchemeType = SecuritySchemeType.ApiKey;\n}\n</code></pre>\n<ol start=\"3\">\n<li>Take advantage of the positions of the arguments</li>\n</ol>\n<pre><code>[Sec(Security.SchemeName, Security.SchemeType, Name = Security.Name, In = Security.In)]\n</code></pre>\n<h3><code>OpenApiResponseWithBodyAttribute</code></h3>\n<ol>\n<li>Abbreviate it to <code>Body</code></li>\n</ol>\n<pre><code>using Sec = using Body = Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes.OpenApiResponseWithBodyAttribute;\n</code></pre>\n<ol start=\"2\">\n<li>Define a <code>ResponseBody</code> and a <code>Description</code> classes</li>\n</ol>\n<pre><code>private static class ResponseBody\n{\n public const HttpStatusCode StatusCode = HttpStatusCode.OK;\n public const string ContentType = &quot;application/json&quot;;\n}\n\nprivate static class Description\n{\n private const string resource = Resource.Name;\n public const string List = &quot;All &quot; + resource + &quot;s&quot;;\n}\n</code></pre>\n<ol start=\"3\">\n<li>Yet again take advantage of the position of the arguments to avoid naming</li>\n</ol>\n<pre><code>[Body(ResponseBody.StatusCode, ResponseBody.ContentType, typeof(Reporter[]), Description = Description.List)]\n</code></pre>\n<hr />\n<p>After moving all hard coded strings and enums into static classes then the methods look like these. Here are two examples:</p>\n<h3>List</h3>\n<pre><code>[Function(Name.List)]\n[Op(Resource.Name, Summary = Summary.List)]\n[Sec(Security.SchemeName, Security.SchemeType, Name = Security.Name, In = Security.In)]\n[Body(ResponseBody.StatusCode, ResponseBody.ContentType, typeof(Reporter[]), Description = Description.List)]\npublic async Task&lt;HttpResponseData&gt; List(\n [HttpTrigger(Trigger.Level, Method.Get, Route = Route.List)] HttpRequestData req,\n FunctionContext executionContext)\n{\n \n}\n</code></pre>\n<h3>Delete</h3>\n<pre><code>[Function(Name.Delete)]\n[Op(tags: Resource.Name, Summary = Summary.Delete)]\n[Sec(Security.SchemeName, Security.SchemeType, Name = Security.Name, In = Security.In)]\n[Param(Parameter.Name, In = Parameter.In, Required = Parameter.IsRequired, Type = typeof(string))]\n[Body(ResponseBody.StatusCode, ResponseBody.ContentType, typeof(Reporter[]), Description = Description.Delete)]\npublic async Task&lt;HttpResponseData&gt; Delete(\n [HttpTrigger(Trigger.Level, Method.Delete, Route = Route.Delete)] HttpRequestData req,\n FunctionContext executionContext)\n{\n\n}\n</code></pre>\n<p>Finally let me share with you the definitions of the <code>Name</code>, <code>Method</code>, <code>Parameter</code> and <code>Route</code> classes:</p>\n<pre><code>public static class Parameter\n{\n public const string Name = Resource.Name + &quot;Id&quot;;\n public const ParameterLocation In = ParameterLocation.Path;\n public const bool IsRequired = true;\n}\n\nprivate static class Name\n{\n private const string prefix = nameof(Reporter);\n public const string List = prefix + nameof(List);\n ...\n public const string Delete = prefix + nameof(Delete);\n}\n\nprivate static class Route\n{\n private const string prefix = Resource.Name;\n public const string List = prefix;\n ...\n public const string Delete = prefix + &quot;/{&quot;+ Parameter.Name + &quot;:required}&quot;;\n}\n\nprivate static class Method\n{\n public const string Get = nameof(HttpMethod.Get);\n ...\n public const string Delete = nameof(HttpMethod.Delete);\n}\n</code></pre>\n<p>One can argue whether or not does it make sense to define that many static classes. I agree that they are still boiler-plate code. But the changes are more localized (in case of renaming or extension).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T11:22:17.840", "Id": "534068", "Score": "1", "body": "Thanks for the very detailed solutions! Even with a lot of static classes - this still looks better." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T10:55:51.120", "Id": "270438", "ParentId": "270437", "Score": "3" } } ]
{ "AcceptedAnswerId": "270438", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T08:57:20.747", "Id": "270437", "Score": "3", "Tags": [ "c#", ".net", "azure" ], "Title": "C# duplicated attributes on Azure Functions with OpenAPI specifications" }
270437
<p>I needed to pass a const reference to part of a <code>std::vector</code> without copy. I posted the previous version in my <a href="https://codereview.stackexchange.com/questions/270271/custom-implementation-to-provide-an-immutable-range-of-a-vector-without-copying">earlier question</a>, thank you for the great support! As far as I know this version supports not only <code>std::vector</code>s but any kind of iterator based continuous containers!</p> <p>Some research, particularly <a href="//stackoverflow.com/q/30469063">this SO question</a>, suggested that it is not something supported by default(at least in pre-c++20 std), so I created my own code for it:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iterator&gt; #include &lt;vector&gt; template &lt;typename Iterator = std::vector&lt;double&gt;::const_iterator&gt; class ConstVectorSubrange{ public: using T = typename Iterator::value_type; ConstVectorSubrange(Iterator start_, std::size_t size_) : start(start_) , range_size(size_) { } ConstVectorSubrange(Iterator begin_, Iterator end_) : start(begin_) , range_size(std::distance(start, end_)) { } const T&amp; operator[](std::size_t index) const{ assert(index &lt; range_size); return *std::next(start, index); } const T&amp; front() const{ return *begin(); } const T&amp; back() const{ return *std::next(end(), -1); } std::size_t size() const{ return range_size; } Iterator begin() const{ return start; } Iterator end() const{ return std::next(start, range_size); } private: const Iterator start; const std::size_t range_size; }; </code></pre> <p>In C++20 the functionality is available in <code>std::span</code>, so I am trying to achieve this with c++17 latest. Target for my code is c++11, but c++17 features are also present in the project I am using this in. I'm not sure I would go up to c++20 as I'm still not sure how widespread it is yet, but I'm still open to it.</p> <p>An example of using this would be a member function where not the whole array is visible, although copies are to be avoided:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;vector&gt; class BigData{ std::vector&lt;int&gt; big_array = vector&lt;int&gt;(10000); public: ConstVectorSubrange get_last_five_thousand_elements(){ return{(big_array.end()-5000), big_array.end()}; } }; </code></pre> <p>How can this code be improved? I tried to remove the dependent typename, but I could only do that with C++20 <code>std::iter_reference_t</code>. Is there no other way to deduce <code>T</code> explicitly?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T13:38:06.983", "Id": "534074", "Score": "0", "body": "Thanks, I corrected it" } ]
[ { "body": "<p>With C++17 the compiler should be able to deduce the template type automatically by using the following:</p>\n<pre><code>template &lt;typename Iterator&gt;\nclass ConstVectorSubrange {\npublic:\n using T = typename Iterator::value_type;\n // ...\n}\n\nint main() \n{\n std::vector v{ 1, 2, 3, 4, 5, 6, 7, 8 };\n ConstVectorSubrange range(v.begin() + 2, v.end() - 2);\n}\n</code></pre>\n<p>I'm not sure why you have included <code>&lt;iterator&gt;</code> and failed to include <code>&lt;cassert&gt;</code>?</p>\n<p>Good:</p>\n<p>I like that you can now use the foreach loop:</p>\n<pre><code>std::vector v{ 7, 7, 3, 4, 5, 6, 7, 7, 8, 9 };\nConstVectorSubrange vsr(v.begin() + 4, v.end());\nfor (int i : vsr)\n std::cout &lt;&lt; i &lt;&lt; &quot;\\n&quot;;\n</code></pre>\n<p>And all the cool stuff from <code>&lt;algorithm&gt;</code></p>\n<pre><code>std::cout &lt;&lt; std::count(vsr.begin(), vsr.end(), 7) &lt;&lt; &quot;\\n&quot;;\n</code></pre>\n<p>Ideas:</p>\n<p>It would be pretty cool if you could include a <code>step</code> or <code>stride</code> to have a slice of the vector. Something like this:</p>\n<pre><code>std::vector v{ 1, 2, 3, 4, 5, 6 };\nstd::size_t step = 2;\nConstVectorSubrange r(v.begin() + 1, v.end(), step);\nfor (int i : r)\n std::cout &lt;&lt; i &lt;&lt; &quot;\\n&quot;;\n// expected results 2, 4, 6\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T19:26:27.103", "Id": "534097", "Score": "1", "body": "`<assert.h>` is not a C++ header. You probably mean `<cassert>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T20:11:50.943", "Id": "534102", "Score": "0", "body": "@indi thanks, updated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T13:56:06.273", "Id": "534141", "Score": "0", "body": "Thank you very much! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T14:06:09.560", "Id": "534142", "Score": "1", "body": "@DavidTóth, cool! You got so close that I almost feel like I should have added a spoiler alert ;-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T14:18:34.723", "Id": "270446", "ParentId": "270439", "Score": "5" } } ]
{ "AcceptedAnswerId": "270446", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T11:55:49.403", "Id": "270439", "Score": "7", "Tags": [ "c++", "template", "iterator", "collections" ], "Title": "Custom implementation to provide an immutable range of a container without copying it" }
270439
<p>I have created a simple abstract class called <code>expr_node</code> which will serve as a base class for any expression-related nodes.</p> <p>My goal is to create a simple deleter that can delete the allocated memory from the derived class in which would be recursive in some cases.</p> <p>Rules and constraints (NOTE: for practice purposes only):</p> <ul> <li>Will not rely on smart pointers (<code>std::unique_ptr</code> and <code>std::shared_ptr</code>)</li> <li>Will not rely on <code>std::variant</code> or <code>std::any</code></li> <li>Not using <code>std::visit</code></li> <li>Apply dynamic dispatch</li> <li>Only use inheritance</li> <li>(i'm also aware that I use recursion very often here just for the sake of traversing each)</li> </ul> <p>Important enumerations:</p> <pre class="lang-cpp prettyprint-override"><code>/// enum class: node_kinds enum class node_kinds { number_atom, unary_op, binary_op }; /// enum class: unary_op_kinds enum class unary_op_kinds { plus, minus }; /// enum class: binary_op_kinds enum class binary_op_kinds { plus, minus, multiplies, divides, modulus }; </code></pre> <p>Abstract class:</p> <pre class="lang-cpp prettyprint-override"><code>/// abstract class: expr_node struct expr_node { virtual ~expr_node() = default; virtual node_kinds node_kind() const = 0; }; </code></pre> <p>Derived classes from <code>expr_node</code>:</p> <pre class="lang-cpp prettyprint-override"><code>/// number_node struct number_node : expr_node { std::int64_t value; number_node(std::int64_t value) : value(value) {} node_kinds node_kind() const override { return node_kinds::number_atom; } }; /// unary_op_node struct unary_op_node : expr_node { unary_op_kinds kind; expr_node* operand; unary_op_node(unary_op_kinds kind, expr_node* operand = nullptr) : kind(kind), operand(operand) {} node_kinds node_kind() const override { return node_kinds::unary_op; } }; /// binary_op_node struct binary_op_node : expr_node { binary_op_kinds kind; expr_node* left; expr_node* right; binary_op_node(binary_op_kinds kind, expr_node* left = nullptr, expr_node* right = nullptr) : kind(kind), left(left), right(right) {} node_kinds node_kind() const override { return node_kinds::binary_op; } }; </code></pre> <p>Main Highlight: Deleter</p> <pre class="lang-cpp prettyprint-override"><code>void delete_nodes(expr_node* node) { if (node != nullptr) { switch (node-&gt;node_kind()) { case node_kinds::number_atom: if (auto temp = dynamic_cast&lt;number_node*&gt;(node); temp != nullptr) { delete temp; temp = nullptr; } break; case node_kinds::unary_op: if (auto temp = dynamic_cast&lt;unary_op_node*&gt;(node); temp != nullptr) { delete_nodes(temp-&gt;operand); delete temp; temp = nullptr; } break; case node_kinds::binary_op: if (auto temp = dynamic_cast&lt;binary_op_node*&gt;(node); temp != nullptr) { delete_nodes(temp-&gt;left); delete_nodes(temp-&gt;right); delete temp; temp = nullptr; } break; } node = nullptr; } } </code></pre> <p>Utilities for printing a tree:</p> <pre class="lang-cpp prettyprint-override"><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, unary_op_kinds kind) { switch (kind) { using enum unary_op_kinds; case plus: return os &lt;&lt; '+'; case minus: return os &lt;&lt; '-'; } return os; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, binary_op_kinds kind) { switch (kind) { using enum binary_op_kinds; case plus: return os &lt;&lt; '+'; case minus: return os &lt;&lt; '-'; case multiplies: return os &lt;&lt; '*'; case divides: return os &lt;&lt; '/'; case modulus: return os &lt;&lt; '%'; } return os; } void display_nodes(expr_node* node, std::size_t level = 0) { if (node != nullptr) { switch (node-&gt;node_kind()) { case node_kinds::number_atom: if (auto temp_node = dynamic_cast&lt;number_node*&gt;(node); temp_node != nullptr) { std::cout &lt;&lt; std::string(level, ' ') &lt;&lt; &quot;number(&quot; &lt;&lt; temp_node-&gt;value &lt;&lt; &quot;)\n&quot;; } break; case node_kinds::unary_op: if (auto temp_node = dynamic_cast&lt;unary_op_node*&gt;(node); temp_node != nullptr) { std::cout &lt;&lt; std::string(level, ' ') &lt;&lt; &quot;unary_op(&quot; &lt;&lt; temp_node-&gt;kind &lt;&lt; &quot;)\n&quot;; display_nodes(temp_node-&gt;operand, level + 1); } break; case node_kinds::binary_op: if (auto temp_node = dynamic_cast&lt;binary_op_node*&gt;(node); temp_node != nullptr) { std::cout &lt;&lt; std::string(level, ' ') &lt;&lt; &quot;binary_op(&quot; &lt;&lt; temp_node-&gt;kind &lt;&lt; &quot;)\n&quot;; display_nodes(temp_node-&gt;left, level + 1); display_nodes(temp_node-&gt;right, level + 1); } break; } } } </code></pre> <p>Sample:</p> <pre class="lang-cpp prettyprint-override"><code>// 1 + (2 + (3 * (-4))) expr_node* nodes = new binary_op_node(binary_op_kinds::plus, new number_node(1), new binary_op_node(binary_op_kinds::plus, new number_node(2), new binary_op_node(binary_op_kinds::multiplies, new number_node(3), new unary_op_node(unary_op_kinds::minus, new number_node(4) ) ) ) ); display_nodes(nodes); delete_nodes(nodes); </code></pre> <p>Output:</p> <pre class="lang-cpp prettyprint-override"><code>binary_op(+) number(1) binary_op(+) number(2) binary_op(*) number(3) unary_op(-) number(4) </code></pre> <p>If we focus primarily on the deleter function <code>delete_nodes</code>, is it enough to be called a &quot;proper&quot; or is it properly deleting? Will there be undefined behavior happen?</p>
[]
[ { "body": "<p>A much simpler approach would be to create virtual destructors for <code>unary_op_node</code> and <code>binary_op_node</code> like the following:</p>\n<pre><code>struct unary_op_node : expr_node {\n expr_node* operand;\n // ...\n virtual ~unary_op_node() override {\n delete operand;\n }\n};\n\nstruct binary_op_node : expr_node {\n expr_node* left;\n expr_node* right;\n // ...\n virtual ~binary_op_node() override\n {\n delete left;\n delete right;\n }\n};\n</code></pre>\n<p>The whole tree can then be deleted with a simple <code>delete</code> statement:</p>\n<pre><code>int main()\n{\n expr_node* nodes = new binary_op_node(binary_op_kinds::plus,\n new number_node(1),\n new binary_op_node(binary_op_kinds::plus,\n new number_node(2),\n new binary_op_node(binary_op_kinds::multiplies,\n new number_node(3),\n new unary_op_node(unary_op_kinds::minus,\n new number_node(4)\n )\n )\n )\n );\n\n delete nodes;\n}\n</code></pre>\n<hr>\n<p>Here are some notes on your existing implementation.</p>\n<p>You should not use <code>nullptr</code> for comparisons. Use either use <code>if (node)</code> to check if the node is not null or <code>if (!node)</code> to check if the node is null.</p>\n<p>This line:</p>\n<pre><code>if (auto temp = dynamic_cast&lt;number_node*&gt;(node); temp != nullptr) {\n</code></pre>\n<p>Can then be changed to the following:</p>\n<pre><code>if (auto temp = dynamic_cast&lt;number_node*&gt;(node); temp) {\n</code></pre>\n<p>And further reduced to:</p>\n<pre><code>if (auto temp = dynamic_cast&lt;number_node*&gt;(node)) {\n</code></pre>\n<hr>\n<p>If the <code>dynamic_cast</code> fails and returns null then something very nasty must have happened earlier. I would recommend that you either throw an <code>exception</code> when this happens:</p>\n<pre><code>case node_kinds::number_atom:\n{\n auto temp = dynamic_cast&lt;number_node*&gt;(node);\n if (!temp)\n throw std::runtime_error(&quot;Failed to cast node&quot;);\n delete temp;\n}\nbreak;\n</code></pre>\n<p>Or, just assume that it will be successful:</p>\n<pre><code>case node_kinds::unary_op:\n delete dynamic_cast&lt;unary_op_node*&gt;(node);\n break;\n</code></pre>\n<hr>\n<p>Considering the following:</p>\n<pre><code>if (auto temp = dynamic_cast&lt;number_node*&gt;(node)) {\n delete temp;\n temp = nullptr;\n}\n</code></pre>\n<p>I'm not sure why you are setting <code>temp</code> to <code>nullptr</code>. When <code>temp</code> falls out of the scope, it no longer exists and setting it to whatever value serves no purpose.</p>\n<p>Perhaps this was closer to what your intentions were:</p>\n<pre><code>void delete_nodes(expr_node** node) {\n if (node) {\n switch ((*node)-&gt;node_kind()) {\n // ...\n }\n *node = nullptr;\n }\n}\n\nint main()\n{\n delete_nodes(&amp;nodes);\n}\n</code></pre>\n<hr>\n<p>I think it may be worthwhile for a sanity check to include a <code>default</code> item to the <code>switch</code>. Something like the following:</p>\n<pre><code> default:\n throw std::runtime_error(&quot;Invalid node type&quot;);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T15:41:27.357", "Id": "270449", "ParentId": "270443", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T13:39:40.000", "Id": "270443", "Score": "0", "Tags": [ "c++", "expression-trees" ], "Title": "Deleter for Simple Expression Tree in C++" }
270443
<blockquote> <p>Given an array <span class="math-container">\$a\$</span> of integers, find minimum sum obtained after performing <span class="math-container">\$K\$</span> <em>operation</em>s. In this context <em>operation</em> involves choosing an element <em>a[i]</em>, multiply it by <span class="math-container">\$2\$</span>, at the same time, choose another element and divide by <span class="math-container">\$2\$</span>.</p> </blockquote> <p>My approach is able to find the minimum sum by carrying out the following operation.<br /> But it's not able to find the minimum sum after performing <span class="math-container">\$K\$</span> operations.</p> <pre><code>def minSum(arr, n, x=2): Sum = 0 # To store the largest element # from the array which is # divisible by x largestDivisible, minimum = -1, arr[0] for i in range(0, n): # Sum of array elements before # performing any operation Sum += arr[i] # If current element is divisible by x # and it is maximum so far if(arr[i] % x == 0 and largestDivisible &lt; arr[i]): largestDivisible = arr[i] # Update the minimum element if arr[i] &lt; minimum: minimum = arr[i] # If no element can be reduced then there's # no point in performing the operation as # we will end up increasing the sum when an # element is multiplied by x if largestDivisible == -1: return Sum # Subtract the chosen elements from the # sum and then add their updated values sumAfterOperation = (Sum - minimum - largestDivisible + (x * minimum) + (largestDivisible // x)) # Return the minimized sum return min(Sum, sumAfterOperation) </code></pre> <p>Any idea on what I can do to extend this approach to handle the concept of doing <span class="math-container">\$K\$</span> operations?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T15:23:30.170", "Id": "534078", "Score": "0", "body": "Welcome to the Code Review Community. We only review code that is working as expected, there are other sites that will help you debug your code. Please read [Where can I get help?](https://meta.stackexchange.com/questions/129598/which-computer-science-programming-stack-exchange-sites-do-i-post-on) and [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T16:16:40.143", "Id": "534089", "Score": "0", "body": "right i forgot to introduce x=2 as default value. I will do that. the reason for not mentioning x is that if we were to generalize the question to say choose an element divide it by x and choose another element multiply it by x." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T23:14:14.247", "Id": "534119", "Score": "0", "body": "Mentioning x is fine, but \"not able to find the minimum sum\" and \"any idea on what I can do\" means that your code is not complete, and therefore off topic." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T13:48:22.940", "Id": "270444", "Score": "-2", "Tags": [ "python" ], "Title": "Minimize sum of array after performing K operations(Python)" }
270444
<p>I wrote a program with Python that converts decimal positive numbers to binary and puts the result in a list. I have a problem with decimal 0 because the result I get is <code>[]</code> instead of <code>[0]</code>. It works just fine with every number except for 0. How can I improve it to make it work with 0 too?</p> <p>This is my code:</p> <pre><code>def dec2bin(number): binary_number = [] final_quotient = 0 while (number != 0): rem = number % 2 binary_number.append(rem) number = number // 2 binary_number.reverse() print(binary_number) return binary_number </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T14:45:55.553", "Id": "534077", "Score": "0", "body": "please this is urgent!!!!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T15:24:23.760", "Id": "534079", "Score": "0", "body": "Welcome to the Code Review Community. We only review code that is working as expected, there are other sites that will help you debug your code. Please read [Where can I get help?](https://meta.stackexchange.com/questions/129598/which-computer-science-programming-stack-exchange-sites-do-i-post-on) and [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T15:26:29.387", "Id": "534080", "Score": "0", "body": "Python supports `if-else` logic in a few different ways. Give that a try." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T16:43:29.560", "Id": "534090", "Score": "0", "body": "What's wrong on `list(bin(number)[2:])`?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T14:04:48.887", "Id": "270445", "Score": "-4", "Tags": [ "python" ], "Title": "Python program to convert decimal to binary" }
270445
<p>Here is my A* algorithm. I tried hard to implement it generically, but come up only with one idea to use lambdas for heuristic and next nodes (neighbours / successors) functions. I know that using good heuristic function is the key to speed up, but here i'm trying to squeeze everything from current implementation not taking into account any external factors.</p> <pre><code> /** * @brief generic a* algorithm * * @tparam T any type with operator&lt; and operator== * @tparam Heuristic function, returns uint32_t * @tparam Mutator function returns iterable of all next states of node * @param initial initial state of node * @param expected expected state of node * @param heuristic function like manhattan or euclidean distance * @param next next mutator * @return std::vector&lt;T&gt; representing path from expected to initial */ template &lt;class T, class Heuristic, class Mutator&gt; std::vector&lt;T&gt; path(const T&amp; initial, const T&amp; expected, Heuristic heuristic, Mutator next) { struct Node { using ref = std::shared_ptr&lt;Node&gt;; explicit Node(const T&amp; data, ref parent, uint32_t g, uint32_t h) : data(data), parent(parent), g(g), h(h), f(g + h) {} const T data; // actual data const ref parent{}; // pointer to parent // scores const uint32_t g, h, f; }; static auto path = [](auto n) { std::vector&lt;T&gt; result; for (; n; n = n-&gt;parent) result.push_back(n-&gt;data); return result; }; // comparator for nodes::ref's to make heap static auto comp = [](auto&amp;&amp; lhs, auto&amp;&amp; rhs) { return lhs-&gt;f &gt; rhs-&gt;f; }; // std::vector&lt;T&gt; closed; std::set&lt;T&gt; closed; // &lt;- required operator&lt; // vector will be used as priority_queue std::vector&lt;typename Node::ref&gt; opened; // initial state with g score = 0 opened.push_back(std::make_shared&lt;Node&gt;(initial, nullptr, 0, heuristic(initial, expected))); while (not opened.empty()) { // pop opened into curr const auto curr = opened.front(); // if goal found if (curr-&gt;data == expected) return path(curr); // poping priority queue std::pop_heap(opened.begin(), opened.end(), comp); opened.pop_back(); // foreach node in successors for (auto&amp;&amp; child : next(curr-&gt;data)) { // if was in closed if (!closed.insert(child).second) continue; // setting up child node const auto node = std::make_shared&lt;Node&gt;(child, curr, curr-&gt;g + 1, heuristic(child, expected)); // find the node with the same data as child auto it = std::find_if(opened.begin(), opened.end(), [&amp;child](auto&amp;&amp; node) { return node-&gt;data == child; }); // if opened does not contains child data push and continue if (it == opened.end()) { opened.push_back(std::move(node)); std::push_heap(opened.begin(), opened.end(), comp); continue; } // if current child node is better than found node // replace previos node with current if (node-&gt;f &lt; (*it)-&gt;f) *it = node; } } return {}; // impossible to reach } </code></pre> <p>Is there any way to improve performance?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T20:26:13.550", "Id": "534104", "Score": "0", "body": "The `not` operator confused me for a second until I remembered about alternative operators. I'm not sure if it's considered good practice to use them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T22:15:48.997", "Id": "534110", "Score": "0", "body": "@jdt Why exactly 'not' itstead of ! is a bad practice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T22:31:34.667", "Id": "534113", "Score": "0", "body": "I’m not saying it is bad practice, it’s just something that you don't see very often. Generally, it’s a good idea to stick to a convention. If you had `while (not opened.empty())` I would have expected to see the same in `if (!closed.insert(child).second)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T22:32:26.730", "Id": "534114", "Score": "1", "body": "Please don't change the question after it has been answered, especially something mentioned in the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T22:33:27.077", "Id": "534115", "Score": "0", "body": "I mean maybe 'not' has some overhead and that is why it is bad practice. But you're right about convention. I just like the way 'and', 'not' and 'or' sounds in code, makes it sound like a Shakespear's poem. (Wish I could say the same for the 'eq', 'not_eq', 'or_eq'...)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T13:38:01.913", "Id": "534140", "Score": "0", "body": "I can ! argue with that =) Some usage examples will be really helpful. Can you send some on github / pastebin / TIO?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T19:55:06.217", "Id": "534178", "Score": "0", "body": "This operators i think i just a styling technique, and probably gives no advantage over normal. I don't think i ever saw people actually taking advantage using it but probably somwere in [macros](https://en.cppreference.com/w/cpp/header/ciso646) world it is a hot thing. Speaking of the last time i saw it [here](https://github.com/tdulcet/Tables-and-Graphs/blob/master/tables.hpp) quy uses 'and' and 'or' a lot but not 'not' :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T16:47:02.087", "Id": "534228", "Score": "0", "body": "I have rolled back Rev 6 → 4. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<h2>Linear search through the whole heap</h2>\n<blockquote>\n<pre><code>// find the node with the same data as child\nauto it = std::find_if(opened.begin(), opened.end(), [&amp;child](auto&amp;&amp; node) {\n return node-&gt;data == child;\n});\n</code></pre>\n</blockquote>\n<p>This is a clear issue. It may seem like there is no way to avoid it, but there actually is. Unfortunately, it will mean having to re-implement the heap functions. The trick is this:</p>\n<ul>\n<li>Maintain an <code>unordered_map</code> (or as secondary choice, <code>map</code>) from <code>T</code> to the index in the heap at which the node with a given <code>data</code> is located.</li>\n<li>All heap-related functions must update the indices in that map when they move nodes. This is why they need to be re-implemented. It won't change their time complexity though.</li>\n<li>&quot;find node with the same data as child&quot; can implemented as a lookup in the map.</li>\n</ul>\n<h2>&quot;Re-parenting&quot; a node changes its <code>f</code> score</h2>\n<p><code>*it = node;</code> is not sufficient to update a node when a shortcut has been found to it. Its <code>f</code> score changed, that's why this is being done in the first place. Leaving it in same position may mean that it violates the heap property, which will have to be restored, otherwise future heap operations become unreliable.</p>\n<h2>Reachable unreachable code</h2>\n<p>The return in the end, <code>return {}; // impossible to reach</code> can be reached, namely when the goal is unreachable from the start and the amount of search space which is reachable from the start is finite.</p>\n<h2>Shared pointers</h2>\n<p>Nodes do not really need shared pointers to their parents, conceptually they do not <em>own</em> their parent after all, the parent pointers are just to say &quot;go there to follow the path&quot;. What is really needed is these two things:</p>\n<ul>\n<li>There must be some way to go from a node to its parent.</li>\n<li>.. and that must be possible when the path finding is done, so the lifetime of this data must be until after the path has been traced.</li>\n</ul>\n<p>That can be accomplished with shared pointers, but that has some disadvantages:</p>\n<ul>\n<li>Creating nodes is non-trivial, requiring individual dynamic allocation.</li>\n<li>Nodes have some additional, hidden, memory overhead (from being shared, and also from being individually allocated).</li>\n<li>Getting rid of the nodes that still exist when the function returns is non-trivial.</li>\n</ul>\n<p>There are various alternatives. For example (these can be combined/mixed to some extent):</p>\n<ul>\n<li>All nodes could be owned by one big vector which is destroyed all in one go when the function returns (the destructor of <code>Node</code> can be trivial as long as <code>T</code> has a trivial destructor, then all the nodes in the vector just poof out of existence without ceremony). References to nodes can be replaced with indexes into that vector, or if you really want, you could still dynamically allocate the individual nodes and refer to them by non-owning pointer (except in the vector, which would own them with a unique pointer), but that negates some of the benefit of doing this.</li>\n<li>The parent relationships could be recorded outside the nodes, in a map from <code>T</code> to <code>T</code>. This way the nodes are only needed as part of the Open set (the only thing needed from a closed node is its parent, but that isn't in the node anymore in this scheme), which could own them by value. This may be bad if <code>T</code> is a large type, because it creates a lot more <code>T</code>s. <br />\nBy the way, you are already using a similar approach for the closed set, which in some implementations is implemented as a <code>bool isClosed</code> in the <code>Node</code> class.</li>\n<li>If the search space is a grid, temporary grids can be used to store the nodes (or its separate constituents). Nodes could be referred to by their position in the grid, parents specifically can also be recorded by their direction.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T22:25:04.897", "Id": "534112", "Score": "0", "body": "OK, thanks a lot, i almost lost hope for good answers, and here is a marvelous one. Thanks, i'll try your suggestions tomorrow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T15:49:15.130", "Id": "534147", "Score": "0", "body": "@David let me know how it goes, this site doesn't require it I'm just curious" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T19:45:15.940", "Id": "534177", "Score": "0", "body": "Sorry, today was actually really busy day, finifshing my term work, i will inform you as soon as algorithm gets better. Btw i use two kinds of tests for it, i'm trying to solve real path between two vectors, and to solve 15 game. At the moment it takes nearly 13k generations and 120 depth level with 400-800 ms on debug to achieve goal with vectors like (0, 0) -> (80, 80) with step +-1 on all directions, but 15 game appears to be unsolvable." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T18:55:07.243", "Id": "270453", "ParentId": "270452", "Score": "4" } }, { "body": "<p>Avoid many small allocations.<br />\nAvoid shared ownership.<br />\nAvoid linear search.</p>\n<p>All of those are expensive and a redesign of your data-structures will get rid of them:</p>\n<ol>\n<li><p>A <code>std::vector</code> to store your nodes. You can stably refer to them by index now.</p>\n</li>\n<li><p>A <code>std::unordered_map</code> (or at least a <code>std::map</code> if the external index cannot be hashed) to map from the external identifiers to internal indices into the vector.</p>\n<p>You should use a custom allocator for this, considering your specific use-case a simple linear allocator would work wonders.</p>\n</li>\n<li><p>A <code>std::priority_queue</code> to store the workitems.</p>\n</li>\n</ol>\n<p>Only store the data you need:<br />\nWhile all of f,g and h are used in explaining the algorithm, you really only need the estimated cost. Only if the heuristic is expensive should you consider storing that separately.</p>\n<p>Don't hard-code a specific type needlessly. You can derive the type for the estimated cost of using a node from the return-value of the heuristic (and the edge-weights if you add those).</p>\n<p>If on exploring a node you find a new node, calculate its priority and add a workitem.<br />\nIf you find a better way to a node instead, update its priority and add a workitem.<br />\nObsolete workitems can be discarded when you get to them, because the priority in the workitem doesn't match the node any longer. Fiddling with items somewhere in the middle of a heap easily destroys the heap, or at least gets expensive.</p>\n<p>This rewrite also gets rid of the closed list, allowing you to use any admissible heuristic, not just a monotone (aka consistent) one. A restriction which you didn't document.</p>\n<p>Avoid passing small trivial types by constant reference. The indirection might inhibit optimization.</p>\n<p>What about weighted edges? Currently, your generic algorithm has a fixed edge-weight of 1.</p>\n<p>If you add the endpoint to the path, you can distinguish no path found (empty) from trivial path found (end is start).</p>\n<p>As an untested example:</p>\n<pre><code>template &lt;class T, class F1, class F2&gt;\nstd::vector&lt;T&gt; path(T start, T target, F1 heuristic, F2 next) {\n using Cost = decltype(heuristic(start, target)\n + std::get&lt;0&gt;(next(start).begin()));\n struct Node {\n const T data;\n std::size_t parent;\n Cost cost;\n };\n struct Open {\n Cost cost;\n std::size_t id;\n bool operator&lt;(const Open&amp; rhs) { return cost &gt; rhs.cost; };\n };\n std::vector&lt;Node&gt; nodes {{ start, 0, heuristic(start, target)}};\n std::unordered_map&lt;T, std::size_t&gt; ids {{ nodes[0].data, 0}};\n // ^^ Find or write a simple linear allocator for all those nodes\n std::priority_queue&lt;Open&gt; open;\n open.emplace(nodes[0].cost, 0);\n while (!open.empty()) {\n auto [cost, id] = open.top();\n open.pop();\n if (nodes[id].cost != cost)\n continue;\n if (nodes[id].data == target) {\n std::vector&lt;T&gt; r;\n for (; id; id = nodes[id].parent)\n r.push_back(nodes[id].data);\n r.push_back(nodes[id].data);\n std::reverse(r.begin(), r.end());\n return r;\n }\n cost -= heuristic(nodes[id].data, target);\n for (auto&amp;&amp; [weight, data] : next(nodes[id].data)) {\n auto [p, added] = ids.try_emplace(data, nodes.size());\n auto estimate = cost + weight + heuristic(data, target);\n if (added)\n nodes.emplace_back(data, id, estimate);\n else if (estimate &lt; nodes[p-&gt;second()].cost)\n nodes[p-&gt;second()].cost = estimate;\n else\n continue;\n open.emplace(estimate, p-&gt;second());\n }\n }\n return {};\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T21:13:16.003", "Id": "270475", "ParentId": "270452", "Score": "4" } }, { "body": "<h1>Changes</h1>\n<p>Ok so after @harold and @Deduplicator gave me a couple pieces of advise (Big thanks btw) I ended up with the following implementation. Performance win is not huge but there is one, about 100-300 ms for 8game solve and 50 ms for two dimensional vectors.</p>\n<pre><code>\nnamespace {\n// the reason why this structure is not in closure\n// is because of operator&lt; has to be friend\n// and friend is only available outside closure\nstruct Open {\n size_t id; // vector stack id instead of ptr\n uint32_t g, h; // still separate variables\n explicit Open(size_t id, uint32_t g, uint32_t h) : id(id), g(g), h(h) {}\n // comparator for priority queue\n friend bool operator&lt;(Open lhs, Open rhs) { return lhs.g + lhs.h &gt; rhs.g + rhs.h; }\n};\n\n} // namespace\n\n/**\n * @brief generic a* algorithm\n *\n * @tparam T any type with operator&lt; and operator==\n * @tparam Heuristic function, returns uint32_t\n * @tparam Mutator function returns iterable of all next states of node\n * @param initial initial state of node\n * @param expected expected state of node\n * @param heuristic function like manhattan or euclidean distance\n * @param next next mutator\n * @return std::vector&lt;T&gt; representing path from expected to initial\n */\ntemplate &lt;class T, class Heuristic, class Mutator&gt;\nstd::vector&lt;T&gt; path(const T&amp; initial, const T&amp; expected,\n Heuristic heuristic, Mutator next, size_t nextWeight = 1) {\n struct Node {\n const T data; // actual data\n size_t parent; // index to parent instead of ptr\n uint32_t f;\n explicit Node(const T&amp; data, size_t parent, uint32_t f)\n : data(data), parent(parent), f(f) {\n }\n };\n std::vector&lt;Node&gt; nodes{Node(initial, 0, heuristic(initial, expected))}; // as was suggested\n // now pq, there is no need to iterate through underlying vector anymore\n std::priority_queue&lt;Open&gt; opened;\n // map because i don't want to force user implement hash function for their data\n std::map&lt;T, size_t&gt; closed{{initial, 0}}; \n\n // initial state\n opened.emplace(0, 0, nodes[0].f);\n\n while (not opened.empty()) {\n // pop opened into curr\n const auto curr = opened.top();\n opened.pop();\n\n // if goal found\n if (nodes[curr.id].data == expected) {\n // no lambda for better performance?\n std::vector&lt;T&gt; result;\n result.reserve(curr.g / nextWeight); // using g for our advantage\n\n auto id = curr.id;\n for (; id; id = nodes[id].parent)\n result.push_back(std::move(nodes[id].data)); // move because we don't need this data anymore in closure\n result.push_back(std::move(nodes[id].data));\n\n return result; // not reversing this is users responsibility\n }\n\n // foreach node in successors\n for (auto&amp;&amp; child : next(nodes[curr.id].data)) {\n // trying to insert into closed map\n const auto [it, inserted] = closed.try_emplace(child, nodes.size());\n\n // precomputing g and h values\n const auto g = curr.g + nextWeight;\n const auto h = heuristic(child, expected);\n\n // data wasn't in closed creating new node in nodes vector\n if (inserted)\n nodes.emplace_back(child, curr.id, g + h);\n // if f cost of existed node is worse than current just updating cost\n else if (g + h &lt; nodes[it-&gt;second].f)\n nodes[it-&gt;second].f = g + h;\n else \n continue;\n \n // finally constructing new open node in open queue\n opened.emplace(it-&gt;second, g, h);\n }\n }\n\n return {}; // path not found\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T15:17:48.630", "Id": "534315", "Score": "0", "body": "Did you try plugging a linear allocator into the map? (not included in the standard library)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T18:48:36.423", "Id": "270504", "ParentId": "270452", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T16:13:53.250", "Id": "270452", "Score": "4", "Tags": [ "c++", "performance", "pathfinding", "a-star" ], "Title": "Improving generic A* algorithm performance" }
270452
<p>I have a base view model which implements an Mode View View model pattern.</p> <pre><code> public interface IBaseViewModel&lt;T&gt; { #region public properties BaseViewModelProperties BaseVMProps { get; set; } T Model { get; set; } #endregion #region public methods Task Init(); Task Init(Guid Id); Task Init(string Id); Task Init(string type, Guid Id); Task Create(); Task Get(Guid Id); Task&lt;T&gt; Get(string Id); Task&lt;IEnumerable&lt;T&gt;&gt; GetList(); Task&lt;IEnumerable&lt;T&gt;&gt; GetList(Guid Id); Task&lt;IEnumerable&lt;T&gt;&gt; GetList(string Id); Task Insert(T t); Task Insert(string type, T t); Task Update(Guid Id, T t); Task Update(string type, Guid Id, T t); Task Delete(Guid Id); Task Delete(string type, Guid Id); void Dispose(); #endregion } public abstract class BaseViewModel&lt;T&gt; : IBaseViewModel&lt;T&gt;, IDisposable { public BaseViewModelProperties BaseVMProps { get; set; } = new BaseViewModelProperties(); public T Model { get; set; } #region Init public virtual Task Init() { return Task.FromResult&lt;T&gt;(default); } public virtual Task Init(Guid Id) { return Task.FromResult&lt;T&gt;(default); } public virtual Task Init(string Id) { return Task.FromResult&lt;T&gt;(default); } public virtual Task Init(string type, Guid Id) { return Task.FromResult&lt;T&gt;(default); } #endregion public virtual Task Create() { return Task.FromResult&lt;T&gt;(default); } #region Get public virtual Task Get(Guid Id) { return Task.FromResult&lt;T&gt;(default); } public virtual Task&lt;T&gt; Get(string Id) { return Task.FromResult&lt;T&gt;(default); } public virtual Task Get(string type, Guid Id) { return Task.FromResult&lt;T&gt;(default); } public virtual Task&lt;IEnumerable&lt;T&gt;&gt; GetList() { return Task.FromResult&lt;IEnumerable&lt;T&gt;&gt;(default); } public virtual Task&lt;IEnumerable&lt;T&gt;&gt; GetList(Guid Id) { return Task.FromResult&lt;IEnumerable&lt;T&gt;&gt;(default); } public virtual Task&lt;IEnumerable&lt;T&gt;&gt; GetList(string Id) { return Task.FromResult&lt;IEnumerable&lt;T&gt;&gt;(default); } #endregion #region Insert public virtual Task Insert(T t) { return Task.FromResult&lt;T&gt;(default); } public virtual Task Insert(string type, T t) { return Task.FromResult&lt;T&gt;(default); } #endregion #region Update public virtual Task Update(Guid Id, T t) { return Task.FromResult&lt;T&gt;(default); } public virtual Task Update(string type, Guid Id, T t) { return Task.FromResult&lt;T&gt;(default); } #endregion #region Delete public virtual Task Delete(Guid Id) { return Task.FromResult&lt;T&gt;(default); } public virtual Task Delete(string type, Guid Id) { return Task.FromResult&lt;T&gt;(default); } #endregion public virtual void ProcessDto(T t) { } public virtual void Dispose() { } </code></pre> <p>Below is a sample implementation of this base view model</p> <pre><code> public class AccountBillViewModel : BaseViewModel&lt;AccountBillGroup&gt;, IAccountBillViewModel { public Guid AccountId { get; set; } public string AccountQDSId { get; set; } public AccountBillGroup SelectedAccountBillGroup { get; set; } public IEnumerable&lt;AccountBillGroup&gt; AccountBillGroupList { get; set; } private IAccountBillDataService accountBillDataService { get; set; } public AccountBillViewModel(IAccountBillDataService accountBillDataService) { this.accountBillDataService = accountBillDataService; AccountBillGroupList = Enumerable.Empty&lt;AccountBillGroup&gt;(); } #region Get collection of account bills by account id - Api call public async override Task&lt;IEnumerable&lt;AccountBillGroup&gt;&gt; GetList(Guid accountId) { try { OperationResult&lt;IEnumerable&lt;AccountBillGroup&gt;&gt; opResult = await accountBillDataService.GetAccountBillsByAccountId(accountId).ConfigureAwait(false); AccountBillGroupList = OperationResultHelper&lt;IEnumerable&lt;AccountBillGroup&gt;&gt;. ProcessOperationResult(opResult, BaseVMProps, &quot;GetAccountBillsByAccountId&quot;, &quot;Get&quot;); return AccountBillGroupList; } catch (Exception ex) { //ToDo: call audit service to log error UtilityHelper.ProcessException(BaseVMProps); throw; } } #endregion } </code></pre> <p>The sample implementation uses a subset of the abstract base class. Does this violate the Interface Segregation Principle? Would it be better to break this base view model down into a set of smaller interfaces and then implement only those interfaces that will be used in each class? Or is the current implementation acceptable?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T23:39:33.430", "Id": "534120", "Score": "1", "body": "Welcome to Code Review? Please tell us, and also make that the title of the question. See [ask]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T10:09:50.510", "Id": "534135", "Score": "0", "body": "@200_success Please tell us *what*, exactly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T16:37:36.050", "Id": "534152", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T16:38:16.710", "Id": "534153", "Score": "1", "body": "Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T17:40:43.457", "Id": "534168", "Score": "0", "body": "@SaraJ What does the code do, the title and maybe a paragraph in the question should tell us." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T18:57:00.053", "Id": "270454", "Score": "-1", "Tags": [ "interface" ], "Title": "Interface Segregation Principle" }
270454
<p>So I tried implementing a easily extendable solution for <a href="https://www.geeksforgeeks.org/sqrt-square-root-decomposition-technique-set-1-introduction/" rel="nofollow noreferrer">Sqrt decompostion</a>, I deduced that only identity value, operation and block update logic change and rest of the code is same. So i created 3 functions</p> <ul> <li><code>T identity()</code></li> <li><code>T operation(const T&amp;a, const T&amp;b)</code></li> <li><code>T block_update_calc(const T old_block_value, const T, const T &amp;old_data_value)</code></li> </ul> <p>I earlier tried inheritance, where these were <strong>pure virtual functions</strong> in base class and these are implemented in derived classes. But I then found out that we can't call virtual functions of derived class in constructor of base class which can be mitigated at cost of syntax.</p> <p>Current solution is template based and <code>AdditionSqrtDecomposition</code> and <code>MultiplicationSqrtDecomposition</code> <strong>behave exactly like I want</strong>, but code looks bit messy, how can I improve this code?</p> <p>Usage:</p> <pre class="lang-cpp prettyprint-override"><code>vector&lt;int&gt; nums(N); AdditionSqrtDecomposition&lt;int&gt; sd_addition(nums); MultiplicationSqrtDecomposition&lt;int&gt; sd_multiplication(nums); </code></pre> <p>Implementation</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef SQRT_DECOMPOSITION_HPP #define SQRT_DECOMPOSITION_HPP #include &lt;cmath&gt; #include &lt;vector&gt; template &lt;typename T, class Core&gt; class SqrtDecomposition { public: std::vector&lt;T&gt; _data, _decomp; int _block_size; // constructors, asssignment, destructor explicit SqrtDecomposition(const std::vector&lt;T&gt; &amp;data) : _data(data), _decomp(ceil(sqrt(data.size())), Core::identitiy()), _block_size(::sqrt(data.size())) { int curr_block = -1; for (int i = 0; i &lt; _data.size(); ++i) { if (i % _block_size == 0) { curr_block++; } auto &amp;d = _decomp[curr_block]; d = Core::operation(d, _data[i]); } } T query(int l, int r) { T result = Core::identitiy(); // identitiy for (; l &lt;= r and l % _block_size != 0; l++) { // individuals before a block result = Core::operation(result, _data[l]); } for (int i = l / _block_size; l + _block_size &lt;= r; ++i, l += _block_size) { // block representatives result = Core::operation(result, _decomp[i]); } for (; l &lt;= r; ++l) { // individuals after a block result = Core::operation(result, _data[l]); } return result; } void update(int index, T value) { int representating_block = index / _block_size; _decomp[representating_block] = Core::block_update_calc( _decomp[representating_block], value, _data[index]); _data[index] = value; } }; // interface template &lt;typename T&gt; class OperationCore { public: static T identitiy() = 0; static T operation(const T &amp;a, const T &amp;b) = 0; static T block_update_calc(const T old_block_value, const T new_data_value, const T &amp;old_data_value) = 0; }; template &lt;typename T&gt; class AdditionCore { public: static T identitiy() { return 0; } static T operation(const T &amp;a, const T &amp;b) { return a + b; } static T block_update_calc(const T old_block_value, const T new_data_value, const T &amp;old_data_value) { return old_block_value + new_data_value - old_data_value; } }; template &lt;typename T&gt; class MultiplicationCore { public: static T identitiy() { return 1; } static T operation(const T &amp;a, const T &amp;b) { return a * b; } static T block_update_calc(const T old_block_value, const T new_data_value, const T &amp;old_data_value) { return (old_block_value * new_data_value) / old_block_value; } }; template &lt;typename T&gt; class AdditionSqrtDecomposition : public SqrtDecomposition&lt;T, AdditionCore&lt;T&gt;&gt; { using SqrtDecomposition&lt;T, AdditionCore&lt;T&gt;&gt;::SqrtDecomposition; }; template &lt;typename T&gt; class MultiplicationSqrtDecomposition : public SqrtDecomposition&lt;T, MultiplicationCore&lt;T&gt;&gt; { using SqrtDecomposition&lt;T, MultiplicationCore&lt;T&gt;&gt;::SqrtDecomposition; }; #endif // SQRT_DECOMPOSITION_HPP </code></pre>
[]
[ { "body": "<h1>Design review</h1>\n<p>Your design is mostly sound. It can be simplified a little bit, and optionally made a bit more rigorous, but the basic design is not bad.</p>\n<p>The name for what you’re doing is <a href=\"https://en.wikipedia.org/wiki/Modern_C%2B%2B_Design#Policy-based_design\" rel=\"nofollow noreferrer\">the “Policy” design pattern</a>. The gist is that you create a class templated on policy types, and then concrete policy classes to control the behaviour of the main class. Even the standard library uses that pattern in places, though mostly as the closely related <a href=\"https://en.wikipedia.org/wiki/Trait_(computer_programming)\" rel=\"nofollow noreferrer\">“Traits” design pattern</a>. For example, <code>std::string</code> is actually <code>std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt;&gt;</code>, where <code>std::char_traits</code> is a traits type, and <code>std::allocator</code> is a policy type for (de)allocation. You can replace the allocator policy type with anything you want: you can have an allocator that logs every allocation, an allocator that allocates from a memory pool, an allocator that does nothing but uses stack memory… literally anything you want.</p>\n<p>Your policy types are very good, too; you’ve boiled them down to a small number of minimal operations. That’s perfect.</p>\n<p>Now, the <code>OperationCore</code> class is pure nonsense. I’m surprised it even compiles. (For the record, it looks like Clang compiles it, but GCC does not.) You seem to have confused static member functions with virtual functions. Those are two entirely different things; completely unrelated. A function cannot be both static and virtual; the idea doesn’t even make sense. So this:</p>\n<pre><code>static T identitiy() = 0;\n</code></pre>\n<p>makes no sense.</p>\n<p>But that’s okay, because the entire <code>OperationCore</code> class serves no purpose, and isn’t used anywhere, so it can just be dumped.</p>\n<p>If you want a way to validate the policy interface, the modern, C++20 way to do it would be to use a concept:</p>\n<pre><code>template &lt;typename Policy, typename T&gt;\nconcept sqrt_decomposition_policy = requires(T t)\n{\n Policy::identity() -&gt; std::same_as&lt;T&gt;;\n Policy::operation(t, t) -&gt; std::same_as&lt;T&gt;;\n Policy::block_update_calc(t, t, t) -&gt; std::same_as&lt;T&gt;;\n};\n</code></pre>\n<p>And your class would be like:</p>\n<pre><code>template &lt;typename T, typename Policy&gt;\n requires sqrt_decomposition_policy&lt;Policy, T&gt;\n // also maybe floating_point&lt;T&gt; or integral&lt;T&gt; or a concept combining them\nclass sqrt_decomposition\n{\n // ...\n</code></pre>\n<p>But since you’re apparently working in C++14, your only practical option is a traits type. This would be <em>much</em> easier to do with C++17, because you’d have <code>std::void_t</code>, <code>std::conjunction</code>, and so on. But it’s still doable in C++14. Here’s a very brief, very rough overview:</p>\n<pre><code>namespace _detail {\n\ntemplate &lt;typename...&gt;\nusing void_t = void;\n\ntemplate &lt;typename Policy, typename T, typename = void&gt;\nstruct has_valid_sqrt_decomposition_policy_identity_function : std::false_type {};\n\ntemplate &lt;typename Policy, typename T&gt;\nstruct has_valid_sqrt_decomposition_policy_identity_function&lt;Policy, T, void_t&lt;\n // this only checks that an identity function exists\n decltype(Policy::identity())\n // you still need to confirm that it returns a T\n&gt;&gt; : std::true_type {};\n\n// ... and so on for the other functions ...\n\n} // namespace _detail\n\ntemplate &lt;typename Policy, typename T&gt;\nstruct is_sqrt_decomposition_policy\n : std::integral_constant&lt;bool,\n _detail::has_valid_sqrt_decomposition_policy_identity_function&lt;Policy, T&gt;::value\n and _detail::has_valid_sqrt_decomposition_policy_operation_function&lt;Policy, T&gt;::value\n and _detail::has_valid_sqrt_decomposition_policy_block_update_calc_function&lt;Policy, T&gt;::value\n &gt;\n{};\n</code></pre>\n<p>And the class would be like:</p>\n<pre><code>template &lt;typename T, typename Policy&gt;\nclass sqrt_decomposition\n{\n static_assert(is_sqrt_decomposition_policy&lt;Policy, T&gt;::value, &quot;&quot;);\n\n // ...\n</code></pre>\n<p>Frankly, I wouldn’t bother. I would either use C++20 concepts, or just forget it completely. The legacy solution is <em>so</em> ridiculously over-complicated, and already obsolete, it’s not worth it. It’s not worth learning how to do it. It’s not worth the headache of trying to maintain it.</p>\n<p>Once you have the main class, and the policy classes, there is no need for inheritance at all, never mind polymorphism. All you need is this:</p>\n<pre><code>template &lt;typename T, template Policy&gt;\nclass SqrtDecomposition\n{\n // ...\n};\n\ntemplate &lt;typename T&gt;\nclass AdditionPolicy\n{\n // ...\n};\n\ntemplate &lt;typename T&gt;\nclass MultiplicationPolicy\n{\n // ...\n};\n\ntemplate &lt;typename T&gt;\nusing AdditionSqrtDecomposition = SqrtDecomposition&lt;T, AdditionPolicy&lt;T&gt;&gt;;\n\ntemplate &lt;typename T&gt;\nusing MultiplicationSqrtDecomposition = SqrtDecomposition&lt;T, MultiplicationPolicy&lt;T&gt;&gt;;\n</code></pre>\n<p>It is also possible to use template templates (no, that is not a typo: “template templates”) to simplify the last two lines a tiny bit:</p>\n<pre><code>template &lt;typename T, template &lt;typename&gt; class Policy&gt;\nclass SqrtDecomposition\n{\n // ...\n};\n\ntemplate &lt;typename T&gt;\nclass AdditionPolicy\n{\n // ...\n};\n\ntemplate &lt;typename T&gt;\nclass MultiplicationPolicy\n{\n // ...\n};\n\ntemplate &lt;typename T&gt;\nusing AdditionSqrtDecomposition = SqrtDecomposition&lt;T, AdditionPolicy&gt;;\n\ntemplate &lt;typename T&gt;\nusing MultiplicationSqrtDecomposition = SqrtDecomposition&lt;T, MultiplicationPolicy&gt;;\n</code></pre>\n<p>I would <em>not</em> recommend this, though. It’s too expert-level, and it doesn’t really add anything for the complexity. In fact, it <em>removes</em> flexibility. So don’t do it. I just had to mention it for completeness.</p>\n<p>Okay, that’s about all for the design. Let’s get to the actual code.</p>\n<h1>Code review</h1>\n<pre><code>template &lt;typename T, class Core&gt; class SqrtDecomposition {\n</code></pre>\n<p>Why mix <code>typename</code> and <code>class</code>? That sends the signal that you are using the different terms as code for something… but what? This only creates confusion. Stick to <code>typename</code>, or <code>class</code>.</p>\n<p>Also, I would suggest instead of “Core” everywhere, you use “Policy”, since that is the name of the design pattern, and everyone who knows design patterns will understand immediately exactly what’s going on.</p>\n<pre><code>public:\n std::vector&lt;T&gt; _data, _decomp;\n int _block_size;\n</code></pre>\n<p>You probably want these to be private, not public.</p>\n<pre><code>std::vector&lt;T&gt; _data, _decomp;\n</code></pre>\n<p><a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es10-declare-one-name-only-per-declaration\" rel=\"nofollow noreferrer\">Don’t do this.</a> Place each declaration on its own line.</p>\n<pre><code>int _block_size;\n</code></pre>\n<p>You have a number of subtle bugs in your code that all come back to the fact that you are treating <code>std::vector&lt;T&gt;::size_type</code> and <code>int</code> interchangeably. They are not.</p>\n<p>First, <code>std::vector&lt;T&gt;::size_type</code> is an unsigned value, while <code>int</code> is signed. <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es100-dont-mix-signed-and-unsigned-arithmetic\" rel=\"nofollow noreferrer\">Mixing signed and unsigned values is a gateway to grief</a>.</p>\n<p>Second, <code>std::vector&lt;T&gt;::size_type</code> could be many times larger than an <code>int</code> (and I believe it is on Windows). By forcing <code>_data.size()</code> into an <code>int</code>, you could be truncating values and getting garbage numbers as a result.</p>\n<p>The best solution to this problem may lie in the constructor:</p>\n<pre><code> explicit SqrtDecomposition(const std::vector&lt;T&gt; &amp;data)\n : _data(data), _decomp(ceil(sqrt(data.size())), Core::identitiy()),\n _block_size(::sqrt(data.size())) {\n</code></pre>\n<p>So, here’s the thing: <code>_data</code> never grows. Neither does <code>_decomp</code>. So right here, in this constructor, you can check one time to make sure that <code>_data.size()</code> can fit in an <code>int</code>, and if so, you’re safe throughout. Here’s what you could do:</p>\n<pre><code>template &lt;typename T, typename Policy&gt;\nclass SqrtDecomposition\n{\n std::vector&lt;T&gt; _data;\n std::vector&lt;T&gt; _decomp;\n int _data_size;\n int _block_size;\n\npublic:\n explicit SqrtDecomposition(std::vector&lt;T&gt; data)\n {\n // you could expose this value as a static const data member, because\n // it is useful information to users\n constexpr auto max_data_size = static_cast&lt;unsigned int&gt;(std::numeric_limits&lt;int&gt;::max()):\n\n if (data.size() &gt; max_data_size)\n throw std::domain_error{&quot;data set is too large to decompose&quot;};\n\n // (at this point, you might as well also check that data.size() isn't\n // zero, and any other checks you want to do on the input data before\n // moving it)\n\n _data = std::move(data);\n\n // now you know this is safe:\n _data_size = static_cast&lt;int&gt;(_data.size());\n\n _block_size = static_cast&lt;int&gt;(std::sqrt(_data_size)); // or sqrt(data.size()), doesn't matter anymore\n\n auto const decomp_size = static_cast&lt;std::vector&lt;T&gt;::size_type&gt;(std::ceil(std::sqrt(_data_size)));\n _decomp = std::vector&lt;T&gt;(decomp_size, Policy::identity());\n\n // ...\n }\n</code></pre>\n<p>Note the addition of a new <code>_data_size</code> data member, which keeps <code>_data.size()</code> as an <code>int</code>. Having the data size as an <code>int</code> will save you a lot of grief later on. The downside is: it’s an extra data member in your class, which takes up space. It probably doesn’t matter, given that you’re already working with large amounts of data. But if it does, then you can drop the <code>_data_size</code> member, and just remember to do <code>auto const data_size = static_cast&lt;int&gt;(data.size());</code> in every member function.</p>\n<p>Also, I recommend making <code>max_data_size</code> a static data member, because it would allow people to check the preconditions for the constructor. Incidentally, you should document the preconditions and postconditions of the constructor and every other function. For now, since we don’t have contracts in C++ yet, you should at least include comments explaining what the expected input is. Clearly you’re not expecting a zero-sized vector (or are you? if so, you have <em>numerous</em> bugs…). You should at least document that in a comment. Same goes for the max vector size, and the range of values for the data vector contents, and so on. I should be able to read a comment at the top of your function telling me what the valid inputs are. It shouldn’t be a mystery.</p>\n<p>(Incidentally, you forgot some <code>std::</code> prefixes for <code>std::ceil()</code> and <code>std::sqrt()</code>.)</p>\n<pre><code> int curr_block = -1;\n for (int i = 0; i &lt; _data.size(); ++i) {\n if (i % _block_size == 0) {\n curr_block++;\n }\n auto &amp;d = _decomp[curr_block];\n d = Core::operation(d, _data[i]);\n }\n</code></pre>\n<p>This loop is dangerous for a couple of reasons.</p>\n<p>First, you’re comparing signed and unsigned integers. That’s always a bad idea. The fix here is to use:</p>\n<pre><code>for (int i = 0; i &lt; _data_size; ++i) // if you've defined _data_size as above\n// or:\nfor (int i = 0; i &lt; static_cast&lt;int&gt;(_data.size()); ++i)\n</code></pre>\n<p>You know the latter is safe if you did the check described earlier.</p>\n<p>The second problem is that you are doing <code>int curr_block = 1;</code> then <code>_decomp[curr_block]</code>. In between you have a block that will increment <code>curr_block</code> to zero on the first iteration, so it probably seems safe. And it is… for now… until someone else (possibly you in the future) goes monkeying around in the code, and maybe moves the <code>if</code> block to after the other statements, or who knows what else. (This isn’t even that crazy an idea, because an <code>if</code> check in a loop is inefficient, and especially so when it’s doing an expensive modulo op every loop iteration. Someone could very easily be tempted to refactor this to loop in block steps.) This is a very brittle pattern, very easy to break.</p>\n<p>I’m not going to give a concrete suggestion of what to refactor it to, though. There are just too many options, all with pros and cons. At the very least, I would add a comment that warns about the fact that that <code>if</code> block <em>must</em> run on the first iteration, or UB.</p>\n<p>Also:</p>\n<pre><code>auto &amp;d = _decomp[curr_block];\nd = Core::operation(d, _data[i]);\n</code></pre>\n<p>seems a lot less readable than simply:</p>\n<pre><code>_decomp[curr_block] = Core::operation(_decomp[curr_block], _data[i]);\n</code></pre>\n<p>Also also, and this applies everywhere. <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#nl18-use-c-style-declarator-layout\" rel=\"nofollow noreferrer\">In C++, the convention is to write the type modifier next to the type, not the identifier</a>. In plain English:</p>\n<ul>\n<li><code>auto &amp;d</code>: this is C style.</li>\n<li><code>auto&amp; d</code>: this is C++ style.</li>\n</ul>\n<p>This applies also to things like <code>const std::vector&lt;T&gt;&amp;</code>:</p>\n<ul>\n<li><code>const std::vector&lt;T&gt; &amp;data</code>: this is C style.</li>\n<li><code>const std::vector&lt;T&gt;&amp; data</code>: this is C++ style.</li>\n<li><code>std::vector&lt;T&gt; const&amp; data</code>: also C++ style, and more technically correct, never mind what the core guidelines say, but if you prefer west <code>const</code>, that’s fine too.</li>\n</ul>\n<p>Also also also, I know <code>x % y == 0</code> is widely understood as meaning “<code>true</code> if <code>x</code> is a multiple of <code>y</code>”, but it still helps readability to spell it out:</p>\n<pre><code>// somewhere else, maybe in a file of simple utility functions:\ntemplate &lt;typename T, typename U&gt; // could be constrained in C++20, or you could use a static assert\nconstexpr auto is_multiple(T const&amp; t, U const&amp; u) noexcept(noexcept(bool(t % u == 0))) -&gt; bool\n{\n return bool(t % u == 0);\n}\n\n\n // and in your code:\n\n int curr_block = -1;\n for (int i = 0; i &lt; _data.size(); ++i) {\n if (is_multiple(i, _block_size)) {\n curr_block++;\n }\n auto &amp;d = _decomp[curr_block];\n d = Core::operation(d, _data[i]);\n }\n\n // ...\n\n for (; l &lt;= r and not is_multiple(l, _block_size); ++l) {\n // individuals before a block\n result = Core::operation(result, _data[l]);\n }\n</code></pre>\n<p>There’s no reason to make your code obscure when it costs nothing to make it clear.</p>\n<pre><code> T query(int l, int r) {\n</code></pre>\n<p>Again, there’s no documentation telling me what the preconditions for this function are. Is it okay if <code>r</code> is less than <code>l</code>? Is it okay if <code>l</code> is greater than the data size? Is it okay if either are zero? Or negative? Document your preconditions!</p>\n<p>Now, let’s go back over the <code>SqrtDecomposition</code> class, and consider some other improvements. First, I would suggest adding <code>constexpr</code> everywhere. Because why not? Even if very little can be <code>constexpr</code> in C++14, as you start using more modern versions of C++, more and more things can be done at compile time. Might as well future-proof your class.</p>\n<p>I would also suggest either documenting your expectations for the types, or spelling them out explicitly. In C++20 and beyond, that usually means concepts, but you can go a long way with static asserts, even in C++14:</p>\n<pre><code>template &lt;typename T, typename Policy&gt;\nclass SqrtDecomposition\n{\n // Requirements on T.\n static_assert(std::is_arithmetic&lt;T&gt;::value, &quot;&quot;);\n static_assert(not std::is_same&lt;std::remove_cv_t&lt;std::remove_reference_t&lt;T&gt;&gt;, bool&gt;::value, &quot;&quot;);\n\n // ...\n</code></pre>\n<p>In your constructor, you take the data vector by <code>const&amp;</code>. Prior to C++11, that was always the right thing to do. But now we have move semantics.</p>\n<p>Since you are going to be copying the data vector anyway, this is a <em>taking</em> parameter… not merely a <em>reading</em> parameter. When you are <em>reading</em> a value, it makes sense to use <code>const&amp;</code>, because you never want to copy it or change it, you just want to inspect it. But whenever you are <em>taking</em> a value, you should take it by value. Here’s why, suppose I do:</p>\n<pre><code>auto decomp = AdditionSqrtDecomposition&lt;int&gt;{std::vector&lt;int&gt;{1, 2, 3, 4, 5}};\n</code></pre>\n<p>If your constructor takes a <code>const&amp;</code>, then this will create a vector… then <em>copy</em> that vector into a new <code>_data</code> vector inside the constructor.</p>\n<p>If your constructor simply takes the vector by value, then this will create a vector… then <em>move</em> that vector into <code>_data</code>.</p>\n<p>So your constructor should be:</p>\n<pre><code> explicit constexpr SqrtDecomposition(std::vector&lt;T&gt; data)\n : _data{std::move{data}}\n , _decomp(std::ceil(std::sqrt(_data.size())) , Core::identitiy())\n , _block_size(::sqrt(_data.size()))\n {\n</code></pre>\n<p>Note that once you move <code>data</code>, you can’t do <code>data.size()</code> anymore. You have to do <code>_data.size()</code>.</p>\n<p>I would recommend validating the input data <em>before</em> moving it into <code>_data</code>. But you could validate it after; doesn’t matter.</p>\n<p>Now, once you’ve done this, you could consider allowing other input than just vectors. For example, what if I want to use a <code>std::array</code> of input data? Or a <code>boost::numeric::ublas::vector&lt;double&gt;</code>? Or maybe I want to read the input data right out of a data file?</p>\n<p>Supporting arbitrary ranges is <em>much</em> easier since C++20… but it’s not exactly hard in C++14:</p>\n<pre><code> template &lt;typename InputRange&gt;\n explicit constexpr SqrtDecomposition(InputRange&amp;&amp; r)\n {\n for (auto&amp; v : r)\n _data.push_back(v);\n\n _initialize();\n }\n\n template &lt;typename InputIterator, typename Sentinel&gt;\n constexpr SqrtDecomposition(InputIterator first, Sentinel last)\n {\n for (; first != last; ++first)\n _data.push_back(*first);\n\n _initialize();\n }\n\n constexpr SqrtDecomposition(std::initializer_list&lt;T&gt; il)\n {\n _data.resize(il.size());\n std::copy(il.begin(), il.end(), _data.begin());\n\n _initialize();\n }\n\n // private helper function\n static constexpr auto _initialize() -&gt; void\n {\n // do the rest of the initialize of _decomp and so on\n }\n</code></pre>\n<p>This will work for <em>any</em> arbitrary range, or any arbitrary iterator/sentinel pair. You could do:</p>\n<pre><code>AdditionSqrtDecomposition&lt;int&gt;{std::vector&lt;int&gt;{1, 2, 3, 4, 5}};\n\n// or with an array:\nauto data = std::array&lt;double, 3&gt;{1.0, 3.0, 5.0};\nAdditionSqrtDecomposition&lt;double&gt;{data};\n\n// or directly out of a file:\nauto in = std::ifstream{&quot;datafile&quot;};\nAdditionSqrtDecomposition&lt;double&gt;(std::istream_iterator&lt;double&gt;{in}, std::istream_iterator&lt;double&gt;{});\n\n// or input the data directly in the constructor:\nAdditionSqrtDecomposition&lt;double&gt;{2.0, 4.0, 6.0};\n</code></pre>\n<p>Now what I’ve written isn’t the most efficient way to do it, but increasing efficiency is simply a matter of adding more overloads, and maybe some <code>enable_if</code>s. (In C++20, it’s trivial to make this super efficient with concepts and ranges.)</p>\n<p>Another efficiency improvement you might consider is abandoning vectors. <em>Normally</em> <code>std::vector</code> is the default container to use for runtime-sized data sets. <em>However</em>, there are two factors that make your case different:</p>\n<ol>\n<li>You never resize the vectors. After constructing <code>_data</code> and <code>_decomp</code> they stay the same size… forever. That pretty much voids most of the benefits of using a vector.</li>\n<li>You need to calculate and maintain the sizes separately anyway. Because you are using the sizes in calculations and loops where you expect them to be <code>int</code>s, you might as well just keep them as <code>int</code>s.</li>\n</ol>\n<p>So maybe:</p>\n<pre><code>template &lt;typename T, typename Policy&gt;\nclass SqrtDecomposition\n{\n std::unique_ptr&lt;T[]&gt; _data;\n std::unique_ptr&lt;T[]&gt; _decomp;\n int _data_size;\n int _decomp_size;\n\npublic:\n template &lt;typename InputIterator, typename Sentinel&gt;\n constexpr SqrtDecomposition(InputIterator first, Sentinel last)\n {\n // For efficiency, you have to handle things differently depending on\n // whether the iterators are input iterators or forward iterators\n // (or better). Not hard to do even in C++14, but verbose, so I'll\n // leave it to you to figure out.\n\n // Input iterators only ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n auto buffer = std::deque&lt;T&gt;{};\n for (; first != last; ++first)\n buffer.push_back(*first);\n\n _data_size = _validate_data(buffer.size());\n\n _data = std::unique_ptr&lt;T[]&gt;(new T[_data_size]);\n std::copy(buffer.begin(), buffer.end(), _data.get());\n\n _initialize();\n\n // Forward iterators or better ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n // note: this won't work prior to C++20 with sentinel types; you'll\n // have to roll your own distance function.\n _data_size = _validate_data_size(std::distance(first, last));\n\n _data = std::unique_ptr&lt;T[]&gt;(new T[_data_size]);\n // again, won't work with sentinel types before C++20. not hard to\n // roll your own.\n std::copy(first, last, _data.get());\n\n _initialize();\n }\n\n template &lt;typename InputRange&gt;\n explicit constexpr SqrtDecomposition(InputRange&amp;&amp; r)\n {\n // For efficiency, you need to check for sized ranges, and input\n // versus forward-or-better ranges. This requires C++20, but you can\n // *almost* get the same effect before, with a little work. I'll\n // leave it as an exercise for the reader.\n }\n\n constexpr SqrtDecomposition(std::initializer_list&lt;T&gt; il) :\n SqrtDecomposition(begin(il), end(il))\n {}\n\nprivate:\n template &lt;typename SizeType&gt;\n constexpr auto _validate_data_size(SizeType s) -&gt; int\n {\n // Check whether SizeType is signed or not, of course. Trivial to\n // handle in C++17 with if constexpr, or in C++20 with concepts.\n // Not hard in C++14, but you're on your own.\n\n if (s == 0)\n throw std::domain_error{&quot;dataset is empty&quot;};\n if (s &gt; max_data_size)\n throw std::domain_error{&quot;dataset size is too large&quot;};\n\n return static_cast&lt;int&gt;(s);\n }\n};\n</code></pre>\n<p>One other thing you might consider adding is an allocator argument, to allow users to customize where/how the internal allocations happen. Not much changes in the code above when using an allocator. You just need an allocator-aware smart pointer (unfortunately, one doesn’t exist in the standard, but it’s not hard to make), and of course you need use it rather than <code>new</code>, but otherwise, pretty much nothing changes. Well, you’d need to add allocator template arguments, of course:</p>\n<pre><code>template &lt;typename T, template Policy, template Allocator&gt;\nclass SqrtDecomposition\n{\n // ...\n};\n\ntemplate &lt;typename T&gt;\nclass AdditionPolicy\n{\n // ...\n};\n\ntemplate &lt;typename T&gt;\nclass MultiplicationPolicy\n{\n // ...\n};\n\ntemplate &lt;typename T, typename Allocator = std::allocator&lt;T&gt;&gt;\nusing AdditionSqrtDecomposition = SqrtDecomposition&lt;T, AdditionPolicy&lt;T&gt;, Allocator&gt;;\n\ntemplate &lt;typename T, typename Allocator = std::allocator&lt;T&gt;&gt;\nusing MultiplicationSqrtDecomposition = SqrtDecomposition&lt;T, MultiplicationPolicy&lt;T&gt;, Allocator&gt;;\n</code></pre>\n<p>Finally, I’ll just review one of the policy classes, since they’re more or less identical:</p>\n<pre><code>template &lt;typename T&gt; class AdditionCore {\npublic:\n static T identitiy() { return 0; }\n static T operation(const T &amp;a, const T &amp;b) { return a + b; }\n static T block_update_calc(const T old_block_value, const T new_data_value,\n const T &amp;old_data_value) {\n return old_block_value + new_data_value - old_data_value;\n }\n};\n</code></pre>\n<p>As mentioned earlier, I’d suggest naming this <code>AdditionPolicy</code> rather than <code>AdditionCore</code>, or maybe even <code>SqrtDecompositionAdditionPolicy</code> to be really explicit. It’s not a big deal if it’s verbose, because no one will be using it directly. (They’ll use the <code>AdditionSqrtDecomposition&lt;T&gt;</code> (or maybe <code>AdditionSqrtDecomposition&lt;T, Allocator&gt;</code>) alias.)</p>\n<p>There’s no reason all of these functions can’t be <code>constexpr</code>.</p>\n<p>Check the spelling of <code>identity()</code>!</p>\n<p>Also, <code>identity()</code>, and <em>only</em> <code>identity()</code> can be <code>noexcept</code>. <code>noexcept</code> means “cannot possibly fail”, and there is no conceivable way <code>identity()</code> can fail. But <code>operation()</code> (for example) could fail if you tried to add <code>std::numeric_limits&lt;int&gt;::max()</code> and anything other than zero. <code>noexcept</code> does <strong>NOT</strong> <em>necessarily</em> mean “might throw an exception”. It just admits that a function can conceivably fail, and even if it doesn’t throw an exception <em>now</em>, it might do so in the future, or maybe in debug mode or something.</p>\n<p>In fact, you could even make a regular addition policy… <em>and</em> a “debug” addition policy that does everything exactly the same, but checks for over/underflow, and maybe logs or throws or whatever. You could define the decomposition type with the regular policy when not debugging or testing, and the special debug policy type when debugging. For example:</p>\n<pre><code>template &lt;typename T&gt;\nstruct AdditionPolicy\n{\n static constexpr auto identity() noexcept -&gt; T { return T{}; }\n\n static constexpr auto operation(T a, T b) -&gt; T { return T(a + b); }\n\n static constexpr auto block_update_calc(T old_block_value, T new_data_value, T old_data_value)\n {\n return T((old_block_value + new_data_value) - old_data_value);\n }\n};\n\ntemplate &lt;typename T&gt;\nstruct DebugAdditionPolicy\n{\n static constexpr auto identity() noexcept -&gt; T { return T{}; }\n\n static constexpr auto operation(T a, T b) -&gt; T\n {\n if ((std::numeric_limits&lt;T&gt;::max() - a) &lt; b) // very basic check...\n // do something, like throw, assert, or log, or whatever\n\n return T(a + b);\n }\n\n static constexpr auto block_update_calc(T old_block_value, T new_data_value, T old_data_value)\n {\n // do checks here, too\n\n return T((old_block_value + new_data_value) - old_data_value);\n }\n};\n\n#ifdef NDEBUG\n template &lt;typename T&gt;\n using AdditionSqrtDecomposition = SqrtDecomposition&lt;T, AdditionPolicy&lt;T&gt;&gt;;\n#else\n template &lt;typename T&gt;\n using AdditionSqrtDecomposition = SqrtDecomposition&lt;T, DebugAdditionPolicy&lt;T&gt;&gt;;\n#endif // NDEBUG\n</code></pre>\n<h1>Summary</h1>\n<ul>\n<li><p>Dump <code>OperationCore</code>. It’s not even legal C++. Even if it were, it serves no purpose.</p>\n</li>\n<li><p>If you <em>really</em> want a way to validate policies at compile time, consider moving to C++20. It’s possible to validate policies with C++14-era type traits… but it’s <em>massively</em> complex, and verbose. Not really worth it since C++20 is already out.</p>\n</li>\n<li><p>Don’t create <code>AdditionSqrtDecomposition</code> and <code>MultiplicationSqrtDecomposition</code> by inheritance. It’s overly complicated, and misguided; if <code>SqrtDecomposition</code> were meant to be a base type, it should have a virtual destructor. Use aliases instead.</p>\n</li>\n<li><p>Document everything better. You don’t necessarily need to explain the whole purpose of the class, because, presumably, anyone using it should know what it’s for. But at a <em>bare minimum</em>, you <em>do</em> need to document the preconditions and postconditions for every function (including constructors, destructors, etc.). That’s because while you can reasonably presume that only someone who understands your class would actually use it in code… the person <em>reviewing</em> or <em>maintaining</em> that code should not need the same level of understanding. A reviewer (or a static analyzer!) should be able to look at a function’s preconditions and postconditions, and—without understanding what black magic is happening inside—be able to spot when someone is passing invalid arguments (or when your functions’ returns are being used as invalid arguments to something else). (To verify that the black magic inside the class is okay, that’s what unit testing is for. Which, by the way…)</p>\n</li>\n<li><p>Test your code <em>properly</em>. That means writing unit tests, preferably with a proper unit testing framework. Test various normal input values, and make sure everything works as expected. Test edge cases. You don’t need to test failures due to precondition violations. But make sure that whenever the preconditions are satisfied, the postconditions are as well.</p>\n</li>\n<li><p>Consider using the established and widely-understood design pattern term “policy”, rather than the vague, idiosyncratic term “core”.</p>\n</li>\n<li><p>Watch out for signed/unsigned comparisons, and for cramming larger types (like <code>std::vector&lt;T&gt;::size_type</code>) into types with smaller ranges (like <code>int</code>, on some platforms).</p>\n</li>\n<li><p>Consider adding more constructors to make the type more flexible, so it can be constructed from things other than vectors, including arbirary ranges, arbitrary iterator/sentinel pairs, and even directly constructed with data.</p>\n</li>\n<li><p>(More difficult, complex, long-term suggestion.) Consider adding an allocator policy.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T06:24:58.737", "Id": "534132", "Score": "0", "body": "I can't thank you enough! I learned a lot and also about the things to learn, thanks for taking out the time for such a detailed explanation and review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T03:08:34.357", "Id": "270460", "ParentId": "270455", "Score": "4" } } ]
{ "AcceptedAnswerId": "270460", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T21:51:36.553", "Id": "270455", "Score": "2", "Tags": [ "c++", "c++11", "template", "c++14" ], "Title": "C++ template and inheritance - Generic Sqrt Decomposition" }
270455