body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I would like to reduce the following Python code. I have one list and a few if statements.</p> <pre><code>a=[one, two, three, four] </code></pre> <pre><code>if a[0] in b: print(a[1]) if a[1] in b: print(a[2]) if a[2] in b: print(a[3]) if a[3] in b: print(a[0]) </code></pre> <p>How can I reduce this to two lines of code and still to run in sequence? It will permit list a to be of &quot;n&quot; length and I will not have to add them individually.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T01:04:31.810", "Id": "480277", "Score": "4", "body": "This does not have enough context to be on topic. What are you actually trying to do with your application? Can you show your whole program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T05:45:28.023", "Id": "480292", "Score": "2", "body": "`print([a[(i+1)%len(a)] for i in range(len(a)) if a[i] in b])`" } ]
[ { "body": "<p>Firstly we can simply loop through <code>a</code> to get the values to check that are in <code>b</code>.\nHowever we need to know the index so we can increment a value, <code>i</code>, whilst looping through <code>a</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>i = 0\nfor value in a:\n if value in b:\n print(a[i + 1])\n i += 1\n</code></pre>\n<p>You should notice that this doesn't actually work. This is because on the last value of <code>a</code> we go out of bounds. To fix this we can simply use the modulo operator, <code>%</code>, to keep the value in bounds.</p>\n<pre class=\"lang-py prettyprint-override\"><code>i = 0\nfor value in a:\n if value in b:\n print(a[(i + 1) % len(a)])\n i += 1\n</code></pre>\n<p>From here we can use <code>enumerate</code> rather than increment <code>i</code> manually.\nAnd we start <code>i</code> at 1 to remove the need for that <code>(i + 1)</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i, value in enumerate(a, start=1):\n if value in b:\n print(a[i % len(a)])\n</code></pre>\n<p>From you have a couple of options.</p>\n<ul>\n<li>You can use <code>zip</code> with <code>itertools</code> to remove the need for <code>i % len(a)</code>. This isn't going to be nice to read but can be more performant.</li>\n<li>Use a comprehension to reduce this to one line of code.</li>\n</ul>\n<p>However these are more advanced topics.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T11:13:00.227", "Id": "480309", "Score": "0", "body": "Thank you. But how can I do this in sequence? For example with a top \"if\" and keyboard confirmation. Press enter show first item then another enter the second etc?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T11:15:29.027", "Id": "480310", "Score": "0", "body": "@AndyAndy You have not coded that and so asking for that is off-topic and I will not answer. If you manage to do that by yourself then you can post a new question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T10:51:36.587", "Id": "244655", "ParentId": "244641", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T00:04:07.593", "Id": "244641", "Score": "-3", "Tags": [ "python" ], "Title": "Printing the next element if the previous element is in a list" }
244641
<p>I have 2 scripts, one is a tkinter GUI script where the user gives specific inputs, the 2nd script takes those inputs, does some modification, and then sends it back to the GUI script to be written/results printed. However, in dealing with multiple user inputs, the entries for the functions started getting longer and longer, and uglier. As you'll see in the GUI script, when I use the function I imported, it has 7 entries which make it quite long. Is there a better way to call user inputs from one script to another?</p> <pre><code>#GUI Script (NOTE: I'm not posting all the global and input functions, since they are basically the same thing. Don't want to be reptitious) #basic tkinter setup root=tk.Tk() with the loop and everything setup #globals where filenames and directories to files are saved, to be called on in the functions sparta_file=() sparta_directory=() seq_file=() seq_directory=() #browse options to choose files def input_file(): fullpath = filedialog.askopenfilename(parent=root, title='Choose a file') global sparta_directory global sparta_file sparta_directory=os.path.dirname(fullpath) sparta_file= os.path.basename(fullpath) label2=Label(root,text=fullpath).grid(row=0,column=1) def input_seq(): fullpath = filedialog.askopenfilename(parent=root, title='Choose a file') global seq_file global seq_directory seq_directory=os.path.dirname(fullpath) seq_file= os.path.basename(fullpath) label3=Label(root,text=fullpath).grid(row=1,column=1) #All the user inputs are designed more or less the same, user browses, clicks on file, and files directory and filename are saved as globals. #function that will be run to use user inputs, modify them, and then write modifications def sparta_gen_only(): from sparta_file_formatter import check_sparta_file_boundaries os.chdir(save_directory) with open(save_file_sparta,'w') as file: for stuff_to_write in check_sparta_file_boundaries(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start): file.write(stuff_to_write+'\n') </code></pre> <p>So right off the bat, you can see the exact issue I'm having (check_sparta_file boundaries has a lot of inputs).</p> <pre><code>#2nd sparta_file_formatter import re import os def create_seq_list(seq_file,seq_directory,seq_start): os.chdir(seq_directory) amino_acid_count=(0+seq_start)-1 sequence_list=[] with open(seq_file) as sequence_file: for amino_acid in sequence_file: stripped_amino_acid=amino_acid.strip().upper() for word in stripped_amino_acid: amino_acid_count+=1 sequence_list.append(str(amino_acid_count)+word) return sequence_list def format_sparta(sparta_file,sparta_directory): os.chdir(sparta_directory) sparta_file_list1=[] proline_counter=0 with open(sparta_file) as sparta_predictions: for line in sparta_predictions: modifier=line.strip().upper() if re.findall('^\d+',modifier): A=modifier.split() del A[5:8] del A[3] A[0:3]=[&quot;&quot;.join(A[0:3])] joined=&quot; &quot;.join(A) proline_searcher=re.search('\BP',joined) if proline_searcher != None: proline_counter+=1 if proline_counter&lt;2: proline_count=re.search('^\d+',joined) sparta_file_list1.append(f'{proline_count.group(0)}PN'+' 1000'+' 1000') else: if proline_count == 4: proline_count=re.search('^\d+',joined) sparta_file_list1.append(f'{proline_count.group(0)}PHN'+' 1000'+' 1000') proline_counter=0 sparta_file_list1.append(joined) return sparta_file_list1 #Each function the entries get longer and longer as they start using the outputs of the previous functions def add_mutation(mutation_list1,mutation_list2,sparta_file,sparta_directory): sparta_file_list2=[] if mutation_list1==() or mutation_list2==(): for amino_acids in format_sparta(sparta_file,sparta_directory): sparta_file_list2.append(amino_acids) else: for mutations,mutations2 in zip(mutation_list1,mutation_list2): for amino_acids in format_sparta(sparta_file,sparta_directory): if re.findall(mutations,amino_acids): splitting=amino_acids.split() mutation=re.sub(mutations,mutations2,splitting[0]) mutation_value=re.sub('\d+.\d+',' 1000',splitting[1]) mutation_value2=re.sub('\d+.\d+',' 1000',splitting[2]) mutation_replacement=mutation+mutation_value+mutation_value2 sparta_file_list2.append(mutation_replacement) else: sparta_file_list2.append(amino_acids) return sparta_file_list2 def filter_sparta_using_seq(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start): sparta_file_list3=[] sparta_comparison=create_seq_list(seq_file,seq_directory,seq_start) for aa in add_mutation(mutation_list1,mutation_list2,sparta_file,sparta_directory): modifiers=aa.strip() splitter=modifiers.split() searcher=re.search('^\d+[A-Z]',splitter[0]) compiler=re.compile(searcher.group(0)) sparta_sequence_comparison=list(filter(compiler.match,sparta_comparison)) if sparta_sequence_comparison != []: sparta_file_list3.append(aa) return sparta_file_list3 def check_sparta_file_boundaries(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start): temp_list=[] temp_counter=0 sparta_filtered_list=filter_sparta_using_seq(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start) for checker in sparta_filtered_list: temp_modifier=checker.strip() temp_split=temp_modifier.split() temp_finder=re.search('^\d+',temp_split[0]) temp_list.append(temp_finder.group(0)) temp_counter+=1 if temp_counter==5: if int(temp_finder.group(0))==int(temp_list[0]): break else: del sparta_filtered_list[0:4] break if len(sparta_filtered_list)%6 != 0: del sparta_filtered_list[-5:-1] return sparta_filtered_list </code></pre> <p>Edit:</p> <p>In terms of exactly what sparta is and what my code is doing. I won't go into too much detail regarding sparta, outside of it is a text file with information we want. This is the format:</p> <pre><code>REMARK SPARTA+ Protein Chemical Shift Prediction Table REMARK All chemical shifts are reported in ppm: .... 3 Y HA 0.000 4.561 4.550 0.018 0.000 0.201 3 Y C 0.000 175.913 175.900 0.021 0.000 1.272 3 Y CA 0.000 58.110 58.100 0.017 0.000 1.940 3 Y CB 0.000 38.467 38.460 0.011 0.000 1.050 4 Q N 3.399 123.306 119.800 0.179 0.000 2.598 ... </code></pre> <p>We only care about the lines with the numbers, so I use a regex search to only extract that. Now the info I want is the first 3 columns, with the 4 column. I want each data formatted <code>3YHA 4.561</code> (2nd function). Now every number should have 6 values associated with it, those that are P, will only have 4, so I add 2 extra values (you may note in the above, the format is HA,C,CA,CB,etc. So I add the values so the format of P is N,HA,C,CA,CB.</p> <p>Sometimes the user will wish to change a specific letter (mutation). So they indicate which letter, the number, and what to change it to (3rd loop).</p> <p>Finally, these files can sometimes have extra info we don't care about. The user specifies the range of info they want by using a seq file (1st and 4rd loop).</p> <p>As stated, every letter should have 6 values. However, the first letter will always have 4. The last letter will also only have 5. So these need to be removed (loop 5).</p> <p>Here is some sample input files as examples:</p> <pre><code>seq_number=1 #seq.txt MSYQVLARKW #sparta_pred.tab 3 Y HA 0.000 4.561 4.550 0.018 0.000 0.201 3 Y C 0.000 175.913 175.900 0.021 0.000 1.272 3 Y CA 0.000 58.110 58.100 0.017 0.000 1.940 3 Y CB 0.000 38.467 38.460 0.011 0.000 1.050 4 Q N 3.399 123.306 119.800 0.179 0.000 2.598 4 Q HA 0.146 4.510 4.340 0.039 0.000 0.237 4 Q C -2.091 173.967 176.000 0.097 0.000 0.914 4 Q CA -0.234 55.623 55.803 0.092 0.000 1.065 4 Q CB 3.207 32.000 28.738 0.092 0.000 1.586 4 Q HN 0.131 8.504 8.270 0.173 0.000 0.484 5 V N 0.131 120.091 119.914 0.078 0.000 2.398 5 V HA 0.407 4.575 4.120 0.080 0.000 0.286 5 V C 0.162 176.322 176.094 0.109 0.000 1.026 5 V CA -1.507 60.840 62.300 0.078 0.000 0.868 5 V CB 0.770 32.625 31.823 0.052 0.000 0.982 5 V HN 0.418 8.642 8.190 0.057 0.000 0.443 6 L N 7.083 128.385 121.223 0.130 0.000 2.123 6 L HA -0.504 4.085 4.340 0.415 0.000 0.217 6 L C 1.827 178.814 176.870 0.195 0.000 1.081 6 L CA 3.308 58.271 54.840 0.205 0.000 0.772 6 L CB -1.005 41.051 42.059 -0.005 0.000 0.890 6 L HN 0.241 8.694 8.230 0.097 -0.164 0.437 7 A N -4.063 118.812 122.820 0.092 0.000 2.131 7 A HA -0.337 4.023 4.320 0.067 0.000 0.220 7 A C 0.433 178.071 177.584 0.090 0.000 1.158 7 A CA 2.471 54.552 52.037 0.073 0.000 0.665 7 A CB -0.332 18.690 19.000 0.036 0.000 0.795 7 A HN -0.517 7.889 8.150 0.063 -0.219 0.460 8 R N -4.310 116.247 120.500 0.096 0.000 2.191 8 R HA -0.056 4.313 4.340 0.048 0.000 0.196 8 R C 2.152 178.488 176.300 0.060 0.000 0.991 8 R CA 1.349 57.485 56.100 0.060 0.000 1.075 8 R CB 0.834 31.147 30.300 0.023 0.000 1.040 8 R HN 0.244 8.408 8.270 0.109 0.172 0.526 9 K N 0.144 120.608 120.400 0.108 0.000 2.283 9 K HA -0.130 4.148 4.320 -0.069 0.000 0.202 9 K C 0.691 177.214 176.600 -0.129 0.000 1.048 9 K CA 2.415 58.707 56.287 0.008 0.000 0.948 9 K CB -0.114 32.430 32.500 0.074 0.000 0.742 9 K HN -0.617 7.728 8.250 0.159 0.000 0.458 10 W N -4.007 117.283 121.300 -0.016 0.000 2.846 10 W HA 0.195 4.850 4.660 -0.009 0.000 0.391 10 W C -1.455 175.056 176.519 -0.013 0.000 1.011 10 W CA -1.148 56.191 57.345 -0.011 0.000 1.832 10 W CB 0.166 29.622 29.460 -0.007 0.000 1.151 10 W HN -0.634 7.728 8.180 0.377 0.045 0.582 11 R N 1.894 122.475 120.500 0.134 0.000 2.483 11 R HA -0.096 4.293 4.340 0.083 0.000 0.329 11 R C -1.368 174.959 176.300 0.045 0.000 0.961 11 R CA -0.713 55.431 56.100 0.073 0.000 1.041 11 R CB 0.187 30.506 30.300 0.033 0.000 0.930 11 R HN -0.880 7.272 8.270 0.107 0.182 0.413 12 P HA -0.173 4.278 4.420 0.051 0.000 0.257 12 P C -1.027 176.281 177.300 0.014 0.000 1.162 12 P CA 0.741 63.865 63.100 0.040 0.000 0.762 12 P CB 0.046 31.768 31.700 0.036 0.000 0.753 13 Q N 1.152 120.951 119.800 -0.001 0.000 2.396 13 Q HA 0.193 4.514 4.340 -0.032 0.000 0.220 13 Q C 0.275 176.261 176.000 -0.024 0.000 0.900 13 Q CA 0.394 56.181 55.803 -0.027 0.000 0.925 13 Q CB 2.516 31.223 28.738 -0.051 0.000 1.065 13 Q HN 0.012 8.472 8.270 0.002 -0.188 0.535 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T03:00:21.213", "Id": "480285", "Score": "2", "body": "What is Sparta? What is this actually doing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T05:30:27.690", "Id": "480290", "Score": "0", "body": "I added edits to address this. But its basically a text file with data, we extract the data we want and modify it based on user input (mutations to change specific letters, sequence to indicate the bounds), However my question here is to find another technique of using functions like this without having a bunch of entries." } ]
[ { "body": "<h2>Returns, not globals</h2>\n<p>Don't declare these at the global level:</p>\n<pre><code>sparta_file=()\nsparta_directory=()\nseq_file=()\nseq_directory=()\n</code></pre>\n<p>Instead, return them from functions; e.g.</p>\n<pre><code>def input_file():\n fullpath = filedialog.askopenfilename(parent=root, title='Choose a file')\n sparta_directory=os.path.dirname(fullpath)\n sparta_file= os.path.basename(fullpath)\n return sparta_directory, sparta_file\n</code></pre>\n<h2>Pathlib</h2>\n<p>Probably best to replace your use of <code>os.path</code> with <code>pathlib</code>, whose object-oriented interface is nicer to use.</p>\n<h2>Local imports</h2>\n<p>such as</p>\n<pre><code> from sparta_file_formatter import check_sparta_file_boundaries\n</code></pre>\n<p>should be moved to the top of the file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T17:20:54.040", "Id": "480611", "Score": "0", "body": "Is there any advantage to not redefine them at the global level? It seems a little bit less clean since in my other script, I'd have to call the function in the argument I.E. some_function(input_file()), instead of some_function(input_file). And in some cases when I have multiple inputs, then I'll have multiple functions I'll be calling in as entries" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T17:09:08.503", "Id": "480825", "Score": "0", "body": "Yes, there are many advantages. The fewer side-effects a function has, the better; and setting a global is a side-effect. Functions that accept parameters are easier to test, reuse, maintain and understand than functions that rely on globals." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T23:17:31.640", "Id": "244760", "ParentId": "244643", "Score": "1" } }, { "body": "<h1>Architecture</h1>\n<p>Your main architectural problem is that instead of</p>\n<pre><code>def make_a(params):\n return a\n\ndef make_b(a, params):\n return b\n\ndef make_c(b, params):\n return c\n\ndef make_result(c, params):\n return result\n\na = make_a(params_a)\nb = make_b(a, params_b)\nc = make_c(b, params_c)\nresult = make_result(c, params_result)\n</code></pre>\n<p>you do</p>\n<pre><code>def make_a(params):\n return a\n\ndef make_b(params_a, params_b):\n a = make_a(params_a) \n return b\n\ndef make_c(params_a, params_b, params_c):\n b = make_b(params_a, params_b)\n return c\n\ndef make_result(params_a, params_b, params_c, params_result):\n c = make_c(params_a, params_b, params_c)\n return result\n\nresult = makeresult(params_a, params_b, params_c, params_result)\n</code></pre>\n<p>Instead of calling a function_1 to generate the necessary artefacts to pass to the next function_2 you call the function_1 inside function_2 and therefore you have to pass the requirements for function_2 as well.</p>\n<p>In your case in function</p>\n<pre><code>def check_sparta_file_boundaries(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start):\n temp_list=[]\n temp_counter=0\n sparta_filtered_list=filter_sparta_using_seq(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start)\n for checker in sparta_filtered_list:\n temp_modifier=checker.strip()\n temp_split=temp_modifier.split()\n temp_finder=re.search('^\\d+',temp_split[0])\n temp_list.append(temp_finder.group(0))\n temp_counter+=1\n if temp_counter==5:\n if int(temp_finder.group(0))==int(temp_list[0]):\n break\n else:\n del sparta_filtered_list[0:4]\n break\n if len(sparta_filtered_list)%6 != 0:\n del sparta_filtered_list[-5:-1]\n\n return sparta_filtered_list\n</code></pre>\n<p>you shall call <code>filter_sparta_using_seq</code> before calling <code>check_sparta_file_boundaries</code> and pass <code>sparta_filtered_list</code> instead of the parameters required for <code>filter_sparta_using_seq</code></p>\n<pre><code>def check_sparta_file_boundaries(sparta_filtered_list):\n temp_list=[]\n temp_counter=0\n # line removed ...\n for checker in sparta_filtered_list:\n temp_modifier=checker.strip()\n temp_split=temp_modifier.split()\n temp_finder=re.search('^\\d+',temp_split[0])\n temp_list.append(temp_finder.group(0))\n temp_counter+=1\n if temp_counter==5:\n if int(temp_finder.group(0))==int(temp_list[0]):\n break\n else:\n del sparta_filtered_list[0:4]\n break\n if len(sparta_filtered_list)%6 != 0:\n del sparta_filtered_list[-5:-1]\n\n return sparta_filtered_list\n\ndef main_program_flow():\n sparta_filtered_list = filter_sparta_using_seq(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start)\n sparta_filtered_list = check_sparta_file_boundaries(sparta_filtered_list)\n</code></pre>\n<p>Next you do the same for <code>filter_sparta_using_seq</code> and so on.</p>\n<p>I tried to answer your specific question and hope you got the idea.</p>\n<hr />\n<p>EDIT:</p>\n<p>The same is valid for your function in the first file</p>\n<pre><code>def sparta_gen_only():\n from sparta_file_formatter import check_sparta_file_boundaries\n os.chdir(save_directory)\n with open(save_file_sparta,'w') as file:\n for stuff_to_write in check_sparta_file_boundaries(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start):\n file.write(stuff_to_write+'\\n')\n</code></pre>\n<p>where you did not pass the parameters but act on globals. Again we do not call from the inside but call before and pass the results. Also we pass parameters instead of using globals.</p>\n<pre><code>def sparta_gen_only(sparta_filtered_list, directory_name, file_name):\n os.chdir(directory_name)\n with open(file_name, 'w') as file:\n for stuff_to_write in sparta_filtered_list:\n file.write(stuff_to_write + '\\n')\n\ndef main_program_flow():\n sparta_filtered_list = filter_sparta_using_seq(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start)\n sparta_filtered_list = check_sparta_file_boundaries(sparta_filtered_list)\n sparta_gen_only(sparta_filtered_list, save_directory, save_file_sparta)\n</code></pre>\n<h1>some other points</h1>\n<ul>\n<li>Get rid of the habit to change directory. At least for file read this is a no-go. Let the user determine the working directory.</li>\n<li>There is nothing wrong with fully qualified file names. You do not need to split to directory/basename.</li>\n<li>After restructuring your code according to the pattern above, there shall be no more globals</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T04:21:51.597", "Id": "480549", "Score": "0", "body": "OH I see, so if I want to call the function and import its value, all I need to do is use it as an entry for the next function. The only issue is how do I use its value though in the next function. I assumed I'd need to redefine that value (that's why I do a=previous fun(previous entry) to use its values." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T01:20:25.440", "Id": "244766", "ParentId": "244643", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T01:05:09.520", "Id": "244643", "Score": "3", "Tags": [ "python" ], "Title": "Protein Chemical Shift Prediction processing" }
244643
<p>I'm still a relative beginner to coding and I would like some feedback on my Minesweeper clone written in Python using Pygame for the graphics. I'm wondering if it would be beneficial to use classes anywhere, or if there's simply a better way of doing what I'm trying to do. Thank you very much—any help is much appreciated.</p> <pre><code>import random, sys import pygame as pg import numpy as np import collections WIDTH = 200 GREY = (128,128,128) #rgb value DARKGREY = (105,105,105) WHITE = (200,200,200) RED = (255, 0, 0) BLUE = (0, 0, 255) GREEN = (0, 128, 0) PURPLE = (128, 0, 128) MAGENTA = (255,0,255) ORANGE = (255, 165, 0) YELLOW = (255,255,0) BLACK = (0,0,0) BOARD_SIZE = 20 WIDTH = HEIGHT = BOARD_SIZE * 20 #window dimensions NUM_BOMBS = 40 colors = [RED, BLUE, GREEN, PURPLE, MAGENTA, ORANGE, YELLOW, BLACK] #random.seed(1) def init_board(): board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)] for i in range(NUM_BOMBS): #while count(board) &lt; 40: row = random.randint(1, BOARD_SIZE-1) column = random.randint(1, BOARD_SIZE-1) board[row][column] = 9 # print(np.array(board)) # print(&quot;\n&quot;) return board def count(board): ret = 0 for row in board[0]: for col in board: if board[row][col]==9: print(board[row][j]) ret+=1 return ret def create_grid(): board = init_board() pg.init() SQUARE_SIZE = 20 win = pg.display.set_mode((HEIGHT, WIDTH)) win.fill(GREY) pg.display.set_caption(&quot;Minesweeper&quot;) font = pg.font.SysFont('Arial', 25) BOMB_IMG = pg.image.load(&quot;bomb.png&quot;) FLAG_IMG = pg.image.load(&quot;flag.png&quot;) rect2 = BOMB_IMG.get_rect() rect3 = FLAG_IMG.get_rect() moveable = True done = False lost = False called = [[]] found = 0 for x in range(BOARD_SIZE): for y in range(BOARD_SIZE): # draw grid rectColor = WHITE rect = pg.Rect(y * SQUARE_SIZE, x * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE) pg.draw.rect(win, rectColor, rect, 1) while not done: for event in pg.event.get(): if moveable and event.type == pg.MOUSEBUTTONDOWN: Mouse_x, Mouse_y = pg.mouse.get_pos() print(np.array(board)) if event.button == 1: if board[Mouse_y // 20][Mouse_x // 20] != 9: board = uncover_squares(board, [Mouse_y // 20, Mouse_x // 20]) # print(np.array(board)) for row in range(len(board)): for col in range(len(board)): if board[row][col] != 0 and board[row][col] != 9: if board[row][col]==-1: rect4 = pg.Rect(col * SQUARE_SIZE, row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE) pg.draw.rect(win, WHITE, rect4, 0) else: rect4 = pg.Rect(col * SQUARE_SIZE, row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE) pg.draw.rect(win, WHITE, rect4, 0) render_num(win, font, board[row][col], colors[board[row][col]], col*20, row*20) if board[Mouse_y // 20][Mouse_x // 20] != -1: rect6 = pg.Rect(Mouse_x//20 * 20, Mouse_y//20 * 20, SQUARE_SIZE, SQUARE_SIZE) render_num(win,font, board[Mouse_y //20 ][Mouse_x//20], colors[board[Mouse_y //20][Mouse_x//20]], Mouse_x, Mouse_y) #pg.draw.rect(win, DARKGREY, rect6, 0) if board[Mouse_y //20 ][Mouse_x//20] == 9: display_img(win, BOMB_IMG, Mouse_x, Mouse_y, rect2) moveable= False pg.display.set_caption(&quot;You lost!&quot;) lost = True if event.button == 3 and board[Mouse_y // 20][Mouse_x // 20] not in range(len(colors)): if board[Mouse_y // 20][Mouse_x // 20] == 9: found+=1 if found == NUM_BOMBS and not any(0 in x for x in board): moveable = False pg.display.set_caption(&quot;You won!&quot;) if event.type == pg.QUIT: done = True pg.display.update() #update display pg.quit() sys.exit() def render_num(screen, font, num, color, mouse_x, mouse_y): screen.blit(font.render(str(num), True, color), (mouse_x // 20 * 20, mouse_y // 20 * 20)) def display_img(screen, img, mouse_x, mouse_y, rect): screen.blit(img, (mouse_x//20 * 20, mouse_y//20 * 20), rect) def uncover_squares(board, move): neighbors = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)] uncover(move[0], move[1], len(board), len(board[0]), board, neighbors) return board def uncover(i, j, m, n, board, neighbors): if board[i][j] != 0: return mine_count = 0 for cell in neighbors: #make sure the search is in bounds of array, then check if neighbor is a bomb if 0 &lt;= i + cell[0] &lt; m and 0 &lt;= j + cell[1] &lt; n and board[i + cell[0]][j + cell[1]] == 9: mine_count += 1 if mine_count == 0: board[i][j] = -1 else: board[i][j] = mine_count return for cell in neighbors: if 0 &lt;= i + cell[0] &lt; m and 0 &lt;= j + cell[1] &lt; n: uncover(i + cell[0], j + cell[1], m, n, board, neighbors) #call neighbors if __name__ == &quot;__main__&quot;: create_grid() </code></pre>
[]
[ { "body": "<h1>Remove commented out code</h1>\n<p>All the code that has been commented out distracts from the actual code. You commented it out for a reason: you don't need it anymore.</p>\n<h1>Type Hints</h1>\n<p>These help the user see what is accepted by a function, and what is returned by a function. It's helpful when you need to remember what functions accept what types of values.</p>\n<pre><code>from typing import List\n\ndef count(board: List[List[int]]) -&gt; int:\n ....\n</code></pre>\n<h1><code>create_grid</code></h1>\n<p>To be frank, this function is really messy. You indent <em><strong>nine</strong></em> times. I would break this into smaller functions that handle different parts of creating the grid.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-07T17:01:40.393", "Id": "481376", "Score": "0", "body": "The commented-out code removal is particularly a good idea if you're using source control, which everyone should anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-07T17:02:19.910", "Id": "481377", "Score": "0", "body": "The _type hints_ suggestion is a good one but should have either a PEP reference or an example for the OP to go off of." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-07T16:43:49.877", "Id": "245140", "ParentId": "244644", "Score": "1" } }, { "body": "<h2>Nomenclature</h2>\n<p><code>create_grid</code> does not just create the grid - it runs the entire game and then kills the process. It should be divided up into multiple functions, but that aside, it does not do what's on the tin.</p>\n<h2>Forced-exit</h2>\n<p>Your use of <code>sys.exit()</code> is not a great idea. What if a unit tester (who would have a difficult time anyway, given the size of your function) wanted to test multiple runs of <code>create_grid</code>? Or what if a different caller wanted to run your game, and then perform some other cleanup after?</p>\n<h2>Round-to-multiple</h2>\n<p>This:</p>\n<pre><code>mouse_x // 20 * 20, mouse_y // 20 * 20\n</code></pre>\n<p>is a little awkward. An alternative is</p>\n<pre><code>mouse_x - mouse_x%20, mouse_y - mouse_y%20\n</code></pre>\n<h2>Early-return</h2>\n<p>I would find</p>\n<pre><code> if mine_count == 0:\n board[i][j] = -1\n else:\n board[i][j] = mine_count\n return\n for cell in neighbors:\n if 0 &lt;= i + cell[0] &lt; m and 0 &lt;= j + cell[1] &lt; n:\n uncover(i + cell[0], j + cell[1], m, n, board, neighbors) #call neighbors\n</code></pre>\n<p>more legible as</p>\n<pre><code> if mine_count == 0:\n board[i][j] = -1\n for cell in neighbors:\n if 0 &lt;= i + cell[0] &lt; m and 0 &lt;= j + cell[1] &lt; n:\n uncover(i + cell[0], j + cell[1], m, n, board, neighbors) #call neighbors\n else:\n board[i][j] = mine_count\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-07T17:10:10.170", "Id": "245141", "ParentId": "244644", "Score": "2" } } ]
{ "AcceptedAnswerId": "245141", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T01:11:55.130", "Id": "244644", "Score": "5", "Tags": [ "python", "game", "pygame", "minesweeper" ], "Title": "Pygame Minesweeper Clone" }
244644
<p>I am a beginner, and so I have decided to program a Roman Numeral to Arabic integer converter. I came up with all of the code on my own. There are differing opinions about what constitutes 'proper' Roman Numerals. For example, 'IIII' is odd but known to exist in ancient writings, and 'VIIV' is a silly but parsable way to write '8'. And so my program will treat any valid string as acceptable and attempt to parse it.</p> <p>It works and I would welcome any comments or considerations, especially with regards to the following:</p> <ul> <li>general best practice,</li> <li>whether the input verification can be made cleaner,</li> <li>if there is a nicer way than using a dictionary to match the characters and values,</li> <li>efficiency of the part which calculates the totals, and</li> <li>if I should add comments to the code.</li> </ul> <pre><code>import re bad = 1 while bad == 1: roman = input('Enter a Roman Numeral: ') test = re.findall('[^IVXLCDM]+', roman) lengthtracker = 0 for item in test: length = len(item) lengthtracker = lengthtracker + length if length != 0: print('Roman Numerals may contain only the characters I, V, X, L, C, D, M') break else: continue if lengthtracker == 0: bad = 0 print('Roman Numeral verified!') ref = dict() ref['I'] = 1 ref['V'] = 5 ref['X'] = 10 ref['L'] = 50 ref['C'] = 100 ref['D'] = 500 ref['M'] = 1000 n = len(roman) m = 0 total = 0 negtotal = 0 tenttotal = 0 while m &lt; n-1: if ref[roman[m]] == ref[roman[m+1]]: tenttotal = tenttotal + ref[roman[m]] elif ref[roman[m]] &gt; ref[roman[m+1]]: total = total + tenttotal + ref[roman[m]] tenttotal = 0 else: negtotal = negtotal + tenttotal + ref[roman[m]] tenttotal = 0 print(total, negtotal, tenttotal) m = m + 1 total = total + tenttotal + ref[roman[m]] - negtotal print('It equals:', total) </code></pre>
[]
[ { "body": "<h2>Dict initialization and reuse</h2>\n<p>This:</p>\n<pre><code>ref = dict() \nref['I'] = 1\nref['V'] = 5\nref['X'] = 10\nref['L'] = 50\nref['C'] = 100\nref['D'] = 500\nref['M'] = 1000\n</code></pre>\n<p>should use a dict literal:</p>\n<pre><code>ref = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000,\n}\n</code></pre>\n<p>You should declare this at the top of the program, so that this:</p>\n<pre><code>'[^IVXLCDM]+'\n</code></pre>\n<p>can become</p>\n<pre><code>'[^' + ''.join(ref.keys()) + ']+'\n</code></pre>\n<p>and this</p>\n<pre><code>'Roman Numerals may contain only the characters I, V, X, L, C, D, M'\n</code></pre>\n<p>can become</p>\n<pre><code>'Roman Numerals may contain only the characters ' + ', '.join(ref.keys())\n</code></pre>\n<h2>No-op continue</h2>\n<p>This:</p>\n<pre><code> else:\n continue\n</code></pre>\n<p>has no effect and can be deleted.</p>\n<h2>Booleans</h2>\n<p><code>bad</code> should use <code>True</code> and <code>False</code> rather than 1 and 0.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T01:45:50.267", "Id": "480279", "Score": "0", "body": "Thank you for this quick and helpful answer! It seems the main goal of your changes is to save space and be efficient. Am I correct about that? I just want to make sure I get why certain things are best practice. To that end, is the boolean correct you suggest *inherently* better (and if so, why?) or is it simply just considered best practice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T02:00:16.490", "Id": "480280", "Score": "4", "body": "_save space and be efficient_ - sure; basically. Say more with less, and don't repeat yourself while keeping the code legible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T02:00:51.680", "Id": "480281", "Score": "2", "body": "The boolean is because it more accurately reflects what you're trying to do - represent a yes/no variable, which is what a boolean is designed for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T02:01:51.890", "Id": "480282", "Score": "0", "body": "Thank you very much again! I appreciate you taking the time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T15:12:04.413", "Id": "480327", "Score": "3", "body": "I would go a step further and not use the flag `bad` at all. Use an infinite loop `while True`, and use `break` where you would have set `bad = 0` to terminate the loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T16:47:21.917", "Id": "480339", "Score": "0", "body": "@chepner I admit I only didn't do that because `while True` scares me, but I suppose I should get over that. Thanks for the tip!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T01:37:41.100", "Id": "244646", "ParentId": "244645", "Score": "14" } }, { "body": "<p>You can simplify <code>foo = foo + ...</code> to just <code>foo += ...</code>.</p>\n<p>For example you can simplify the following two lines:</p>\n<blockquote>\n<pre><code>m = m + 1\n</code></pre>\n</blockquote>\n<pre><code>m += 1\n</code></pre>\n<blockquote>\n<pre><code>total = total + tenttotal + ref[roman[m]] - negtotal\n</code></pre>\n</blockquote>\n<pre><code>total += tenttotal + ref[roman[m]] - negtotal\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T16:46:02.550", "Id": "480338", "Score": "0", "body": "Thank you for these hints! Definitely a space saver." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T16:49:03.310", "Id": "480340", "Score": "1", "body": "Liked it that I could be helpful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T05:49:45.533", "Id": "244651", "ParentId": "244645", "Score": "1" } }, { "body": "<p>The algorithm you're using is excessively complex. There's no need to track <code>total</code> and <code>negtotal</code> separately. You also don't need <code>tenttotal</code> unless you want to support particularly exotic numerals like IIX (which is rare but <a href=\"https://commons.wikimedia.org/wiki/File:Sonnenuhr_Jubi_Juist.JPG\" rel=\"nofollow noreferrer\">apparently not unattested</a>). And if you're not tracking <code>tenttotal</code>, then you don't need to distinguish the &quot;current = next&quot; and &quot;current &gt; next&quot; cases, either.</p>\n<p>The algorithm I'd use is:</p>\n<ul>\n<li>Start with total = 0.</li>\n<li>For each character in the string:\n<ul>\n<li>If the current character's value is less than the following character's value, subtract the current character's value from the total.</li>\n<li>Otherwise, add the current character's value to the total.</li>\n</ul>\n</li>\n</ul>\n<p>So, something like this:</p>\n<pre><code>for i in range(len(roman)):\n current_char_value = ref[roman[i]]\n next_char_value = ref[roman[i+1]] if i+1 &lt; len(roman) else 0\n\n if current_char_value &lt; next_char_value:\n total -= current_char_value\n else:\n total += current_char_value\n</code></pre>\n<p>By the way, <code>ref</code> is a strange name for your dictionary. <code>letter_values</code> would make a lot more sense.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T17:02:47.360", "Id": "480342", "Score": "0", "body": "I do want to support things like 'IIX', I fear. I did try this algorithm at first." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T16:56:29.130", "Id": "244669", "ParentId": "244645", "Score": "1" } } ]
{ "AcceptedAnswerId": "244646", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T01:19:59.020", "Id": "244645", "Score": "10", "Tags": [ "python", "beginner", "roman-numerals" ], "Title": "Convert Roman Numerals to integers" }
244645
<p>I am working on classification problem, My input data is labels and output expected data is labels</p> <pre><code>Labels Count 1 94481 0 65181 2 60448 </code></pre> <p>I have made X, Y pairs by shifting the X and Y is changed to the categorical value</p> <h1>create X/y pairs</h1> <pre><code>df1 = df['Data_Used'] df1 = concat([df1, df1.shift(1)], axis=1) df1.dropna(inplace=True) </code></pre> <pre><code> X Y 2 1.0 1 2.0 1 1.0 2 1.0 2 2.0 </code></pre> <pre><code>values = df1.values encoder = LabelEncoder() test_labels = to_categorical(encoder.fit_transform(values[:,1]),num_classes=3) train_X,test_X,train_y,test_y= train_test_split(values[:,0], test_labels,test_size = 0.30,random_state = 42) print(train_X.shape) print(train_y.shape) print(test_X.shape) print(test_y.shape) </code></pre> <p>(154076,) (154076, 3) (66033,) (66033, 3)<br /> Converting this to LSTM format</p> <pre><code>train_X = train_X.reshape(train_X.shape[0],1,1) test_X = test_X.reshape(test_X.shape[0],1,1) # configure network n_batch = 1 n_epoch = 10 n_neurons = 100 </code></pre> <p>ModelArchitecture</p> <pre><code>tf.keras.backend.clear_session() model = tf.keras.models.Sequential([ tf.keras.layers.LSTM(n_neurons, batch_input_shape=(n_batch, train_X.shape[1],train_X.shape[2]), stateful=True), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(100, activation = 'relu',kernel_regularizer=regularizers.l2(0.0001)), tf.keras.layers.Dense(3, activation='softmax') ]) model.summary() model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc']) history = model.fit(train_X,train_y,validation_data=(test_X, test_y),epochs=n_epoch, batch_size=n_batch, verbose=1,shuffle= False) </code></pre> <p>Validation Accuracy is not Changing</p> <pre><code>Epoch 1/5 154076/154076 [==============================] - 356s 2ms/step - loss: 1.0844 - acc: 0.4269 - val_loss: 1.0814 - val_acc: 0.4310 Epoch 2/5 154076/154076 [==============================] - 354s 2ms/step - loss: 1.0853 - acc: 0.4256 - val_loss: 1.0813 - val_acc: 0.4310 Epoch 3/5 154076/154076 [==============================] - 355s 2ms/step - loss: 1.0861 - acc: 0.4246 - val_loss: 1.0814 - val_acc: 0.4310 Epoch 4/5 154076/154076 [==============================] - 356s 2ms/step - loss: 1.0874 - acc: 0.4228 - val_loss: 1.0825 - val_acc: 0.4310 Epoch 5/5 154076/154076 [==============================] - 353s 2ms/step - loss: 1.0887 - acc: 0.4208 - val_loss: 1.0828 - val_acc: 0.4310 </code></pre> <p>What can be the changes to improve the model.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T15:59:53.647", "Id": "480333", "Score": "1", "body": "Can you share the part of the code to download/ load the `values`? Also does increasing `num_epochs` has any effect ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T16:26:46.223", "Id": "480337", "Score": "0", "body": "@ankk I have updated the code, eventhough increasing the num_epochs my validation accuracy is not changing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T03:01:31.493", "Id": "487476", "Score": "0", "body": "can you share your data?" } ]
[ { "body": "<p>One possible reason of this could be unbalanced data. You should have same amount of examples per label. And if you don't have that data, you can use <strong>Loss Weights</strong>. It is a parameter in <strong>model.compile()</strong>. You can learn more about Loss weights on google.</p>\n<p>Also, I noticed you were using rmsprop as the optimizer. Try using Adam optimizer, as it is one of the best optimizer.</p>\n<p>If, doing all of these I mentioned above, doesn't changes anything and the results are the same, remove the Dense() Layers and just keep 1 dense() layer, that is, just keep the last Dense Layer, and remove all the other Dense() Layers.</p>\n<p>This will surely improve the model. But, if still it doesn't changes anything, then have a look <a href=\"https://stats.stackexchange.com/a/352037\">here</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T06:23:07.797", "Id": "251080", "ParentId": "244658", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T12:08:07.290", "Id": "244658", "Score": "2", "Tags": [ "python", "neural-network", "keras", "lstm" ], "Title": "LSTM Model - Validation Accuracy is not changing" }
244658
<p>Just finished an exercise in the Rust online book and I wanted to know if there is anything worth talking about in the code I wrote... if there's any mistake or optimization possible.</p> <p><strong>Convert strings to pig latin</strong></p> <ul> <li><p>The first consonant of each word is moved to the end of the word and “ay” is added, so “first” becomes “irst-fay”.</p> </li> <li><p>Words that start with a vowel have “hay” added to the end instead (“apple” becomes “apple-hay”).</p> </li> <li><p>Keep in mind the details about UTF-8 encoding!</p> </li> </ul> <pre><code>use std::io; fn main() { let mut user_input = String::new(); io::stdin() .read_line(&amp;mut user_input) .expect(&quot;Failed to read line.&quot;); for word in user_input.split_whitespace() { match word.chars().nth(0).unwrap() { 'a' | 'e' | 'i' | 'o' | 'u' | 'y' =&gt; print!(&quot;{} &quot;, format!(&quot;{}-hay&quot;, word.trim())), _ =&gt; print!(&quot;{} &quot;, format!(&quot;{}{}-ay&quot;, &amp;word[word.chars().next().unwrap().len_utf8()..].trim(), word.chars().nth(0).unwrap())), }; } println!(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-04T15:40:39.780", "Id": "481051", "Score": "1", "body": "Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>Some small remarks:</p>\n<ul>\n<li><p>according to the documentation, you want to output <code>irst-fay</code> on <code>first</code>, but your code will output <code>irstf-ay</code> instead</p>\n</li>\n<li><p>your code will only work on lower case words, but not on &quot;Apple&quot;</p>\n</li>\n<li><p>instead of <code>print!(&quot;{} &quot;, format!(...))</code> use <code>print!(...)</code></p>\n</li>\n<li><p>instead of <code>nth(0)</code> use <code>next()</code></p>\n</li>\n<li><p>I recommend you to format your code with <code>rustfmt</code></p>\n</li>\n<li><p>instead of <code>&amp;word[word.chars().next().unwrap().len_utf8()..]</code> you can use <code>c.len_utf8()</code> if you name your match instead of using <code>_</code>, e.g.</p>\n<pre><code>match word.chars().nth(0).unwrap() {\n 'a' | 'e' | 'i' | 'o' | 'u' | 'y' =&gt; print!(&quot;{}-hay &quot;, word.trim())),\n c =&gt; print!(&quot;{}-{}ay &quot;, &amp;word[c.len_utf8()..].trim(), c),\n};\n</code></pre>\n</li>\n<li><p>if you know that your index will end up at a proper UTF8 boundary you can use <code>&amp;word[1..]</code> and <code>&amp;word[..1]</code> instead of your indexing, but your variant is a lot safer. <strong>Well done here</strong>, as invalid string slicing is a common error in first Rust experiences :)</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T19:17:27.510", "Id": "480353", "Score": "0", "body": "Thank you very much ! I've updated the code on my machine and passed it trough rustfmt once again and also fixed it so it supports uppercase and lowercase :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T07:00:09.350", "Id": "480390", "Score": "0", "body": "@h4k that sounds great!. As a further exercise, write `fn piglatin(input : &str) -> String` (or a similar function) and additional tests as in [Chapter 11](https://doc.rust-lang.org/book/ch11-01-writing-tests.html). Don't worry about jumping over chapter 9 and 10, both aren't necessary to write simple tests :). The `first` and `Apple` test cases should both be covered, as well as an empty string." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T16:09:05.637", "Id": "244666", "ParentId": "244663", "Score": "6" } } ]
{ "AcceptedAnswerId": "244666", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T15:08:08.620", "Id": "244663", "Score": "7", "Tags": [ "rust" ], "Title": "Pig Latin Application in rust" }
244663
<p>I was looking over some code that I wrote years ago (that is still technically working, albeit on a very quiet production server) and I came across this segment of code.</p> <pre><code>if(isset($array2)){ foreach($array2 as $key =&gt; $value) { if((isset($value['coord'])||isset($value['bookedbefore']))&amp;&amp;!isset($value['bookedslot'])){ echo(&quot;&lt;h2&gt;Error: you ticked checkbox(es) on the booking selection setting without choosing a corresponding slot&lt;/h2&gt;&quot;); die(); } $slotcode = $value['bookedslot']; !empty($value['bookedbefore']) ? $bookedbefore = 1 : $bookedbefore=0; // not required !empty($value['coord']) ? $coord = 1 : $coord=0; // not required $valuearray = array($UserID, $slotcode, $bookedbefore, $coord); //echo(&quot;&lt;h1&gt;debug...&lt;/h1&gt;&quot;);var_dump($valuearray); try{ $sql = (&quot; INSERT INTO bookedslot(`FK_UserID`, `FK_SlotCode`, `booked_before`, `coordinator_approv`) VALUES ( :UserID, :slotcode, :bookedbefore, :coord ); ON DUPLICATE KEY UPDATE FK_UserID = :UserID, FK_SlotCode = :slotcode, booked_before = :bookedbefore, coordinator_approv = :coord &quot;); $sth = $dbh-&gt;prepare($sql); $sth-&gt;bindValue(':UserID', $valuearray[0]); $sth-&gt;bindValue(':slotcode', $valuearray[1]); $sth-&gt;bindValue(':bookedbefore', $valuearray[2]); $sth-&gt;bindValue(':coord', $valuearray[3]); $sth-&gt;execute(); $sth-&gt;closeCursor(); } catch(PDOException $e) { $message = (implode($valuearray)); echo(&quot;&lt;h3&gt;Something seems to have gone wrong with your choices.&lt;/h3&gt;&quot;); } } unset($array2); } </code></pre> <p>I am usually loath to touch things that aren't broken, but that foreach loop looks completely unjustified in my mind, or at the very least, surely it is making a large number of unnecessary calls to the database? Was I having a brainfart years ago, or now?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T12:33:55.973", "Id": "480417", "Score": "1", "body": "Just noticed that you have `);` at the end of the `VALUES` bit, not sure if the `;` should be there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T17:48:31.153", "Id": "480476", "Score": "1", "body": "@NigelRen good catch" } ]
[ { "body": "<p>There is always the temptation to revisit code after a while to tweak it to make it work <em>better</em>, the main thing is to ensure you don't break what is already there. The first thing to ensure is that you can reliably test the code which you are changing. Breaking something that appears to work (no matter how bad you think it is) will not go down well.</p>\n<p>As for the code itself, there are a few things about it.</p>\n<ol>\n<li>The prepare stuff should be done outside the loop, you should\nprepare the statement once and then execute it however many times\nare appropriate. This means you don't close the statement inside the\nloop as well.</li>\n<li>Rather than binding each value, you can pass an array of values\ninto the <code>execute()</code>, which also means you can remove some of the\ntemporary values you use.</li>\n<li>If any of the values fails validation, then you may end up with\npartial data. Records 1 and 2 may be inserted, but record 3 fails -\nBUT records 1 and 2 are already on the database.</li>\n<li>The error processing seems to be a dump some HTML and stop. This is\nprobably a general method that you have used, but I would recommend\nhaving a read around for some ideas on how to do this.\n<a href=\"https://stackoverflow.com/questions/32421702/best-practice-for-error-handling-using-pdo\">Best practice for error handling using PDO</a>\nis a more database oriented version.</li>\n</ol>\n<p>Sometimes validating all of the data prior to doing any database processes is preferable, ideally you should validate some of the common issues in the front end. As this is fairly limited in this case it may be OK to mix the validation and database stuff and use database transactions (<a href=\"https://stackoverflow.com/questions/2708237/php-mysql-transactions-examples\">PHP + MySQL transactions examples</a>).</p>\n<p>If you wanted to go the other way, you would have a small <code>foreach()</code> loop first and check each row before even preparing the statement. This is better (IMHO) when the database code is more involved.</p>\n<p>As the prepare is done outside of the loop, I've moved the scope of the <code>try...catch()</code> block.</p>\n<p>I have not addressed the error reporting as that would be something you need to look into as it's probably a site wide change.</p>\n<pre><code>if(isset($array2)){\n \n try{\n $sql =\n (&quot;\n INSERT INTO bookedslot(`FK_UserID`, `FK_SlotCode`, `booked_before`, `coordinator_approv`)\n VALUES (:UserID, :slotcode, :bookedbefore, :coord )\n ON DUPLICATE KEY UPDATE\n FK_UserID = :UserID,\n FK_SlotCode = :slotcode,\n booked_before = :bookedbefore,\n coordinator_approv = :coord\n &quot;);\n \n \n $sth = $dbh-&gt;prepare($sql);\n \n $dbh-&gt;beginTransaction();\n \n foreach($array2 as $value)\n {\n if((isset($value['coord']) || isset($value['bookedbefore'])) \n &amp;&amp; !isset($value['bookedslot'])){\n echo(&quot;&lt;h2&gt;Error: you ticked checkbox(es) on the booking selection setting without choosing a corresponding slot&lt;/h2&gt;&quot;);\n // Remove any records added so far\n $dbh-&gt;rollback();\n die();\n }\n \n $sth-&gt;execute( [ ':UserID' =&gt; $UserID, \n ':slotcode' =&gt; $value['bookedslot'],\n ':bookedbefore' =&gt; (int)!empty($value['bookedbefore']),\n ':coord' =&gt; (int)!empty($value['coord'])\n ]);\n }\n $dbh-&gt;commit();\n }\n catch(PDOException $e) {\n echo(&quot;&lt;h3&gt;Something seems to have gone wrong with your choices.&lt;/h3&gt;&quot;);\n // Remove any records added so far\n $dbh-&gt;rollback();\n \n }\n unset($array2);\n}\n</code></pre>\n<p>As a personal opinion, I have never liked the following type of construct...</p>\n<pre><code>!empty($value['bookedbefore']) ? $bookedbefore = 1 : $bookedbefore=0;\n</code></pre>\n<p>But the way it is being used makes it is easy to rework as you can just assign the result of the <code>!empty()</code> anyway...</p>\n<pre><code>$bookedbefore = !empty($value['bookedbefore']);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T12:03:52.287", "Id": "480415", "Score": "0", "body": "`REPLACE INTO`? Also, `$key` is not used. Please cast the boolean return values as int to go to the db." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T07:11:35.617", "Id": "244697", "ParentId": "244664", "Score": "2" } }, { "body": "<p>First of all, I don't see any &quot;unnecessary&quot; calls here. Do you need to insert all these lines into the database? Then all there calls are necessary.</p>\n<p>However, you can greatly optimize the process, thanks to</p>\n<h2>Two cornerstone rules for running multiple DML queries</h2>\n<ol>\n<li>prepare once execute multiple will gain you like 2-5% speed\n<ul>\n<li>(however, in order to get that small speed improvement from prepared statements, you have to <a href=\"https://phpdelusions.net/pdo#emulation\" rel=\"nofollow noreferrer\">disable the emulation mode</a>. But in this case you'll be unable to reuse the placeholder name in the same query. Luckily, there is a <code>values()</code> keyword to the rescue)</li>\n</ul>\n</li>\n<li>wrapping all DML queries in a transaction can boost the speed up to <em>70 times</em> (though depends on the software settings and hardware configuration) and is overall a sensible move. You either want all rows to be inserted or none.</li>\n</ol>\n<h2>Error reporting</h2>\n<p>Another issue to address is error reporting which is completely flawed and far from being any helpful in the real life (I have to admit, it's hard to master this skill as your code most of time works as intended) but, unlike what most people think, it's really simple to make it right.</p>\n<p>The first thing you have to realize is that there are <strong>two kinds of errors</strong> that require <strong>absolutely different treatment</strong>:</p>\n<ul>\n<li>userland errors are specific to the application logic and must be conveyed to the user</li>\n<li>PHP errors are system errors and a user has no business with them. At the same time, They are <strong>vital</strong> for the programmer and must be <strong>preserved</strong> for the future inspection. Luckily, due to their nature, system errors essentially require the <strong>uniform treatment</strong> which means you can write the handling code once, store it elsewhere, and <strong>completely remove</strong> any system error handling from your code.</li>\n</ul>\n<p>In order to separate these two kinds of errors, validate your data prior the data manipulation. First check if you have all the required data and only then run your inserts. This way you will be able to separate the user interaction errors from the system errors. Be aware that <code>die()</code> is considered a bad practice. It's better to collect all errors into a variable that have to be conveyed to the user in a more convenient fashion.</p>\n<p>Regarding the system errors, just like it was said above, write a dedicated error handler once, that would <strong>log the error</strong> for the programmer and tell the user that something went wrong. I've got a <a href=\"https://phpdelusions.net/articles/error_reporting#code\" rel=\"nofollow noreferrer\">complete working error handler example</a> in my article dedicated to PHP error reporting, you can simply take this file and include it in your script.</p>\n<h2>Reduce the nesting level</h2>\n<p>As you may noticed, your code is hard to read because it is constantly shifting to the right side. Hence it's a good idea to remove unneceessary nesting, as most of time it's a sign of the problem code. For example, it makes sense to check outside variables with <code>isset()</code> but internal variables? It's always a good idea to be positively sure whether some variable exists or not. Hence always have your variables initialized before use. Have <code>$array2</code> initialized at some point and you can drop that outermost condition. Other levels can be removed as well, such as unnecessary try-catch.</p>\n<p>Things that indeed could be considered blunders from your beginners days that look rather amusing:</p>\n<ul>\n<li>that <code>$valuearray</code></li>\n<li>the way <code>empty()</code> is used. In fact, to get 1 or 0 from a boolean value you can simply cast it as int</li>\n</ul>\n<p>So what could we have after all these improvements?</p>\n<p>First of all, separate the data validation from the query execution.</p>\n<p>Validate all the data first,</p>\n<pre><code>$errors = [];\n// perform all other validations\nforeach($array2 as $value) {\n if ((isset($value['coord']) || isset($value['bookedbefore'])) &amp;&amp; isset($value['bookedslot'])) {\n $errors[] = &quot;Error: you ticked checkbox(es) on the booking selection setting without choosing a corresponding slot&quot;;\n break;\n }\n}\n</code></pre>\n<p>and after that check for errors and if everything is OK then insert all your data, or show the form back to the user with values filled in and errors displayed</p>\n<pre><code>if (!$errors) {\n $sql = &quot;INSERT INTO bookedslot(FK_UserID, FK_SlotCode, booked_before, coordinator_approv)\n VALUES (:UserID, :slotcode, :bookedbefore, :coord )\n ON DUPLICATE KEY UPDATE\n FK_UserID = values(FK_UserID),\n FK_SlotCode = values(FK_SlotCode),\n booked_before = values(booked_before),\n coordinator_approv = values(coordinator_approv)&quot;;\n $sth = $dbh-&gt;prepare($sql);\n\n $dbh-&gt;beginTransaction();\n foreach($array2 as $value) {\n $slotcode = $value['bookedslot'];\n $bookedbefore = (int)!empty($value['bookedbefore']); // not required\n $coord = (int)!empty($value['coord']); // not required\n\n $sth-&gt;bindValue(':UserID', $UserID);\n $sth-&gt;bindValue(':slotcode', $slotcode);\n $sth-&gt;bindValue(':bookedbefore', $bookedbefore);\n $sth-&gt;bindValue(':coord', $coord);\n $sth-&gt;execute();\n }\n $dbh-&gt;commit();\n} else {\n // inform the user\n}\n</code></pre>\n<p>What's going on here?</p>\n<p>We are implementing all the things mentioned above. Just note that if your application is intended to die in case of a system error, there is no need to wrap your transaction in a try-catch block: it will be rolled back automatically by mysql as soon as the connection will be closed, and PHP always closes all its connections before die.</p>\n<p>Just don't forget to configure PDO to throw exception and to disable the emulation mode. Here I've got an example <a href=\"https://phpdelusions.net/pdo_examples/connect_to_mysql\" rel=\"nofollow noreferrer\">PDO connection code</a> that does all the necessary stuff.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T08:50:45.757", "Id": "480404", "Score": "0", "body": "Oh yes thank you. At first i intended to leave die() in place but then decided to fix that too but forgot to make it consistent. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T12:00:08.953", "Id": "480414", "Score": "0", "body": "`REPLACE INTO`? Also `$key`s are not used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T17:48:50.270", "Id": "480478", "Score": "0", "body": "@mickmackusa i am not sure about replace into" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T08:37:23.960", "Id": "244700", "ParentId": "244664", "Score": "3" } } ]
{ "AcceptedAnswerId": "244700", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T15:44:57.693", "Id": "244664", "Score": "2", "Tags": [ "php", "pdo" ], "Title": "Unnecessary loop in database population" }
244664
<p>I made my first website from scratch using HTML and CSS. It's a <a href="https://priscillacodes.github.io/" rel="nofollow noreferrer">doughnut shop</a></p> <p>I did this as a way to practice what I have learned so far from an HTML and CSS course that I am taking. I would appreciate anyone's feedback on this. I am fairly new to coding and your feedback will help continue learning and improving in these skills.</p> <pre><code>&lt;!--the home page of my website--&gt; &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt; &lt;title&gt;Master Doughnut Shop&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css&quot; integrity=&quot;sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://use.fontawesome.com/releases/v5.13.0/css/all.css&quot; integrity=&quot;sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;donutShop.css&quot;&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Architects+Daughter&amp;family=Kaushan+Script&amp;family=Staatliches&amp;display=swap&amp;family=Advent+Pro:wght@500&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;nav id=&quot;mainNav&quot; class=&quot;navbar navbar-expand-md navbar-dark fixed-top&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;&lt;i class=&quot;fas fa-compact-disc&quot;&gt;&lt;/i&gt; MASTER DOUGHNUT SHOP&lt;/a&gt; &lt;button class=&quot;navbar-toggler justify-content-end align-items-end&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#topNav&quot; aria-label=&quot;Toggle navigation&quot;&gt; &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt; &lt;/button&gt; &lt;div class=&quot;collapse navbar-collapse justify-content-end align-items-end&quot; id=&quot;topNav&quot;&gt; &lt;div class=&quot;navbar-nav&quot;&gt; &lt;a class=&quot;nav-item nav-link&quot; href=&quot;donutShop.html&quot;&gt;HOME &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/a&gt; &lt;a class=&quot;nav-item nav-link&quot; href=&quot;menu.html&quot; target=&quot;_blank&quot;&gt;MENU &lt;/a&gt; &lt;a class=&quot;nav-item nav-link&quot; href=&quot;contact.html&quot; target=&quot;_blank&quot;&gt;CONTACT US&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; &lt;div class=&quot;jumbotron px-0&quot;&gt;&lt;/div&gt; &lt;section class=&quot;container-fluid px-0&quot;&gt; &lt;div id=&quot;firstSec&quot; class=&quot;row align-items-center content&quot;&gt; &lt;div class=&quot;col-md-6 order-2 order-md-1 mt-0&quot;&gt; &lt;img src=&quot;assorted.jpg&quot; alt=&quot;various donuts&quot; class=&quot;img-fluid&quot;&gt; &lt;/div&gt; &lt;div class=&quot;col-md-6 text-center order-1 order-md-2&quot;&gt; &lt;div class=&quot;row justify-content-center&quot;&gt; &lt;div class=&quot;col-10 col-lg-8 mb-5 mt-5 mb-md-0 &quot;&gt; &lt;h2&gt;ABOUT&lt;/h2&gt; &lt;i class=&quot;fas fa-compact-disc&quot;&gt;&lt;/i&gt; &lt;p&gt;&lt;span id=&quot;welcome&quot;&gt;&lt;strong&gt;WELCOME!&lt;/strong&gt;&lt;/span&gt; Master Doughnuts is a family-owned business. We have proudly served The Colony community since 1992. We offer an assortment of donuts for all tastes, as well as other breakfast items. &lt;/p&gt; &lt;p&gt;Our main satisfaction is being able to see our guests start their day with a smile. We can't wait to meet YOU! &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;secondSec&quot; class=&quot;row align-items-center content&quot;&gt; &lt;div class=&quot;col-md-6 text-center&quot;&gt; &lt;div class=&quot;row justify-content-center&quot;&gt; &lt;div class=&quot;col-10 col-lg-8 mt-5 mb-5 mb-md-0&quot;&gt; &lt;h2&gt;LOVE IS SWEET&lt;/h2&gt; &lt;i class=&quot;fas fa-compact-disc&quot;&gt;&lt;/i&gt; &lt;p&gt;Start your day with our beautifully crafted donuts and a cup of freshly-brewed coffee. We have options for everyone to enjoy. Visit our &lt;a id=&quot;menuLink&quot; href=&quot;menu.html&quot; target=&quot;_blank&quot;&gt;&lt;strong&gt;MENU&lt;/strong&gt;&lt;/a&gt; to explore all options! &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-md-6&quot;&gt; &lt;img id=&quot;stacked&quot; src=&quot;sharingDonuts.jpg&quot; alt=&quot;various donuts&quot; width=&quot;100%&quot; height=&quot;415px&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;footer id=&quot;bottomNav&quot; class=&quot;navbar-fixed-bottom&quot;&gt; &lt;div class=&quot;container text-center&quot;&gt; &lt;h4&gt;Master Doughnut Shop&lt;/h4&gt; &lt;h6&gt;5201 South Colony Blvd, The Colony, TX 75056&lt;/h6&gt; &lt;h6&gt;(469) 362-2333&lt;/h6&gt; &lt;/div&gt; &lt;/footer&gt; &lt;!-- Optional JavaScript --&gt; &lt;!-- jQuery first, then Popper.js, then Bootstrap JS --&gt; &lt;script src=&quot;https://code.jquery.com/jquery-3.3.1.slim.min.js&quot; integrity=&quot;sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js&quot; integrity=&quot;sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js&quot; integrity=&quot;sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://kit.fontawesome.com/f1298564b2.js&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script&gt; $(function () { $(document).scroll(function () { var $nav = $(&quot;topNav&quot;); $nav.toggleClass(&quot;scrolled&quot;, $(this).scrollTop() &gt; $nav.height()); }) }) &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; &lt;!--the menu page of my website--&gt; &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Menu&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css&quot; integrity=&quot;sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://use.fontawesome.com/releases/v5.13.0/css/all.css&quot; integrity=&quot;sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;donutShop.css&quot;&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Architects+Daughter&amp;family=Kaushan+Script&amp;family=Staatliches&amp;display=swap&amp;family=Advent+Pro:wght@500&amp;display=swap&amp;family=Rajdhani:wght@500&amp;display=swap&amp;family=Cantarell:ital@1&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;nav id=&quot;mainNav&quot; class=&quot;navbar navbar-expand-md navbar-dark fixed-top&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;&lt;i class=&quot;fas fa-compact-disc&quot;&gt;&lt;/i&gt; MENU&lt;/a&gt; &lt;button class=&quot;navbar-toggler justify-content-end align-items-end&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#topNav&quot; aria-label=&quot;Toggle navigation&quot;&gt; &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt; &lt;/button&gt; &lt;div class=&quot;collapse navbar-collapse justify-content-end align-items-end&quot; id=&quot;topNav&quot;&gt; &lt;div class=&quot;navbar-nav&quot;&gt; &lt;a class=&quot;nav-item nav-link&quot; href=&quot;donutShop.html&quot;&gt;HOME &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/a&gt; &lt;a class=&quot;nav-item nav-link&quot; href=&quot;menu.html&quot;&gt;MENU &lt;/a&gt; &lt;a class=&quot;nav-item nav-link&quot; href=&quot;contact.html&quot; target=&quot;_blank&quot;&gt;CONTACT US&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; &lt;h2 id=&quot;classics&quot; class=&quot;text-center&quot;&gt;CLASSICS&lt;/h2&gt; &lt;div class=&quot;container d-flex justify-content-center&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;glazedDonut.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;donut picture&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;GLAZED&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;chocolateDonut.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;donut picture&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;CHOCOLATE ICED&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;strawberryDonut.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;donut picture&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;STRAWBERRY ICED&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container d-flex justify-content-center&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;mapleDonut.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;donut picture&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;MAPLE ICED&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;powderedSugar.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;donut picture&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;POWDERED SUGAR&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;cinnamonDonut.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;donut picture&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;CINNAMON SUGAR&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;h2 id=&quot;favorites&quot; class=&quot;text-center&quot;&gt;BREAKFAST FAVORITES&lt;/h2&gt; &lt;div class=&quot;container d-flex justify-content-center&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;croissant.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;croissant&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;CROISSANT&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;miniDonuts.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;mini donuts&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;MINI DONUTS&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;sprinkles.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;donuts with sprinkes&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;DONUTS WITH SPRINKLES&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;container d-flex justify-content-center&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;donutHoles.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;donut picture&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;DONUT HOLES&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;pigsinablanket.jpg&quot; height=190px class=&quot;card-img-top&quot; alt=&quot;pigs-in-a-blanket&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;PIGS-IN-A-BLANKET&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;birthdayDonut.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;birthday donut&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;BIRTHDAY DONUTS&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;h2 id=&quot;bev&quot; class=&quot;text-center&quot;&gt;BEVERAGES&lt;/h2&gt; &lt;div id=&quot;beverages&quot; class=&quot;container d-flex justify-content-center&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;coffee.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;coffee&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;COFFEE&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;orangeJuice.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;orange juice&quot; height=&quot;190px&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;ORANGE JUICE&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;col-lg-4 mb-3&quot;&gt; &lt;div class=&quot;card&quot; style=&quot;width: 18rem&quot;&gt; &lt;img src=&quot;milk.jpg&quot; class=&quot;card-img-top&quot; alt=&quot;milk&quot;&gt; &lt;div class=&quot;card-body&quot;&gt; &lt;h5 class=&quot;card-title text-center&quot;&gt;MILK&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;footer id=&quot;bottomNav&quot; class=&quot;navbar-fixed-bottom&quot;&gt; &lt;div class=&quot;container text-center&quot;&gt; &lt;h4&gt;Master Doughnut Shop&lt;/h4&gt; &lt;h6&gt;5201 South Colony Blvd, The Colony, TX 75056&lt;/h6&gt; &lt;h6&gt;(469) 362-2333&lt;/h6&gt; &lt;/div&gt; &lt;/footer&gt; &lt;!-- Optional JavaScript --&gt; &lt;!-- jQuery first, then Popper.js, then Bootstrap JS --&gt; &lt;script src=&quot;https://code.jquery.com/jquery-3.3.1.slim.min.js&quot; integrity=&quot;sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js&quot; integrity=&quot;sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js&quot; integrity=&quot;sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://kit.fontawesome.com/f1298564b2.js&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; &lt;!--the contact page of my website--&gt; &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Contact Us&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css&quot; integrity=&quot;sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;https://use.fontawesome.com/releases/v5.13.0/css/all.css&quot; integrity=&quot;sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV+i/6YWSzkz3V&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;donutShop.css&quot;&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Architects+Daughter&amp;family=Kaushan+Script&amp;family=Staatliches&amp;display=swap&amp;family=Advent+Pro:wght@500&amp;display=swap&amp;family=Rajdhani:wght@500&amp;display=swap&amp;family=Cantarell:ital@1&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; &lt;/head&gt; &lt;body id=&quot;contact&quot;&gt; &lt;nav id=&quot;mainNav&quot; class=&quot;navbar navbar-expand-md navbar-dark fixed-top&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;&lt;i class=&quot;fas fa-compact-disc&quot;&gt;&lt;/i&gt; CONTACT US&lt;/a&gt; &lt;button class=&quot;navbar-toggler justify-content-end align-items-end&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#topNav&quot; aria-label=&quot;Toggle navigation&quot;&gt; &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt; &lt;/button&gt; &lt;div class=&quot;collapse navbar-collapse justify-content-end align-items-end&quot; id=&quot;topNav&quot;&gt; &lt;div class=&quot;navbar-nav&quot;&gt; &lt;a class=&quot;nav-item nav-link&quot; href=&quot;donutShop.html&quot;&gt;HOME &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/a&gt; &lt;a class=&quot;nav-item nav-link&quot; href=&quot;menu.html&quot; target=&quot;_blank&quot;&gt;MENU &lt;/a&gt; &lt;a class=&quot;nav-item nav-link&quot; href=&quot;contact.html&quot;&gt;CONTACT US&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; &lt;form id=&quot;form&quot; class=&quot;container&quot;&gt; &lt;div class=&quot;form-row&quot;&gt; &lt;div class=&quot;form-group col-md-6&quot;&gt; &lt;label for=&quot;inputFirstName&quot;&gt;First Name&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;inputFirstName&quot; placeholder=&quot;First Name&quot;&gt; &lt;/div&gt; &lt;div class=&quot;form-group col-md-6&quot;&gt; &lt;label for=&quot;inputLastName&quot;&gt;Last Name&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;inputLastName&quot; placeholder=&quot;Last Name&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;form-row&quot;&gt; &lt;div class=&quot;form-group col-md-6&quot;&gt; &lt;label for=&quot;inputEmail4&quot;&gt;Email&lt;/label&gt; &lt;input type=&quot;email&quot; class=&quot;form-control&quot; id=&quot;inputEmail&quot; placeholder=&quot;example@email.com&quot;&gt; &lt;/div&gt; &lt;div class=&quot;form-group col-md-6&quot;&gt; &lt;label for=&quot;inputPhone&quot;&gt;Phone Number&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;inputPhone&quot; placeholder=&quot;123-456-7891&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;label for=&quot;exampleFormControlTextarea1&quot;&gt;Comments and Questions&lt;/label&gt; &lt;textarea class=&quot;form-control&quot; id=&quot;exampleFormControlTextarea1&quot; rows=&quot;3&quot;&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;button id=&quot;submit&quot; type=&quot;submit&quot; class=&quot;btn&quot;&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; /*Stylesheet for Master Doughnut Shop project*/ body{ background-color: rgba(247, 187, 196, 0.945); } body p{ font-family: 'Architects Daughter', cursive; } .jumbotron { background: url('patrick-fore-NnTQBkBkU9g-unsplash.jpg') no-repeat center center; background-size: cover; height: 615px; width: 100%; margin-bottom: 0px; } #topNav .nav-link{ color: white; font-size: 1.5rem; font-family: 'Staatliches', cursive; } #mainNav .navbar-brand{ color: white; font-size: 2.1rem; font-family: 'Kaushan Script', cursive; font-weight: 900; } #mainNav .fas{ color: #ea1c2c; } #topNav .nav-link:hover{ color: #ea1c2c; } .navbar .scrolled{ background: transparent; transition: bacground 200ms; } @media (max-width: 1200px){ #mainNav .navbar-toggler{ float: right; } } #firstSec{ padding-top: 0%; margin-top: 0px; } #firstSec h2{ font-family: 'Kaushan Script', cursive; } #firstSec i{ font-size: 30px; color: white; padding-top: 5px; padding-bottom: 10px; } #firstSec p{ font-size: 1.25rem; } #secondSec{ padding-top: 0%; margin-top: 0px; } #secondSec h2{ font-family: 'Kaushan Script', cursive; } #secondSec i{ font-size: 30px; color: white; padding-top: 5px; padding-bottom: 10px; } #secondSec p{ font-size: 1.25rem; } .content{ margin-top: 75px; } #stacked .img-fluid{ max-height: 10px; } #welcome{ color: #ea1c2c; } #menuLink{ color: #ea1c2c; } #bottomNav{ background-color: plum; height: 98px; margin-bottom: 0px; padding-bottom: 0px; } #bottomNav h4{ font-family: 'Kaushan Script', cursive; color: white; padding-top: 10px; } #bottomNav h6{ font-family: 'Advent Pro', sans-serif; color: white; font-size: 15px; } h1{ padding-top: 5%; padding-bottom: 3px; font-family: 'Kaushan Script', cursive; } #classics{ padding-top: 5%; padding-bottom: 2%; font-family: 'Cantarell', sans-serif; font-size: 2.75rem; color: #ea1c2c; } #favorites{ padding-top: 2%; padding-bottom: 2%; font-family: 'Cantarell', sans-serif; font-size: 2.75rem; color: #ea1c2c; } #bev{ padding-top: 2%; padding-bottom: 2%; font-family: 'Cantarell', sans-serif; font-size: 2.75rem; color: #ea1c2c; } #beverages{ padding-bottom: 2%; } .card h5{ font-family: 'Architects Daughter', cursive; font-weight: 400; } .card .card-body{ background-color: plum; } .card{ border-color: plum; } #form{ padding-top: 6%; max-width: 1000px; } #contact{ background: url(pink.jpg) no-repeat; background-position: center; } #submit{ color: white; background-color: #ea1c2c; margin-top: 10px; } label{ color: #ea1c2c; font-family: 'Advent Pro', sans-serif; font-weight: 500; font-size: 1.1rem; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T17:35:33.343", "Id": "480345", "Score": "0", "body": "Yes, when I open the site on Chrome my image in the jumbotron covers the entire width and height. However, when I open it on Firefox the image doesn't cover the entire height. You can slightly see a little bit of the About section begin to show up." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T17:41:58.520", "Id": "480347", "Score": "0", "body": "Oh, you meant responsiveness in that way. I would probably have been able to help with the other meaning, however not with this one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T17:42:56.387", "Id": "480348", "Score": "0", "body": "I also notice the images are slow to load especially in the Menu page. Any recommendations for improving that?" } ]
[ { "body": "<p>First off, I'm not a big fan of Bootstrap. It bloats the HTML with additional elements and classes. Also as a beginner it stops you from learning standard CSS.</p>\n<p>Avoid using IDs to apply styles. IDs have a high <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity\" rel=\"nofollow noreferrer\">specificity</a> making organizing the style sheet more difficult. Use classes instead.</p>\n<p>Don't write text in ALL CAPS. Use normal English capitalization and change the display with <code>text-transform: uppercase</code> in the style sheet. This helps screen readers understand and pronounce the text better, for example, by able to distinguish between words and abbreviations (e.g. &quot;us&quot; vs &quot;U.S.&quot;).</p>\n<p>The proper elements for what they are meant for. H4 and H6 are for headlines, not for addresses. The <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/address\" rel=\"nofollow noreferrer\"><code>address</code></a> element would be more appropriate.</p>\n<p>Don't open links (especially &quot;normal&quot; ones inside the site) in new windows/tabs with <code>target=&quot;_blank&quot;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T14:14:57.660", "Id": "480595", "Score": "0", "body": "Thank you for your feedback RoToRa, this is very helpful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T09:13:32.103", "Id": "244702", "ParentId": "244670", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T16:59:37.113", "Id": "244670", "Score": "3", "Tags": [ "html", "css", "html5", "twitter-bootstrap" ], "Title": "Master Doughnut Shop Website" }
244670
<p>Hello am a new to Python and my programming concept is catching up to me. I just created my first ever project. I did not look else where for an answer, and it took me 6 hours to write.</p> <p>How can I improve this code? Is their a way to use for loop to check the if player1 beats player2. Please don't recomend using functions.</p> <pre><code>choice = ['r', 'p', 's'] player = ['1', '2'] user_Ply = [] ply_round = 0 draw = 0 print(&quot;--------------------------------------------------------------------&quot;) print(r&quot;&quot;&quot;THIS IS A GAME OF ROCK, PAPER AND SICSSORS TO PLAY EITHER ENTER R FOR &quot;ROCK&quot; P FOR &quot;PAPER&quot; AND &quot;S&quot; FOR SCISSORS &quot;&quot;&quot;) while True: ply_round += 1 win = '' active_player = player[0] isPlayer1_TheActive_Player = True if isPlayer1_TheActive_Player: for i, players in enumerate(player): if active_player == player[i]: print('------------------------------------------') print('Player One it your Turn') ply_1 = input('Enter &quot;Rock&quot;,&quot;Paper&quot;,&quot;Scissors :&quot; ') user_Ply.append(ply_1) for j, v in enumerate(choice): if choice[j] in ply_1: print(f'you choose {choice[j]}') else: print('------------------------------------------') print('Player Two it your Turn') ply_2 = input('Enter &quot;Rock&quot;,&quot;Paper&quot;,&quot;Scissors :&quot; ') user_Ply.append(ply_2) for j, v in enumerate(choice): if choice[j] in ply_2: print(f'you choose {choice[j]}') isPlayer1_TheActive_Player = False if ((user_Ply[0] == choice[-1] and user_Ply[1] == choice[-1]) or (user_Ply[0] == choice[1] and user_Ply[1] == choice[1]) or (user_Ply[0] == choice[0] and user_Ply[1] == choice[0])): print(fr'The result of round {ply_round} is a draw') draw += 1 user_Ply.clear() elif (user_Ply[0] == choice[0] and user_Ply[1] == choice[-1]): print(fr'The result of round {ply_round} is a win for P1') user_Ply.clear() elif (user_Ply[1] == choice[0] and user_Ply[0] == choice[-1]): print(fr'The result of round {ply_round} is a win for P2') user_Ply.clear() elif (user_Ply[0] == choice[-1] and user_Ply[0] == choice[1]): print(fr'The result of round {ply_round} is a win for P1') user_Ply.clear() elif (user_Ply[1] == choice[1] and user_Ply[0] == choice[-1]): print(fr'The result of round {ply_round} is a win for P2') user_Ply.clear() elif (user_Ply[0] == choice[1] and user_Ply[0] == choice[0]): print(fr'The result of round {ply_round} is a win for P1') user_Ply.clear() elif (user_Ply[1] == choice[0] and user_Ply[0] == choice[1]): print(fr'The result of round {ply_round} is a win for P2') user_Ply.clear() else: user_Ply.clear() if ply_round == 5: break print('------------------------------') print('Game over') print() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T23:23:26.813", "Id": "480369", "Score": "3", "body": "This will not run. Please examine your indentation." } ]
[ { "body": "<p>There is a lot of room for improvement in your code.</p>\n<p>First, I'd like to address an unusual request you made:</p>\n<blockquote>\n<p>Please don't recomend using functions.</p>\n</blockquote>\n<p>Why not? They are a fundamental notion in programming, and can't really be avoided. Glossing over the fact that you already use a bunch of functions like <code>print</code>, <code>input</code>, <code>append</code>, etc., and assuming you are referring to functions that you define yourself in the code, it is still a puzzling request. Functions can make your code cleaner, easier to read, easier to maintain and more reusable, so why would you want to avoid them?</p>\n<p>Take for example the part of the code where you ask for user input: the same code is copied and pasted twice. There are improvements to be made to that snippet. Implementing <em>one</em> these improvements would mean changing the code in <em>two</em> places. If it were encapsulated in a function, you would need to make that change only once, reducing the risk for errors.</p>\n<p>Also, when reviewing your code, or when re-reading it yourself for further reference, encountering a properly named function is likely to be easier to process than what would effectively be the body of the function. I could see something like <code>ask_for_input(player1)</code> and focus on how the game move in handled, and then check out how you approach asking the user for input, independently from the previous logic. You could potentially reuse your <code>ask_for_input</code> function as is in future projects. Finally, you could then trivially replace the <code>ask_for_input</code> function with some sort of computer player if you want to expand this program.</p>\n<hr />\n<p>As for the rest of the code, I won't provide a functional code, as there are already <a href=\"https://codereview.stackexchange.com/questions/tagged/rock-paper-scissors+python\">a lot of reviews on the site</a> for &quot;rock-paper-scissors&quot; programs in Python. I'm sure you can find good, clean code that fits the bill.</p>\n<p>However, I'll address a few design choices you made that can be improved upon, in no particular order.</p>\n<h2>Naming conventions</h2>\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 Style Guide for Python Code</a> recommends naming variables in lowercase <code>snake_case</code>, and constants in <code>ALL_CAPS</code>. Your variables and constants names are a mix of <code>snake_case</code> and <code>CamelCase</code>. While you may chose not to adhere to PEP 8 (although it's good practice to keep your code consistent with what is expected), at least pick a convention and stick with it.</p>\n<p>PEP 8 is also a comprehensive style guide, and include cases that you may not even have thought about (like using a different style for constants, making the identifiable at first glance), so it is at the very least an interesting read.</p>\n<h2>Main loop</h2>\n<p>Most of your logic is enclosed in a <code>while</code> loop:</p>\n<pre><code>while True:\n ply_round += 1\n # ...\n if ply_round == 5:\n break\n</code></pre>\n<p>A <code>while</code> loop is clearly not the best fit here, as you effectively iterate over an incrementing index. A <code>for</code> loop would be functionally the same, while eliminating some overhead:</p>\n<pre><code>for ply_round in range(1, 6):\n # ...\n</code></pre>\n<p>Or better yet, use a named constant or a variable to specify how many rounds are played, so that you can see at first glance what the number means.</p>\n<h2><code>enumerate</code></h2>\n<p>You use <code>enumerate</code> a lot in your <code>for</code> loops. <code>enumerate</code> returns a tuple of <code>(index, value)</code>, and you usually just use one of them. Instead of using enumerate, use <code>for item in list</code> if you only need the item, or <code>for i in range(len(list))</code> if you only need the index.</p>\n<p>Some times (although it is not your case here), you can't avoid using a throwaway variable. It is common practice to use <code>_</code> in these cases, clearly showing that you don't need that variable.</p>\n<h2>Sanitizing inputs</h2>\n<p>When getting user input, you should check if the inputted value matches what the program expects. In your case, the program expects on of the values <code>r</code>, <code>p</code>, or <code>s</code>. If the user enters anything else, the program continues on and gives no output, while still incrementing the round counter.</p>\n<p>This is made even worse because the prompts first ask for <code>R</code>, <code>P</code> or <code>S</code>, then for <code>Rock</code>, <code>Paper</code> or <code>Scissors</code>. The user has no way to know what the expected input is.</p>\n<p>At the very least, you should change the prompts to ask for the correct value, and use <code>.lower()</code> on the inputs, so that the case doesn't matter. Then, if the value isn't what is expected, discard the value and ask again, instead of silently accepting wrong inputs.</p>\n<p>At this point, you should <em>really</em> put the input code into a function, or else your program will get absolutely unreadable.</p>\n<h2>Backwards logic</h2>\n<p>Consider this piece of code:</p>\n<pre><code>for j, v in enumerate(choice):\n if choice[j] in ply_1:\n print(f'you choose {choice[j]}')\n</code></pre>\n<p>Ignoring the <code>enumerate</code> issue addressed earlier, what happens here is:</p>\n<ol>\n<li>you loop over accepted inputs</li>\n<li>check if the accepted input is in the actual input (which should be 1 character long)</li>\n</ol>\n<p>It makes much more sense to do this the other way (check if the actual input is in the accepted range), and it's simpler too:</p>\n<pre><code>if ply_1 in choice:\n # do something\n</code></pre>\n<h2>Winner determining logic</h2>\n<p>To determine which player wins, you basically check every possible case individually. That is a lot of code for a rather simple task. In fact, is is about on fourth of your code, and you only handle the most basic case of 2 players and 3 weapons. What if you wanted to improve your game to allow for more players or more weapons (think &quot;rock-paper-scissors-lizard-spock&quot;)? Then it would become absurdly long.</p>\n<p>Possible solutions can include a lookup table, a dictionary associating each weapon to the weapon it beats, implementing a <code>Weapon</code> class with comparison operators, or maybe other things.</p>\n<p>At the very least, you can check for ties with <code>if user_Ply[0] == user_Ply[1]</code> instead of comparing both to multiple common values.</p>\n<h2>Using a list instead of multiple variables</h2>\n<p>I feel like two variables, named for example <code>player_1_move</code> and <code>player_2_move</code>, would be more readable and more suited than putting them both in a list.</p>\n<h2>Anti-cheat measures</h2>\n<p>Player 2 can see what move player 1 made, making it trivial for him to win every round.</p>\n<p>I'm aware that this is a programming exercise and no-one wants to actually play rock-paper-scissors on a terminal, but clearing the console would simply make sense to me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T14:06:45.617", "Id": "244712", "ParentId": "244671", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T17:11:39.923", "Id": "244671", "Score": "1", "Tags": [ "python", "beginner", "game", "rock-paper-scissors" ], "Title": "Rock paper scissor game in Python" }
244671
<p>I have implemented a Tic-Tac-Toe game in C which can be played as two-player or with a computer player.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdint.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdlib.h&gt; #include &lt;ctype.h&gt; #define NPLY 10 /* board is represented using two bitfields */ const int wins[] = { 0007, 0070, 0700, 0111, 0222, 0444, 0421, 0124 }; int bestm[NPLY]; void show_board(int x, int y); char next_player(char d) { return (d == 'x') ? 'o' : 'x'; } /* determine if there are three in a row */ int is_win(int n) { for (size_t i = 0; i &lt; sizeof(wins) / sizeof(int); i++) { if ((n &amp; wins[i]) == wins[i]) return true; } return false; } /* determine best move using recursive search */ int negamax(int d, int x, int o, int ply) { int bestmove; int value = -999, cur; int xx, oo; if (is_win(x)) return (d == 'x') ? 1 : -1; else if (is_win(o)) return (d == 'o') ? 1 : -1; else if ((x | o) == 0777) /* all squares filled, draw */ return 0; for (int i = 0; i &lt; 9; i++) { xx = x; oo = o; if ((x | o) &amp; (1 &lt;&lt; i)) continue; if (d == 'x') /* make move */ xx |= (1 &lt;&lt; i); else oo |= (1 &lt;&lt; i); cur = -negamax(next_player(d), xx, oo, ply - 1); if (cur &gt; value) { value = cur; bestmove = i; } } bestm[ply] = bestmove; return value; } void show_board(int x, int o) { puts(&quot;+---+---+---+&quot;); for (int i = 0; i &lt; 3; i++) { putchar('|'); for (int j = 0; j &lt; 3; j++) { char c; if (x &amp; (1 &lt;&lt; (3 * i + j))) c = 'X'; else if (o &amp; (1 &lt;&lt; (3 * i + j))) c = 'O'; else c = '0' + 3 * i + j; printf(&quot; %c |&quot;, c); } puts(&quot;\n+---+---+---+&quot;); } } int main() { int x = 0, o = 0; char c, d = 'x'; char ai; bool over = false; int move; char s[100]; printf(&quot;Enter AI player x/o or 2 for two player: &quot;); ai = tolower(getchar()); while ((c = getchar()) != '\n'); while (!over) { if (d == ai) { negamax(d, x, o, NPLY - 1); move = bestm[NPLY - 1]; } else { show_board(x, o); printf(&quot;Player %c, make your move: &quot;, d); fflush(stdout); fgets(s, sizeof(s), stdin); /* read a line */ move = atoi(s); if (!(0 &lt;= move &amp;&amp; move &lt; 9)) { puts(&quot;Invalid move.&quot;); continue; } if ((x &amp; (1 &lt;&lt; move)) || (o &amp; (1 &lt;&lt; move))) { puts(&quot;Square occupied; try again.&quot;); continue; } } if (d == 'x') { x |= (1 &lt;&lt; move); } else { o |= (1 &lt;&lt; move); } d = next_player(d); if (is_win(x)) { show_board(x, o); puts(&quot;X wins&quot;); over = true; } else if (is_win(o)) { show_board(x, o); puts(&quot;O wins&quot;); over = true; } else if ((x | o) == 0777) { puts(&quot;Draw&quot;); over = true; } } } </code></pre> <p>What points could be improved? What would you have done differently and why?</p>
[]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Fix your formatting</h2>\n<p>There are inconsistent spaces at the beginning of lines, inconsistent indentation and inconsistent use and placement of curly braces <code>{}</code>. Being consistent helps others read and understand your code.</p>\n<h2>Use longer, more meaningful names</h2>\n<p>Names like <code>c</code> and <code>d</code> are not very descriptive and leave readers of the code little clue as to their significance to the program.</p>\n<h2>Eliminate global variables</h2>\n<p>The global variables <code>wins</code> and <code>bestm</code> don't need to be global. Eliminating them allows your code to be more readable and maintainable, both of which are important characteristics of well-written code. Global variables introduce messy linkages that are difficult to spot and error prone. For this program, <code>wins</code> can be a <code>static const</code> variable defined within <code>is_win</code>. The <code>bestm</code> array could also be static to <code>negamax</code> and the move could be an additional parameter like this:</p>\n<pre><code>int negamax(int current_player, int x, int o, int ply, int* best) {\n // mostly same\n *best = bestm[ply] = bestmove\n return value;\n}\n</code></pre>\n<p>The call from <code>main</code> would then be:</p>\n<pre><code>negamax(current_player, x, o, NPLY - 1, &amp;move);\n</code></pre>\n<h2>Simplify expressions</h2>\n<p>The code includes these lines:</p>\n<pre><code>if ((x &amp; (1 &lt;&lt; move)) || (o &amp; (1 &lt;&lt; move))) {\n puts(&quot;Square occupied; try again.&quot;);\n continue;\n}\n</code></pre>\n<p>This could be somewhat simpler as</p>\n<pre><code>if ((x|o) &amp; (1 &lt;&lt; move)) {\n</code></pre>\n<p>Similarly, <code>show_board</code> could be rewritten as:</p>\n<pre><code>void show_board(int x, int o)\n{\n int mask = 1;\n int col = 0;\n for (int i = '0'; i &lt; '9'; ++i, mask &lt;&lt;= 1) {\n if (col == 0) {\n printf(&quot;\\n+---+---+---+\\n|&quot;);\n col = 3;\n }\n char c;\n if (x &amp; mask) {\n c = 'X';\n } else if (o &amp; mask) {\n c = 'O';\n } else {\n c = i;\n }\n printf(&quot; %c |&quot;, c);\n --col;\n }\n puts(&quot;\\n+---+---+---+&quot;);\n}\n</code></pre>\n<h2>Simplify win checking</h2>\n<p>The game currently checks if either player won after every move, but this isn't really necessary. By definition, only the player who just moved can win the game. This same strategy can be used within the <code>negamax</code> routine.</p>\n<h2>Create more helper functions</h2>\n<p>I'd suggest that the <code>main</code> routine could be made a little more clear if some helper functions were defined and used, such as checking for a tie or checking if a slot is occupied. These would allow the logic of the game to be clear while hiding implementation details.</p>\n<h2>Consider a different data structure</h2>\n<p>Right now there are a number of places in the code where we have something like this:</p>\n<pre><code>if (d == 'x') {\n x |= (1 &lt;&lt; move);\n} else {\n o |= (1 &lt;&lt; move);\n}\n</code></pre>\n<p>If we rename <code>d</code> to <code>current_player</code> and have it point to either <code>x</code> or <code>o</code>, we could write this:</p>\n<pre><code>*current_player |= (1 &lt;&lt; move);\n</code></pre>\n<p>By creating a structure like this:</p>\n<pre><code>struct {\n char token;\n int board;\n} players[2] = {\n {'x', 0},\n {'o', 0},\n};\n</code></pre>\n<p>We could simplify even further.</p>\n<h2>Use only required <code>#include</code>s</h2>\n<p>The code currently has an <code>#include</code> that is not needed. Nothing is used from <code>&lt;stdint.h&gt;</code>. Only include files that are actually needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T02:18:16.767", "Id": "480378", "Score": "0", "body": "Re: Formatting and includes. Let automatic tool handle that. Not efficient use of programmer's time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T23:06:37.787", "Id": "244685", "ParentId": "244672", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T18:24:43.803", "Id": "244672", "Score": "3", "Tags": [ "c", "tic-tac-toe" ], "Title": "Tic-Tac-Toe in C" }
244672
<p>I'm trying to find a way to know if a number on a matrix is positive, negative or zero. Below is my code, but I'm wondering if there is a more Pythonic way to write that. Any ideas?</p> <pre><code>array = np.random.randint(-10,10, size=(10,10)) def function(array): case1 = np.where(array &lt; 0, -1, array) case2 = np.where(case1 &gt; 0, 1, case1) case3 = np.where(case2 == 0, 0, case2) return case3 print(function(array)) </code></pre>
[]
[ { "body": "<p>You should choose better functions names, <code>function</code> does not give any indication what the purpose of the function is.</p>\n<p>In addition, a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">docstring comment</a> can be used to give a short description.</p>\n<p>But actually there is no need for a custom function because <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.sign.html\" rel=\"noreferrer\"><code>numpy.sign</code></a> already provides the exact functionality:</p>\n<blockquote>\n<p>Returns an element-wise indication of the sign of a number.</p>\n</blockquote>\n<p>Example:</p>\n<pre><code>import numpy as np\n\narray = np.random.randint(-10,10, size=(4,4))\nprint(np.sign(array))\n</code></pre>\n<p>Output:</p>\n<pre>\n[[-1 1 1 1]\n [ 1 1 0 0]\n [ 1 1 -1 1]\n [ 1 -1 1 -1]]\n</pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T21:15:42.553", "Id": "480356", "Score": "0", "body": "Yes, that's it! Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T19:31:05.357", "Id": "244677", "ParentId": "244673", "Score": "5" } } ]
{ "AcceptedAnswerId": "244677", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T19:07:35.890", "Id": "244673", "Score": "2", "Tags": [ "python", "matrix" ], "Title": "Positive, Negative or zero in a 2D array python" }
244673
<p>So I'm working through a beginners C++ book and they had this example demonstrating class hierarchy, which was originally in a single file. I tried recreating it with multiple files (header files + source files) to test my understanding, but I wanted to make sure that I did everything in the &quot;optimal&quot; way. Specifically, I had to use more <code>#include</code>s than I thought I would need to, so I'm wondering if I can make improvements there. Here is what the project looks like:</p> <p><strong>main.cpp</strong></p> <pre><code>#include &quot;FDeepDishPizza.h&quot; #include &lt;iostream&gt; using std::cout, std::endl; int main() { cout &lt;&lt; &quot;Hello world!&quot; &lt;&lt; endl; FDeepDishPizza deepPizza(12, 13, 14, 15); deepPizza.DumpDensity(); return 0; } </code></pre> <hr /> <p><strong>FrozenFood.h</strong></p> <pre><code>#ifndef FROZENFOOD_H_INCLUDED #define FROZENFOOD_H_INCLUDED class FrozenFood { private: int Price; protected: int Weight; public: FrozenFood(int APrice, int AWeight); int GetPrice(); int GetWeight(); }; #endif // FROZENFOOD_H_INCLUDED </code></pre> <p><strong>FrozenFood.cpp</strong></p> <pre><code>#include &quot;FrozenFood.h&quot; #include &lt;iostream&gt; using std::cout, std::endl; FrozenFood::FrozenFood(int APrice, int AWeight) { Price = APrice; Weight = AWeight; } int FrozenFood::GetPrice() { cout &lt;&lt; Price &lt;&lt; endl; } int FrozenFood::GetWeight() { cout &lt;&lt; Weight &lt;&lt; endl; } </code></pre> <hr /> <p><strong>FrozenPizza.h</strong></p> <pre><code>#ifndef FROZENPIZZA_H_INCLUDED #define FROZENPIZZA_H_INCLUDED #include &quot;FrozenFood.h&quot; class FrozenPizza : public FrozenFood { protected: int Diameter; public: FrozenPizza(int APrice, int AWeight, int ADiameter); void DumpInfo(); }; #endif // FROZENPIZZA_H_INCLUDED </code></pre> <p><strong>FrozenPizza.cpp</strong></p> <pre><code>#include &quot;FrozenPizza.h&quot; #include &lt;iostream&gt; using std::cout, std::endl; FrozenPizza::FrozenPizza(int APrice, int AWeight, int ADiameter) : FrozenFood(APrice, AWeight) { Diameter = ADiameter; } void FrozenPizza::DumpInfo() { cout &lt;&lt; &quot;\tFrozen Pizza Info:&quot; &lt;&lt; endl; cout &lt;&lt; &quot;\t\tWeight: &quot; &lt;&lt; Weight &lt;&lt; &quot; ounces&quot; &lt;&lt; endl; cout &lt;&lt; &quot;\t\tDiameter: &quot; &lt;&lt; Diameter &lt;&lt; &quot; inches&quot; &lt;&lt; endl; } </code></pre> <hr /> <p><strong>FDeepDishPizza.h</strong></p> <pre><code>#ifndef FDEEPDISHPIZZA_H_INCLUDED #define FDEEPDISHPIZZA_H_INCLUDED #include &quot;FrozenPizza.h&quot; class FDeepDishPizza : public FrozenPizza { //public inherit from FrozenPizza, which itself inherits FrozenFood private: int Height; public: FDeepDishPizza(int APrice, int AWeight, int ADiameter, int AHeight); void DumpDensity(); }; #endif // FDEEPDISHPIZZA_H_INCLUDED </code></pre> <p><strong>FDeepDishPizza.cpp</strong></p> <pre><code>#include &quot;FDeepDishPizza.h&quot; #include &lt;iostream&gt; using std::cout, std::endl; FDeepDishPizza::FDeepDishPizza(int APrice, int AWeight, int ADiameter, int AHeight) : FrozenPizza(APrice, AWeight, ADiameter) { Height = AHeight; } void FDeepDishPizza::DumpDensity() { cout &lt;&lt; &quot;\tDensity: &quot;; cout &lt;&lt; Weight * 2 &lt;&lt; &quot; pounds per cubic foot&quot; &lt;&lt; endl; //doesn't actually give density just a test } </code></pre>
[]
[ { "body": "<h1>Don't use <code>std::endl</code></h1>\n<p>Use <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\"><code>&quot;\\n&quot;</code> instead of <code>std::endl</code></a>. The latter is equivalent to <code>&quot;\\n&quot;</code>, but also forces a flush of the output stream, which can be bad for performance.</p>\n<h1>Don't confuse getting a value with printing a value</h1>\n<p>You have functions like <code>int GetPrice()</code>, that look like they return the price as an <code>int</code>. However, in your implementation, you actually print the price to the screen, and return nothing. Either don't print and return the price, or rename the function <code>void PrintPrice()</code> and return nothing.</p>\n<p>It's usually better to just return the value instead of printing them. The caller can then decide if they want to print the value, and if so how.</p>\n<h1>Consider adding <code>operator&lt;&lt;</code> overloads for printing</h1>\n<p>It's always best to make classes behave like standard types. When printing something, wouldn't it be nice if you could write the following?</p>\n<pre><code>FrozenPizza fp(1, 2, 3);\nstd::cout &lt;&lt; fp;\n</code></pre>\n<p>You can if you create a <code>friend operator&lt;&lt;()</code>, like so:</p>\n<pre><code>class FrozenPizza: public FrozenFood {\n ...\n public:\n friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const FrozenPizza &amp;fp);\n};\n\nstd::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const FrozenPizza &amp;fp) {\n os &lt;&lt; &quot;\\tFrozen Pizza Info:\\n&quot;\n &quot;\\t\\tWeight: &quot; &lt;&lt; fp.GetWeight() &lt;&lt; &quot; ounces\\n&quot;\n &quot;\\t\\tDiameter: &quot; &lt;&lt; fp.GetDiameter() &lt;&lt; &quot; inches\\n&quot;;\n}\n</code></pre>\n<p>The advantage is that you can now also &quot;print&quot; to different streams beside <code>std::cout</code>, like to a <code>std::stringstream</code> or a <code>std::ofstream</code>, making it much more generic.</p>\n<h1>Mark constants with <code>const</code></h1>\n<p>In your classes, you initialize the member variables with some value, after which they can never be changed. In that case, make those member variables <code>const</code>, so that this is also clear to the compiler, which can then better optimize your code, and give an error if you accidentily do write to those variables:</p>\n<pre><code>class Frozenfood {\n const int Price;\n\nprotected:\n const int Weight;\n\npublic:\n ...\n};\n</code></pre>\n<p>To be able to set these <code>const</code> variables in the constructor, use <a href=\"https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list\">member intialization lists</a>:</p>\n<pre><code>FrozenFood::FrozenFood(int APrice, int AWeight):\n Price{APrice},\n Weight{AWeight} {\n}\n</code></pre>\n<p>I see you already use member initializer lists when initializing the base class, which is good.</p>\n<h1>Mark member functions that do not modify any member variables as <code>const</code></h1>\n<p>Apart from making member variables <code>const</code>, you can also make member functions <code>const</code>. This tells the compiler that these functions do not change any member variables, which allows it to generate better code, produce errors if you do accidentily make changes, and allows those functions to be called on <code>const</code> objects.\nSo for example:</p>\n<pre><code>class FrozenFood {\n ...\n int GetPrice() const;\n int GetWeight() const;\n};\n\nint GetPrice() const {\n return Price;\n}\n\nint GetWeight() const {\n return Weight;\n}\n</code></pre>\n<h1>Consider using <code>#pragma once</code></h1>\n<p>You are using header guards correctly. However, it can be a chore to add <code>#ifndef..#define..#endif</code>, and it is easy to accidentily copy&amp;paste the header guard and forget to change the name. All major compilers support <a href=\"https://en.wikipedia.org/wiki/Pragma_once\" rel=\"nofollow noreferrer\"><code>#pragma once</code></a>. If you add that to the header files, the compiler will ensure it's only ever included once.</p>\n<p>However, as pointed out by others, it is not standard C++ (yet). Also, C++20 introduces <a href=\"https://www.modernescpp.com/index.php/c-20-modules\" rel=\"nofollow noreferrer\">modules</a>, which avoids the need for header guards.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T21:56:03.683", "Id": "480359", "Score": "7", "body": "#pragma once isn't in the standard yet, so I don't recommend it over header guards. Most but not all compilers can use it which may affect portability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T03:16:19.557", "Id": "480383", "Score": "0", "body": "Wow a lot here for me to look into, thank you so much! I went ahead and marked your response as the answer, since it had a bit more to it and had good tips to improve performance as well as format. Y'all are awesome thank you so much!!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T20:32:33.367", "Id": "244680", "ParentId": "244674", "Score": "8" } }, { "body": "<h2>Code structure</h2>\n<ul>\n<li><p>The code in the file <code>main.cpp</code> only operates on <code>FDeepDishPizza</code> class, so the name sounds misleading to me. It feels like <code>main.cpp</code> would be working on the base class <code>FrozenFood</code>, instantiating its derived classes and calling their public functions, which it doesn't do.</p>\n</li>\n<li><p>A trivial constructor which only initialises the member variables can be in header file, instead of the implementation.</p>\n<pre><code> # FDeepDishPizza.h\n FDeepDishPizza(int APrice, int AWeight, int ADiameter, int AHeight); #can be expanded here itself, instead of in FDeepDishPizza.cpp . \n</code></pre>\n<ul>\n<li><a href=\"https://docs.microsoft.com/en-us/cpp/cpp/constructors-cpp?view=vs-2019#init_list_constructors\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/cpp/cpp/constructors-cpp?view=vs-2019#init_list_constructors</a></li>\n</ul>\n</li>\n</ul>\n<h2>Use of Caps</h2>\n<pre><code>class FrozenFood {\nprivate:\n int Price;\n}\n....\nFDeepDishPizza(...)\n</code></pre>\n<ul>\n<li><p>Capitalised names indicate classes, while all small letters indicate variables and functions. The latter two are the ones you'd be typing a lot, so better keep <kbd>shift</kbd> key out of the way.</p>\n</li>\n<li><p>Also, private members can be prefixed with <code>_</code>, like <code>_price</code> to have them stand out if they're being modified.</p>\n</li>\n</ul>\n<h2><code>#ifndef</code> vs <code>pragma once</code></h2>\n<blockquote>\n<p>Note Some implementations offer vendor extensions like <code>#pragma once</code> as alternative to include guards. It is not standard and it is not portable. It injects the hosting machine’s filesystem semantics into your program, in addition to locking you down to a vendor. Our recommendation is to write in ISO C++: See <a href=\"http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rp-Cplusplus\" rel=\"nofollow noreferrer\">rule P.2</a>.</p>\n</blockquote>\n<p><a href=\"http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rs-guards\" rel=\"nofollow noreferrer\">http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rs-guards</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T03:14:17.507", "Id": "480382", "Score": "0", "body": "Great suggestions here, thank you! I copied the syntax more or less from the book, and I was wondering if there was a reason they kept capitalizing the member variables! I guess it was just overlooked. I also didn't know about the \"pragma once\" stuff so that'll be awesome to look into :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:40:47.687", "Id": "480446", "Score": "0", "body": "\"Capitalised names indicate classes, while all small letters indicate variables and functions\" This is highly dependent on style. Some places use the style in the OP, with everything in PascalCase. Other places use the style in the standard library, with everything in lower_snake_case. It's incorrect to state anything definitive about casing other than that you should stick to a particular one, because there is such a large variance in style." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T17:17:36.863", "Id": "480467", "Score": "0", "body": "@Justin I did put it as an individual preference: that's why I mentioned the shift key. But yes it's not a golden rule. It's what happening where I'm contributing to, and may not happen where you are. But OP, while starting out, should be typing comfortably." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T21:08:21.747", "Id": "244681", "ParentId": "244674", "Score": "5" } } ]
{ "AcceptedAnswerId": "244680", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T19:10:34.530", "Id": "244674", "Score": "6", "Tags": [ "c++", "classes" ], "Title": "Simple Multiclass C++ Project" }
244674
<p>How can I optimise this code there is time out error</p> <p>Program Challenge:</p> <blockquote> <p>HackerLand National Bank has a simple policy for warning clients about possible fraudulent account activity. If the amount spent by a client on a particular day is greater than or equal to double the client's median spending for a trailing number of days, they send the client a notification about potential fraud. The bank doesn't send the client any notifications until they have at least that trailing number of prior days' transaction data. Given the number of trailing days and a client's total daily expenditures for a period of days, find and print the number of times the client will receive a notification over all days.</p> <p>For example, <code>d = 3</code> and <code>expenditures = [10, 20, 30, 40, 50]</code>. On the first three days, they just collect spending data. At day 4, we have trailing expenditures of <code>[10, 20, 30]</code>. The median is 20 and the day's expenditure is 40. Because <span class="math-container">\$40 \ge 2*20\$</span>, there will be a notice. The next day, our trailing expenditures are <code>[20, 30, 40]</code> and the expenditures are 50. This is less than <span class="math-container">\$2*30\$</span> so no notice will be sent. Over the period, there was one notice sent.</p> <p>Note: The median of a list of numbers can be found by arranging all the numbers from smallest to greatest. If there is an odd number of numbers, the middle one is picked. If there is an even number of numbers, median is then defined to be the average of the two middle values. (Wikipedia)</p> <p>Function Description</p> <p>Complete the function activityNotifications in the editor below. It must return an integer representing the number of client notifications.</p> <p>activityNotifications has the following parameter(s):</p> <p>expenditure: an array of integers representing daily expenditures d: an integer, the lookback days for median spending</p> <p>Input Format</p> <p>The first line contains two space-separated integers and, the number of days of transaction data, and the number of trailing days' data used to calculate median spending. The second line contains space-separated non-negative integers where each integer denotes.</p> <p>Constraints</p> <ul> <li><span class="math-container">\$ 1 \le n \le 2*10^5 \$</span></li> <li><span class="math-container">\$ 1 \le d \le n \$</span></li> <li><span class="math-container">\$ 0 \le expenditure[i] \le 200\$</span></li> </ul> <p>Output Format</p> <p>Print an integer denoting the total number of times the client receives a notification over a period of days.</p> <p>Sample Input 0</p> <p>9 5</p> <p>2 3 4 2 3 6 8 4 5</p> <p>Sample Output 0</p> <p>2</p> </blockquote> <p><a href="https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem" rel="nofollow noreferrer">HackerRank fraudulent activity.</a></p> <pre><code>public static int[] CountSort(int []arr,int si,int ei) { int []count=new int[201]; int result[]=new int[ei-si]; for(int i=si;i&lt;ei;i++) { count[arr[i]]++; } for(int i=1;i&lt;count.length;i++) { count[i]+=count[i-1]; } for(int i=ei-1;i&gt;=si;i--) { result[--count[arr[i]]]=arr[i]; } return result; } // Complete the activityNotifications function below. static int activityNotifications(int[] expenditure, int d) { int notice=0; for(int i=0;i&lt;=expenditure.length-d;i++) { int arr[]=new int[d]; double median=0; arr=CountSort(expenditure,i,i+d); if(d%2==0) { int mid1=(d)/2; int mid2=(d)/2 +1; median=(arr[mid1]+arr[mid2])/2; }else { int mid=(d)/2; median=arr[mid]; } if(i+d&lt;expenditure.length&amp;&amp;expenditure[i+d]&gt;=2*median) { notice++; } } return notice; } </code></pre>
[]
[ { "body": "<p>Quite often with HackerRank puzzles, there will be a check that your algorithm scales to large sizes. Here we are explicitly told that n may be up to 199 999.</p>\n<p>You have managed to come up with a homebrew sort that appears to be efficient given the data constraints. However, you are calling it in the outer loop, so your algorithm appears to be O(n^2) overall.</p>\n<p>Try working through the sample input &quot;9 5 / 2 3 4 2 3 6 8 4 5&quot; with pencil and paper; I'll bet you find it didn't involve nearly as much sorting. Then think about what data structures would best model what you did.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T17:25:52.277", "Id": "480469", "Score": "0", "body": "thanks it is a great help" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:59:05.430", "Id": "480523", "Score": "0", "body": "its min heap ?? am I right" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T08:18:07.417", "Id": "244698", "ParentId": "244678", "Score": "0" } } ]
{ "AcceptedAnswerId": "244698", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T19:48:40.503", "Id": "244678", "Score": "-2", "Tags": [ "java", "programming-challenge", "time-limit-exceeded" ], "Title": "Programming challenge - report fraudulent banking activity times out" }
244678
<p>I had trouble solving instances of Exact Three Cover with 100 units in input <strong>C</strong>. All in a reasonable amount of time. Mainly because the problem is <strong>NP-complete</strong>. So I came up with an <strong>approximate</strong> solution <em>(Don't ask me the ratio for correctness, because I don't know)</em> I have gotten 100, 500 and 1000 units in <strong>C</strong> to return correct solutions. <a href="https://cdn.hackaday.io/images/4687511592450886108.PNG" rel="nofollow noreferrer">Screenshot of 3000 units in C</a>. And, here is a <a href="https://repl.it/@TravisWells/Nuke-Em-All-Script-My-best-P-vs-NP-attempt#main.py" rel="nofollow noreferrer">link to my approximation algorithm</a> where <strong>C</strong> has <strong>100</strong> units.</p> <p>I believe that if I don't have significant amounts of <em>chaff</em> (sets that could cause my algorithm to fail) I can solve instances of Exact Three Cover I usually come upon quite quickly.</p> <p>Now, I don't have to wait for millennia to solve C with 500 units when I encounter these cases.</p> <p>Please don't ask me to change my constants; because I'm testing for 10,000 units in <strong>C</strong>. So I need a large constant for my while-loop.</p> <pre><code>import random from itertools import combinations from itertools import permutations import sympy import json s = input(&quot;Input set of integers for S : &quot;).split(',') c = input('enter list for C (eg. [[1,2,3],[4,5,6]]): ') c = json.loads(c) for a in range(0, len(s)): s[a] = int(s[a]) # Need a prime # seems to help spread # 3sets apart. count = len(s)//3 while True: count = count + 1 if sympy.isprime(count) == True: prime = count break # This is a SUPER Greedy # Algorithim that runs # in polynomial time. # It is impractical # for NO instances # It will TAKE FOREVER (constant of 241.. Duhh...) # to halt and # return an approximated # no. # The purpose of why I got # such a large constant # is because I needed # to find Exact Three # Covers in lists of C with # lengths of 100, 500, 1000 # units long. # The Exact 2^n solution # is unreasonably to long # for me. # This is a formula # to count all # possible combinations # of THREE except # I am using a constant # value of 241. while_loop_steps = len(s)*241*((len(s)*241)-1)*((len(s)*241)-2)//6 # Don't worry about this. #p = (len(s)//3)/while_loop_steps * 100 if len(s) % 3 != 0: print('invalid input') quit() # Sort list to remove # sets like (1,2,3) and (1,3,2) # but leave (1,2,3) delete = [] for a in range(0, len(c)): for i in permutations(c[a], 3): if list(i) in c[a:]: if list(i) != c[a]: delete.append(list(i)) for a in range(0, len(delete)): if delete[a] in c: del c[c.index(delete[a])] # remove sets # that have # repeating # elements remove = [] for rem in range(0, len(c)): if len(c[rem]) != len(set(c[rem])): remove.append(c[rem]) for rem_two in range(0, len(remove)): if remove[rem_two] in c: del c[c.index(remove[rem_two])] # remove sets # that have # elements # that don't # exist in S. remove=[] for j in range(0, len(c)): for jj in range(0, len(c[j])): if any(elem not in s for elem in c[j]): remove.append(c[j]) for rem_two in range(0, len(remove)): if remove[rem_two] in c: del c[c.index(remove[rem_two])] # Remove repeating sets solutions =[c[x] for x in range(len(c)) if not(c[x] in c[:x])] # check left and right for solutions def check_for_exact_cover(jj): jj_flat = [item for sub in jj for item in sub] jj_set = set(jj_flat) if set(s) == jj_set and len(jj_set) == len(jj_flat): print('yes', jj) quit() # Well if length(c) is small # use brute force with polynomial constant if len(c) &lt;= len(s)//3*2: for jj in combinations(c, len(s)//3): check_for_exact_cover(jj) if len(c) &gt;= len(s)//3*2: for jj in combinations(c[0:len(s)//3*2], len(s)//3): check_for_exact_cover(jj) if len(c) &gt;= len(s)//3*2: X = list(reversed(c)) for jj in combinations(X[0:len(s)//3*2], len(s)//3): check_for_exact_cover(jj) # Well, I have to quit # if the loop above # didn't find anything. # when len(c) &lt;= len(s)//3*2 if len(c) &lt;= len(s)//3*2: quit() # will need these Three (what a prime!) # just in case my algorithim # needs to reverse in loop. length = len(solutions) ss = s c = solutions # Primes # have been # observed # in nature # to help # avoid conflict. # So why not # pre shuffle C # prime times? for a in range(0, prime): random.shuffle(c) # while loop to see # if we can find # an Exact Three Cover # in poly-time. stop = 0 Potential_solution = [] opps = 0 failed_sets = 0 #Don't worry about this. (100/p*while_loop_steps) while stop &lt;= while_loop_steps: # Shuffling c randomly # this seems to help # select a correct set opps = opps + 1 stop = stop + 1 random.shuffle(c) if len(Potential_solution) == len(ss) // 3: # break if Exact # three cover is # found. print('YES SOLUTION FOUND!',Potential_solution) print('took',stop,'steps in while loop') failed_sets = failed_sets + 1 break # opps helps # me see # if I miss a correct # set if opps &gt; len(c): if failed_sets &lt; 1: s = set() opps = 0 # Keep c[0] # and append to # end of list # del c[0] # to push &gt;&gt; # in list. c.append(c[0]) del [c[0]] Potential_solution = [] s = set() for l in c: if not any(v in s for v in l): Potential_solution.append(l) s.update(l) if len(Potential_solution) != len(ss)//3: if stop == length: # Reverse list just # to see if I missed a solution for cc in range(0, len(c)): c = list(reversed(c)) random.shuffle(c) </code></pre> <p>Questions</p> <ul> <li>What parts of my sorting algorithms could be shortened and improved?</li> <li>Is the usage of primes to theoretically space out sets pointless?</li> <li>What variable names would you use in my code?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T23:57:54.577", "Id": "480371", "Score": "0", "body": "I just realized a mistake at the end of my code. The reversing will never be executed. So I should place that before the \"opps\" statements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T15:07:59.237", "Id": "480685", "Score": "1", "body": "Do you have example input for S and C that could be used to test the script? There are significant improvements that can be made in this script, but I am hesitant to implement them since there is no test case I can use to verify the validity of the code as changes are being made." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T01:47:53.957", "Id": "482205", "Score": "0", "body": "@Zchpyvr I have made my final script here. https://hackaday.io/project/173227/logs The second one has a large fixed C as shown in link." } ]
[ { "body": "<h2>Functions</h2>\n<p>For many reasons, you should attempt to move your global code into functions. Reasons include testability, meaningful stack traces, and de-cluttering the global namespace.</p>\n<h2>User input</h2>\n<p>This prompt:</p>\n<pre><code>input(&quot;Input set of integers for S : &quot;)\n</code></pre>\n<p>is missing a description to the user that they should be entering a comma-delimited list.</p>\n<p>This input:</p>\n<pre><code>input('enter list for C (eg. [[1,2,3],[4,5,6]]): ')\n</code></pre>\n<p>forces the user (who, we should assume, is not a programmer) to both understand and use JSON. JSON is intended as an application-friendly and not user-friendly serialization format. Instead, consider &quot;assisting&quot; the user by looping through and accepting multiple comma-separated (for consistency) lists. Given your example, a loop would execute twice and each iteration would produce a list of three items.</p>\n<h2>Iteration</h2>\n<pre><code>for a in range(0, len(s)):\n s[a] = int(s[a])\n</code></pre>\n<p>can be</p>\n<pre><code>s = [int(a) for a in s]\n</code></pre>\n<h2>In-place addition</h2>\n<pre><code>count = count + 1\n</code></pre>\n<p>can be</p>\n<pre><code>count += 1\n</code></pre>\n<h2>Boolean comparison</h2>\n<pre><code>if sympy.isprime(count) == True:\n</code></pre>\n<p>should be</p>\n<pre><code>if sympy.isprime(count):\n</code></pre>\n<h2>Iteration of a counted variable</h2>\n<pre><code>count = len(s)//3\nwhile True:\n count = count + 1\n</code></pre>\n<p>should be</p>\n<pre><code>for count in itertools.count(len(s)//3):\n</code></pre>\n<h2>Wrapping</h2>\n<p>This is a minor thing, but the comments starting at</p>\n<pre><code># This is a SUPER Greedy\n</code></pre>\n<p>are wrapped to a very small column count. Typically, the smallest column wrap you'll find in the wild is 80. It's probably a good idea to reformat this so that each line goes up to 80 characters long.</p>\n<h2>Temporary variables</h2>\n<p>Consider</p>\n<pre><code>n = len(s)\n</code></pre>\n<p>to simplify expressions like</p>\n<pre><code>len(s)*241*((len(s)*241)-1)*((len(s)*241)-2)//6\n</code></pre>\n<h2>More iteration</h2>\n<pre><code>delete = []\nfor a in range(0, len(c)):\n for i in permutations(c[a], 3):\n</code></pre>\n<p>should be</p>\n<pre><code>for a in c:\n for i in permutations(a, 3):\n # ...\n</code></pre>\n<h2>Variable naming</h2>\n<pre><code>opps = 0\n</code></pre>\n<p>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-10T20:36:04.857", "Id": "481695", "Score": "0", "body": "Could be worth mentioning that you can `map` to an input when splitting it, so you can do it in one line instead of two. `s = list(map(int, input(...).split()))`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T23:08:48.980", "Id": "244759", "ParentId": "244686", "Score": "4" } } ]
{ "AcceptedAnswerId": "244759", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-28T23:40:19.370", "Id": "244686", "Score": "2", "Tags": [ "python", "algorithm", "python-3.x" ], "Title": "Super greedy algorithm for Exact Three Cover" }
244686
<p>I just finished solving <a href="https://projecteuler.net/problem=50" rel="nofollow noreferrer">Project Euler's 50th problem</a>, but it's awfully slow. I'd like to hear your thoughts on my code's efficiency and practices.</p> <p><strong>Problem Statement</strong></p> <p>The prime 41, can be written as the sum of six consecutive primes:</p> <p><span class="math-container">\$41 = 2 + 3 + 5 + 7 + 11 + 13\$</span></p> <p>This is the longest sum of consecutive primes that adds to a prime below one-hundred.</p> <p>The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.</p> <p>Which prime, below one-million, can be written as the sum of the most consecutive primes?</p> <p><strong>Code</strong></p> <hr /> <pre><code>let primeNumbers = []; function isPrime(number) { // checks whether number is prime or not for(let i = 2; i &lt;= number / 2; i++) { // stops checking at 1/2 of number if (number % i === 0) return false; } return true; } function storePrimes(count) { for(let i = 2; i &lt; count; i++) { // starts at 2 if (isPrime(i)) { primeNumbers.push(i); } } } function findLargestSum() { let termsCount = 0; let sumOfTerms = 0; primeNumbers.forEach(currentSum =&gt; { // keeps track of possible sum primeNumbers.forEach((startNumber, startIndex) =&gt; { // keeps track of start index let consecutiveCount = 0; let consecutiveSum = 0; primeNumbers.forEach((prime, primeIndex) =&gt; { // iterates through primes if (primeIndex &gt;= startIndex) { // applies start index consecutiveCount++; consecutiveSum += prime; if (consecutiveCount &gt; termsCount &amp;&amp; consecutiveSum === currentSum) { termsCount = consecutiveCount; sumOfTerms = consecutiveSum; } } }) }) }) return {largestSum: sumOfTerms, termsCount: termsCount}; } function findPrimes(count) { storePrimes(count) let results = findLargestSum(); console.log(&quot;Largest sum'o'primes of prime consecutives under &quot; + count + &quot; is: &quot; + results.largestSum + &quot; with &quot; + results.termsCount + &quot; terms.&quot;); } findPrimes(1000000); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T08:42:04.057", "Id": "480402", "Score": "0", "body": "Please add a short description of the problem (not the performance problem, the programming challenge) to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T08:51:11.960", "Id": "480405", "Score": "0", "body": "@ArbriIbra Check `Sieve of Eratosthenes` since this question seems to be a duplicate. You can read about that on google or even search in the search bar here. There are lots of already answered questions. Also you can go for sqrt(n) + 1 instead of n/2 for the function isprime." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T10:04:21.013", "Id": "480409", "Score": "0", "body": "@VisheshMangla As we talked about yesterday this is an improvement to the code. This should go in _answers_ not in comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T10:21:07.070", "Id": "480411", "Score": "0", "body": "I have still a lot to learn. I was hesitant whether I should answer it because this seems to be a duplicate." } ]
[ { "body": "<p><strong>Improvement in function <code>isprime</code>:</strong></p>\n<pre><code>for(let i = 2; i &lt;= number / 2; i++)\n</code></pre>\n<p>can be</p>\n<pre><code>for(let i = 2; i &lt;= Math.round(Math.sqrt(number)) + 1 ; i++)\n</code></pre>\n<p>Otherwise, the best easy to understand approach(in accordance to my knowledge) is to use the <code>Sieve of Eratosthenes</code>. Your problem can be a subset of the following problem <a href=\"https://codereview.stackexchange.com/questions/80267/sieve-of-eratosthenes-javascript-implementation-performance-very-slow-over-a-c\">Sieve of Eratosthenes JavaScript implementation - performance very slow over a certain number</a>. Credits of the code below goes to the owner of this post.</p>\n<pre><code>function getPrimesUnder(number) {\n var start = new Date().getTime();\n\n var numbers = [2];\n var sqNum = Math.sqrt(number);\n var i, x;\n for (i = 3; i &lt; number; i = i + 2) {\n numbers.push(i);\n }\n for (x = 0; numbers[x] &lt; sqNum; x++) {\n for (i = 0; i &lt; numbers.length ; i++){\n if (numbers[i] &gt; numbers[x]) {\n if(numbers[i] % numbers[x] === 0){\n numbers.splice(i, 1)\n }\n }\n }\n }\n var end = new Date().getTime();\n var time = end - start;\n alert('Execution time: ' + time/1000 + ' seconds');\n return numbers;\n\n} \n</code></pre>\n<p>There is something much more efficient (<a href=\"https://stackoverflow.com/questions/453793/which-is-the-fastest-algorithm-to-find-prime-numbers\">Which is the fastest algorithm to find prime numbers?</a>) known as <code>Sieve of Atkin</code>. You can do more research on it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T10:38:05.947", "Id": "244706", "ParentId": "244699", "Score": "1" } }, { "body": "<p>You should measure the duration of each step in the algorithm to detect where the bottleneck(s) is/are. You can do that using <code>console.time(&quot;id&quot;)</code> paired with <code>console.timeEnd(&quot;id&quot;)</code>:</p>\n<pre><code>function findPrimes(count) {\n console.time(&quot;prime generation&quot;);\n storePrimes(count);\n console.timeEnd(&quot;prime generation&quot;)\n console.time(&quot;finding&quot;);\n let results = findLargestSum();\n console.timeEnd(&quot;finding&quot;);\n console.log(&quot;Largest sum'o'primes of prime consecutives under &quot; + count + &quot; is: &quot; + results.largestSum + &quot; with &quot; + results.termsCount + &quot; terms.&quot;);\n}\n</code></pre>\n<p>You'll then detect that <code>storePrimes()</code> takes considerably long time to generate primes up to <code>1,000,000</code>.</p>\n<hr />\n<p>One optimization could be in <code>isPrime()</code>:</p>\n<pre><code>function isPrime(number) {\n if (number &lt; 2) return false;\n if (number == 2) return true;\n if (number % 2 == 0) return false;\n\n let sqrt = Math.round(Math.sqrt(number));\n\n for (let n = 3; n &lt;= sqrt; n += 2) {\n if (number % n == 0) return false;\n }\n\n return true;\n}\n</code></pre>\n<p>As seen it is only necessary to check for values up to and including the square root of the number. And by handling <code>2</code> as a special case you only need to check odd numbers from <code>3</code> and up.</p>\n<p>But <code>storePrimes()</code> is still too slow, and I think it's about that you constantly push new primes on <code>primeNumbers</code>. Instead you can use a generator function in the following way:</p>\n<pre><code>function* createPrimes(limit) {\n yield 2; \n for (let i = 3; i &lt; limit; i += 2) { // You can start at 3 and only iterate over odd numbers\n if (isPrime(i)) {\n yield i;\n }\n }\n}\n</code></pre>\n<p>and then in <code>findPrimes()</code> call it as:</p>\n<pre><code>function findPrimes(limit) {\n primeNumbers = Array.from(createPrimes(limit));\n let results = findLargestSum(limit);\n console.log(&quot;Largest sum'o'primes of prime consecutives under &quot; + limit + &quot; is: &quot; + results.largestSum + &quot; with &quot; + results.termsCount + &quot; terms.&quot;);\n}\n</code></pre>\n<p>This will speed up the process beyond compare. Notice that I've changed some names like <code>count</code> to <code>limit</code> because it determines the largest prime - not the number of primes to generate.</p>\n<hr />\n<p>Using <code>forEach()</code> in this exact situation isn't a good idea, because you can't step out whenever you like, but have to iterate the entire prime set over and over again unnecessarily in your three nested loops. That is very inefficient. Besides that, I find it rather difficult to read and understand nested <code>forEach()</code>-calls as in your code.</p>\n<p>Instead you should use good old <code>for</code>-loops, because you then can break out when ever the state makes it meaningless to continue the loop:</p>\n<pre><code>function findLargestSum() {\n let termsCount = 0;\n let sumOfTerms = 0;\n let length = primeNumbers.length;\n\n for (let i = 0; i &lt; length; i++) {\n let targetSum = primeNumbers[i]; // keeps track of possible sum\n\n for (var j = 0; j &lt; i &amp;&amp; i - j &gt; termsCount; j++) {\n let sum = 0;\n for (var k = j; k &lt; i &amp;&amp; sum &lt; targetSum; k++) {\n sum += primeNumbers[k];\n }\n\n if (k - j &gt; termsCount &amp;&amp; sum == targetSum) {\n termsCount = k - j;\n sumOfTerms = targetSum;\n }\n }\n }\n\n return { largestSum: sumOfTerms, termsCount: termsCount };\n}\n</code></pre>\n<p>This is a significant improvement on performance, but is still rather slow. I have tried different steps to optimization, but I can't point out the bottlenecks. But below is my take on the challenge:</p>\n<pre><code>function findLargestSum(limit) {\n let resultSum = 0;\n let resultCount = -1;\n\n for (var i = 0; i &lt; primeNumbers.length &amp;&amp; primeNumbers.length - i &gt; resultCount; i++) {\n let sum = 0;\n\n for (var j = i; j &lt; primeNumbers.length; j++) {\n let prime = primeNumbers[j];\n\n sum += prime;\n if (sum &gt;= limit) {\n sum -= prime;\n break;\n }\n }\n j--;\n\n\n while (j &gt;= i &amp;&amp; !isPrime(sum)) {\n sum -= primeNumbers[j--];\n }\n\n if (j &gt;= i &amp;&amp; j - i &gt; resultCount) {\n resultSum = sum;\n resultCount = j + 1 - i;\n }\n }\n\n return { largestSum: resultSum, termsCount: resultCount };\n}\n</code></pre>\n<p>It repeatedly sums up the primes from each prime in the list and backtracks by subtracting the largest prime until the sum is either a prime or zero. It continues as long as the number of primes beyond <code>i</code> is greater than the length of an already found sequence.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T10:47:01.037", "Id": "480578", "Score": "0", "body": "Your answer helped me a lot. I know the comment tip says to avoid thank you comments but I really really appreciate it. Thank you" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:24:41.513", "Id": "244733", "ParentId": "244699", "Score": "1" } }, { "body": "<p>Consider what you are doing here. You are generating a list of primes less than a number. You are generating this list in order of increasing size. One simple optimization is to seed the list with a few primes at the beginning. In particular, 2 and 3. Then you iterate to skip over all the even numbers. That cuts your checks in half.</p>\n<p>Now, a second point is that you don't have to divide by all numbers less than half the number. You only have to divide by primes less than the square root of the number. And you know what, you have a list of primes smaller than the number. So use that in your trial division.</p>\n<p>So in your prime generation function (what you call <code>storePrimes</code> but which I might call <code>load_primes</code>), call a function that divides by the primes that you already have.</p>\n<pre><code>function is_divisible_from(candidate, numbers) {\n for (const n of numbers) {\n if (candidate % n === 0) {\n return true;\n }\n\n if (n &gt; candidate / n) {\n return false;\n }\n }\n\n // you should never get here\n return false;\n}\n</code></pre>\n<p>It is quite common to generate both the remainder and the quotient at the same time. So both <code>candidate % n</code> and <code>candidate / n</code> can be generated by one activity in many parsers. So this is probably efficient (do timing tests if you want to be sure). You have to do the division/remainder operation once per loop regardless. This just uses both results where most alternatives are doing an added square root check (hopefully just once).</p>\n<p>This is essentially saying that if you can find some number in the list that divides the candidate, then it is clearly a composite number and not prime. I call this <code>is_divisible_from</code> as better describing what the function does. But when you use it, a true result means that the number is not prime and a false result that it is.</p>\n<pre><code>function load_primes(upper_bound) {\n let primes = [ 2, 3 ];\n\n for (let i = 5; i &lt;= upper_bound; i += 2) {\n if (!is_divisible_from(i, primes)) {\n primes.push(i);\n }\n }\n}\n</code></pre>\n<p>There's also another optimization here, but I doubt that it will give enough savings to overcome its increased overhead. It's possible to skip over all the divisible by three values.</p>\n<p>Now you have efficiently created a list of primes in <span class=\"math-container\">\\$\\mathcal{O}(n \\sqrt{n})\\$</span> time, where <span class=\"math-container\">\\$n\\$</span> is your upper bound. Your original was <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span> in that step. Your original was also <span class=\"math-container\">\\$\\mathcal{O}(p^3)\\$</span> to use the list where <span class=\"math-container\">\\$p\\$</span> was the number of primes. But I believe that it is possible to do this in <span class=\"math-container\">\\$\\mathcal{O}(p^2)\\$</span> time.</p>\n<p>It should be obvious that you can calculate the sums in linear time. So keep adding to the sum until it is too large (greater than the upper bound). Then subtract the smallest value from it until is both small enough and prime. It's linear to check if a given number is prime (in the list). And it's linear to generate the sums, because we don't need to check every pair of indexes. We iterate over each left once and each right once.</p>\n<pre><code>let primes = load_primes(upper_bound);\nlet left = 0;\nlet right = 0;\nlet sum = 2;\nlet result = {largestSum: sum, termsCount: 0};\n\nwhile (right &lt; primes.length &amp;&amp; left &lt;= right) {\n if ((right - left &gt; result.termsCount) &amp;&amp; (0 &lt;= primes.indexOf(sum))) {\n result.largestSum = sum;\n result.termsCount = right - left;\n }\n\n right++;\n sum += primes[right];\n while ((sum &gt; upper_bound) &amp;&amp; (left &lt; right)) {\n sum -= primes[left];\n left++;\n }\n}\n\nresult.termsCount++;\nreturn result;\n</code></pre>\n<p>This works because we are looking for consecutive primes. So we don't need to backtrack or compare most values. We can move forward through all the possibilities that might be true, looking at a sliding window of values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T01:29:30.980", "Id": "244914", "ParentId": "244699", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T08:32:16.577", "Id": "244699", "Score": "3", "Tags": [ "javascript", "performance", "algorithm", "programming-challenge", "primes" ], "Title": "Project Euler 50: Consecutive prime sum" }
244699
<p>I have made a program that converts Celsius to Fahrenheit and Fahrenheit to Celsius. How is my code?</p> <pre><code>import java.util.Scanner; public class TemperatureConversion { public static void main(String[] args) { double fahrenheit, celsius; Scanner input = new Scanner(System.in); // Celsius to Fahrenheit \u2103 degree Celsius symbol System.out.println(&quot;Input temperature (\u2103): &quot;); celsius = input.nextDouble(); System.out.println(celsius * 1.8 + 32 + &quot; \u2109 \n&quot;); // Fahrenheit to Celsius \u2109 degree Fahrenheit symbol System.out.println(&quot;Input temperature (\u2109: &quot;); fahrenheit = input.nextDouble(); System.out.print((fahrenheit - 32) / 1.8 + &quot; \u2103&quot;); } } </code></pre>
[]
[ { "body": "<h2>It solves the problem, and that's good. Period.</h2>\n<p>But you're presenting your code here to get advice how to improve your programming skills, so here are a few remarks. Take them as a hint where to go from here, as soon as you feel ready for the &quot;next level&quot;.</p>\n<h2>Separate user interaction from computation</h2>\n<p>Your main method contains both aspects in one piece of code, even within the same line (e.g. <code>System.out.println(celsius * 1.8 + 32 + &quot; \\u2109 \\n&quot;);</code>). Make it a habit to separate tasks that can be named individually into methods of their own:</p>\n<ul>\n<li>input a Celsius value (a method <code>double readCelsius()</code>)</li>\n<li>input a Fahrenheit value (a method <code>double readFahrenheit()</code>)</li>\n<li>convert from Celsius to Fahrenheit (a method <code>double toFahrenheit(double celsius)</code>)</li>\n<li>convert from Fahrenheit to Celsius (a method <code>double toCelsius(double fahrenheit)</code>)</li>\n<li>output a Fahrenheit value (a method <code>void printFahrenheit(double fahrenheit)</code>)</li>\n<li>output a Celsius value (a method <code>void printCelsius(double celsius)</code>)</li>\n</ul>\n<p>With separate methods, it will be easier to later change your program to e.g. use a window system, or do bulk conversions of many values at once, etc.</p>\n<h2>More flexible workflow</h2>\n<p>Your current program always forces the user to do exactly one C-to-F and then one F-to-C conversion. This will rarely both be needed at the same time. I'd either ask the user at the beginning for the conversion he wants, or make it two different programs. By the way, doing so will be easier if the different tasks have been separated.</p>\n<h2>Minor hints</h2>\n<p>Combine variable declaration and value assignment. You wrote <code>double fahrenheit, celsius;</code> and later e.g. <code>celsius = input.nextDouble();</code>, I'd combine that to read <code>double celsius = input.nextDouble();</code>. This way, when reading your program (maybe half a year later), you immediately see at the same place that <code>celsius</code> is a <code>double</code> number coming from some input.</p>\n<p>I'd avoid the special characters like <code>\\u2109</code> and instead write two simple characters <code>°F</code>. Not all fonts on your computer will know how to show that <code>\\u2109</code> Fahrenheit symbol, so this might end up as some ugly-looking question mark inside a rectangle or similar. Using two separate characters does the job in a more robust way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T02:32:31.647", "Id": "480547", "Score": "0", "body": "Thank you for the comment and tips on my code. It really helped me a lot on how to improve my code. I'll be studying and experiment on how things work in Java. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T04:51:42.543", "Id": "480552", "Score": "1", "body": "Opposing opinion on the special characters: The degree sign is a special character which will be mangled if the code is transferred via a system that does not understand unicode. Unfortunaltey in the year 2020 it is still best to only rely on US-ASCII when dealing with file formats that do not include charset information (such as Java source code and property files). So use \"\\u00B0F\" and \"\\u00B0C\" instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T09:01:59.277", "Id": "480574", "Score": "1", "body": "@TorbenPutkonen Yes, your comment goes even further than my recommendation. I wrote my answer hoping that the OP's editor and compiler are correctly set up, and both agree on a character encoding containing the \"degree\" character. If so, I'd prefer `°F` over `\\u00B0F` because of readability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-09T01:44:54.943", "Id": "481508", "Score": "0", "body": "Thank you for all of your help. I have now fixed the code for conversion and added other temperature scale to convert with: https://pastebin.com/LcapCu8s" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T10:22:36.427", "Id": "244705", "ParentId": "244704", "Score": "7" } } ]
{ "AcceptedAnswerId": "244705", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T09:42:58.737", "Id": "244704", "Score": "4", "Tags": [ "java", "unit-conversion" ], "Title": "Java Temperature Converter" }
244704
<p>I am trying to calculate the rolling mean and std of a pandas dataframe. So far I'm here:</p> <pre><code>phi = pd.DataFrame(data=phi) #mean and std ## This could be a function... #for each window, get the mean and std of previous M frames #M = 40 p1_mean = phi.iloc[0].rolling(40, min_periods=1).mean() p2_mean = phi.iloc[1].rolling(40, min_periods=1).mean() p3_mean = phi.iloc[2].rolling(40, min_periods=1).mean() p4_mean = phi.iloc[3].rolling(40, min_periods=1).mean() P_mean = P_mean = [p1_mean, p2_mean, p3_mean, p4_mean] P_mean = pd.DataFrame(data=P_mean) p1_std = phi.iloc[0].rolling(40, min_periods=1).std() p2_std = phi.iloc[1].rolling(40, min_periods=1).std() p3_std = phi.iloc[2].rolling(40, min_periods=1).std() p4_std = phi.iloc[3].rolling(40, min_periods=1).std() P_std = [p1_std, p2_std, p3_std, p4_std] P_std = pd.DataFrame(data=P_std) </code></pre> <p>This works, but I'm wondering if there is a more pythonic way to do this?</p> <p>I tried this something like this:</p> <pre><code>P = phi.rolling(40, min_periods=1).agg({np.std, np.mean}) </code></pre> <pre><code>print 0 1 2 3 \ mean std mean std mean std mean 0 0.084194 NaN 0.329374 NaN 0.353773 NaN 0.345830 1 0.161660 0.109554 0.229725 0.140926 0.290061 0.090103 0.302811 2 0.163631 0.077542 0.286092 0.139506 0.312857 0.074955 0.318717 3 0.138196 0.081217 0.295218 0.115359 0.323390 0.064725 0.325664 </code></pre> <p>which seems close enough, except that I want the std and mean for each column on the same column. In my df of shape (4, 3000) this gives me (4, 6000) and I'm looking for a shape of (8, 3000) Also, I want the rolling window row/-wise not default column wise. Any ideas? Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T08:28:11.670", "Id": "480571", "Score": "0", "body": "Can you show us the output you actually want? Because you say you want it as a shape `(8, 3000)`, but your code does not actually do that." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T10:48:45.087", "Id": "244707", "Score": "1", "Tags": [ "python", "pandas", "statistics" ], "Title": "Calculate rolling mean and std over a pandas dataframe" }
244707
<p>For my students (I am an Austrian math teacher) I would like to provide some simple online calculators on my blog.</p> <p>Let's say there are two pages on my website(&quot;Circle&quot; and &quot;Cube&quot;) and on every page I want to have about 10 different calculators.</p> <p>Here is an example of one page with two calculators:</p> <p><a href="https://i.stack.imgur.com/keTXg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/keTXg.png" alt="enter image description here" /></a></p> <p><strong>My code</strong></p> <p><a href="https://jsfiddle.net/ygo97rzf/5/" rel="nofollow noreferrer">JSFiddle</a></p> <p><em>HTML</em></p> <pre><code>&lt;h1&gt;Circle&lt;/h1&gt; &lt;h2&gt;Calculate circumference of circle&lt;/h2&gt; &lt;p&gt; Radius of circle: &lt;input type=&quot;text&quot; id=&quot;calc1-input&quot;&gt; &lt;button onclick=&quot;calc1()&quot;&gt;Calculate&lt;/button&gt; &lt;/p&gt; &lt;p&gt; Circumference of circle: &lt;span id=&quot;calc1-output&quot;&gt;&lt;/span&gt; &lt;/p&gt; &lt;h2&gt;Calculate area of circle&lt;/h2&gt; &lt;p&gt; Radius of circle: &lt;input type=&quot;text&quot; id=&quot;calc2-input&quot;&gt; &lt;button onclick=&quot;calc2()&quot;&gt;Calculate&lt;/button&gt; &lt;/p&gt; &lt;p&gt; Area of circle: &lt;span id=&quot;calc2-output&quot;&gt;&lt;/span&gt; &lt;/p&gt; </code></pre> <p><em>Javascript</em></p> <pre><code>function commaToDot(number) { return parseFloat(number.replace(',','.').replace(' ','')); } function dotToComma(number){ return number.toString().replace('.',','); } function calc1() { var input = document.getElementById(&quot;calc1-input&quot;).value; input = commaToDot(input); if (isNaN(input)) { document.getElementById('calc1-output').innerHTML = &quot;&lt;b&gt;Please enter a number!&lt;/b&gt;&quot;; } else { var output = 2 * Math.PI * input; document.getElementById('calc1-output').innerHTML = dotToComma(output); } } function calc2() { var input = document.getElementById(&quot;calc2-input&quot;).value; input = commaToDot(input); if (isNaN(input)) { document.getElementById('calc2-output').innerHTML = &quot;&lt;b&gt;Please enter a number!&lt;/b&gt;&quot;; } else { var output = Math.PI * Math.pow(input,2); document.getElementById('calc2-output').innerHTML = dotToComma(output); } } </code></pre> <p><strong>Explanation</strong></p> <ul> <li><em>Input:</em> In my country we use commas as decimal separators.<br /> So the students write 55,5 instead of 55.5 (see <code>commaToDot()</code>).</li> <li><em>Output:</em> The students expect the output to be with comma decimal separator, too (see <code>dotToComma()</code>).</li> <li><em>Error:</em> If the input is not a number (<code>if (isNaN(input))</code>) an error message will be displayed instead of the calculation result.</li> </ul> <p><strong>Questions</strong></p> <ul> <li>I see a lot of redundance in my code but I don't know how to improve it.<br /> The only difference between <code>calc1()</code> and <code>calc2()</code> is the formula.</li> <li>Maybe it is possible to improve the naming of the variables/functions?</li> </ul>
[]
[ { "body": "<p><code>calc1</code> and <code>calc2</code> are really bad names. Names should always clearly describe what they are for or do. <code>calculateCircleCircumference</code> and <code>calculateCircleArea</code> would be better\nchoices.</p>\n<p>I'm not a big fan of the names <code>commaToDot</code> and <code>commaToDot</code> either. I'd prefer more conceptional names such as <code>parseNumber</code> and <code>formatNumber</code>, maybe even <code>parseGermanNumber</code> and <code>formatGermanNumber</code>.</p>\n<p>A slightly better HTML structure would be in order: Each calculator could be surrounded by a <code>&lt;form&gt;</code> element and there is an <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output\" rel=\"nofollow noreferrer\"><code>&lt;output&gt;</code></a> element specifically for display calculation results.</p>\n<p>In current JavaScript one should prefer <code>const</code> and <code>let</code> over <code>var</code>.</p>\n<p>The following suggestions may introduce concepts, that the students haven't learnt yet, but they are considered good conventions.</p>\n<p>For a better separation of layout and logic it is usually suggested not to use <code>on...</code> event handler attributes, but instead assign them using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>addEventListener</code></a>.</p>\n<p>Also one should move all element look ups to the initialization. This could look like this (notice the changed IDs):</p>\n<pre><code>const circleCircumferenceRadiusInput = document.getElementById(&quot;circle-circumference-radius-input&quot;);\nconst circleCircumferenceOutput = document.getElementById('circle-circumference-output');\n\nfunction calculateCircleCircumference() {\n // Using separate variables so &quot;const&quot; can be used.\n const inputString = circleCircumferenceRadiusInput.value;\n const input = commaToDot(inputString);\n if (isNaN(input)) {\n circleCircumferenceOutput.innerHTML = &quot;&lt;b&gt;Please enter a number!&lt;/b&gt;&quot;;\n } else {\n const output = 2 * Math.PI * input;\n circleCircumferenceOutput.innerHTML = dotToComma(output);\n }\n}\n\ndocument.getElementById('circle-circumference-button').addEventHandler(&quot;click&quot;, calculateCircleCircumference);\n</code></pre>\n<p>This can be simplified a bit by wrapping HTML of the calculator in an <code>&lt;form&gt;</code> element and referring to the needed elements by name. Also I'm wrapping the code in an initialization function to avoid lots of global variables. Both of these prepare for generalizing and reusing the code.</p>\n<pre><code>&lt;form id=&quot;circle-circumference&quot;&gt;\n &lt;h2&gt;Calculate circumference of circle&lt;/h2&gt;\n &lt;p&gt;\n Radius of circle: &lt;input type=&quot;text&quot; name=&quot;radius&quot;&gt; &lt;button name=&quot;execute&quot;&gt;Calculate&lt;/button&gt;\n &lt;/p&gt;\n &lt;p&gt;\n Circumference of circle: &lt;output name=&quot;output&quot;&gt;&lt;/output&gt;\n &lt;/p&gt;\n&lt;/form&gt;\n</code></pre>\n<pre><code>function initCircleCircumferenceCalculator(form) {\n const radiusInput = form.elements[&quot;radius&quot;];\n const outputElement = form.elements[&quot;output&quot;];\n\n function calculate() {\n const inputString = radiusInput.value;\n const input = commaToDot(inputString);\n if (isNaN(input)) {\n outputElement.innerHTML = &quot;&lt;b&gt;Please enter a number!&lt;/b&gt;&quot;;\n } else {\n const output = 2 * Math.PI * input;\n outputElement.innerHTML = dotToComma(output);\n }\n }\n\n form.elements[&quot;execute&quot;].addEventHandler(&quot;click&quot;, calculate);\n} \n\ninitCircleCircumferenceCalculator(document.getElementById(&quot;circle-circumference&quot;));\n</code></pre>\n<p>Now that we have the initialization function it's easier to generalize this so that it can be used for multiple calculators:</p>\n<pre><code>function initCalculator(form, inputName, calculationFunction) {\n const inputElement = form.elements[inputName];\n const outputElement = form.elements[&quot;output&quot;];\n\n function calculate() {\n const inputString = inputElement.value;\n const input = commaToDot(inputString);\n if (isNaN(input)) {\n outputElement.innerHTML = &quot;&lt;b&gt;Please enter a number!&lt;/b&gt;&quot;;\n } else {\n const output = calculationFunction(input);\n outputElement.innerHTML = dotToComma(output);\n }\n }\n\n form.elements[&quot;execute&quot;].addEventHandler(&quot;click&quot;, calculate);\n} \n\n// Circle circumference\ninitCalculator(document.getElementById(&quot;circle-circumference&quot;), &quot;radius&quot;, r =&gt; 2 * Math.PI * r);\n\n// Circle area \ninitCalculator(document.getElementById(&quot;circle-area&quot;), &quot;radius&quot;, r =&gt; Math.PI * Math.pow(r, 2));\n\n</code></pre>\n<p>The next step could be modify <code>initCalculator</code> so that it supports multiple input fields.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T12:51:34.603", "Id": "480419", "Score": "0", "body": "That's really impressive. Thanks for sharing your skill with me. Maybe you can add the following feature: There are calculators with two or more inputs. I think an array will do the job?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T12:45:59.647", "Id": "244709", "ParentId": "244708", "Score": "4" } } ]
{ "AcceptedAnswerId": "244709", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T11:30:05.363", "Id": "244708", "Score": "3", "Tags": [ "javascript", "calculator" ], "Title": "Several simple calculators on one page" }
244708
<p>I am new to C programming, I previously studied Python. Below is my year one project in C.</p> <p>My project's name is &quot;Advanced Calculator&quot;, it's a menu-driven calculator application with several operations, as you can see from the first menu:</p> <pre><code>Which mode do you want to use? [1] Normal maths operations [2] Special Functions [3] Fibonacci Series [4] Random Mathematical Question [5] Exit Your input: </code></pre> <p>Although the calculator works so far and all operations are completed, I feel that the program lacks some features and functions that are typically found in any calculator. I plan to add <code>sinh</code>, <code>tanh</code> and <code>cosh</code> into it, but what else? Any idea is appreciated!</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; //For functions like system() and exit() #include &lt;windows.h&gt; //For function Sleep() #include &lt;math.h&gt; //For functions like pow(), sin(), cos(), tan() #include &lt;time.h&gt; //For time based modules and functions #include &lt;conio.h&gt; //For kbhit, input detector #define PI 3.14159265358979323846 load(); //Function Prototype main(void) { int i = 1; /* */ double x, xy, y; /* */ char Opt; /* Declaring the type variables */ int Numbering; /* */ int N, F, Oof, Check; /* */ int a, b, Choice; /* */ int c, d, K; /* */ float Num1, Num2 ,ans, CheckF; /* */ char oper, H; /* */ system(&quot;cls&quot;); //Clears terminal screen printf(&quot;Welcome to our calculator.\n&quot;); while (1){ //While loop that never ends, unless exit(0) is used printf(&quot;\n\nWhich mode do you want to use?\n[1] Normal maths operations\n[2] Special Functions\n[3] Fibonacci Series\n[4] Random Mathematical Question\n[5] Exit\n\nYour input: &quot;); scanf(&quot; %c&quot;, &amp;Opt); if (Opt == '1'){ printf(&quot;Welcome to Normal maths operation Mode.\n\nYour two numbers: &quot;); scanf(&quot;%f%f&quot;, &amp;Num1, &amp;Num2); printf(&quot;\nAVAILABLE SYMBOLS:\n\n+ for Addition\n- for Subtraction\n/ for Division\n* for Multiplication\n^ for Power function\n\\ for Rooting\nYour input: &quot;); scanf(&quot; %c&quot;, &amp;oper); if (oper == '+'){ ans = (Num1 + Num2); printf(&quot;Here is your answer:\n%f %c %f = %.5f (To 5 decimal places)\n\n&quot;, Num1, oper, Num2, ans); Sleep(245); } else if (oper == '-'){ ans = (Num1 - Num2); printf(&quot;Here is your answer:\n%f %c %f = %.5f (to 5 decimal places)\n\n&quot;, Num1, oper, Num2, ans); Sleep(245); } else if (oper == '/'){ ans = (Num1 / Num2); printf(&quot;Here is your answer:\n%f %c %f = %.5f (to 5 decimal places)\n\n&quot;, Num1, oper, Num2, ans); Sleep(245); } else if (oper == '*'){ ans = (Num1 * Num2); printf(&quot;Here is your answer:\n%f %c %f = %.5f (to 5 decimal places)\n\n&quot;, Num1, oper, Num2, ans); Sleep(245); } else if (oper == '^'){ ans = (pow (Num1 , Num2)); printf(&quot;Here is your answer:\n%f %c %f = %.5f (to 5 decimal places)\n\n&quot;, Num1, oper, Num2, ans); Sleep(245); } else if (oper == '\\'){ ans = pow(Num2 , 1/Num1); Check = Num1; Oof = Check % 2; if (Num2 &lt; 0){ printf(&quot;Cannot root a negative number; ERROR 1 Sintek\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } else if (Oof == 0){ printf(&quot;Here is your answer:\n%f root(%f) = - %.5f or + %.5f (to 5 decimal places)\n\n&quot;, Num1, Num2, ans, ans); Sleep(245); } else if (!Oof == 0){ printf(&quot;Here is your answer:\n%f root(%f) = + %.5f (to 5 decimal places)\n\n&quot;, Num1, Num2, ans); Sleep(245); } } else { printf(&quot;\n\nYour input operator is incorrect; ERROR 1 Sintek\n&quot;); printf(&quot;\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } } if (Opt == '2'){ printf(&quot;Welcome to Special Functions Mode.\n\n[1] Sine Function\n[2] Cosine Function\n[3] Tangent Function\n[4] Log (With base 10)\n[5] Log (With base e)\n[6] Log (With user defined base)\n[7] Sine Inverse Function\n[8] Cosine Inverse Function\n[9] Tangent Inverse Function\n\nWhich mode do you want: &quot;); scanf(&quot;%d&quot;, &amp;N); if (N == 1){ printf(&quot;Your angle: &quot;); scanf(&quot;%f&quot;, &amp;Num1); ans = (sin ( Num1 * PI/180 )); printf(&quot;\nHere is your answer:\nSine(%f) = %.5f (to 5 decimal places)\n\n&quot;, Num1, ans); Sleep(245); } else if (N == 2){ printf(&quot;Your angle: &quot;); scanf(&quot;%f&quot;, &amp;Num1); ans = (cos ( Num1 * PI/180 )); printf(&quot;Here is your answer:\nCosine(%f) = %.5f (to 5 decimal places)\n\n&quot;, Num1, ans); Sleep(245); } else if (N == 3){ printf(&quot;Your angle: &quot;); scanf(&quot;%f&quot;, &amp;Num1); ans = (tan ( Num1 * PI/180 )); printf(&quot;Here is your answer:\nTangent(%f) = %.5f (to 5 decimal places)\n\n&quot;, Num1, ans); Sleep(245); } else if (N == 4){ printf(&quot;Your number: &quot;); scanf(&quot;%f&quot;, &amp;Num1); ans = log10(Num1); if (Num1 &lt; 0){ printf(&quot;Cannot log a negative number; ERROR 1 Sintek\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } else if (Num1 == 0){ printf(&quot;Cannot log(0); ERROR 1 Sintek\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } else if (Num1 &gt; 0){ printf(&quot;Here is your answer:\nLg(%f) = %.5f (to 5 decimal places)\n\n&quot;, Num1, ans); Sleep(245); } } else if (N == 5){ printf(&quot;Your number: &quot;); scanf(&quot;%f&quot;, &amp;Num1); ans = log(Num1); if (Num1 &lt; 0){ printf(&quot;Cannot ln a negative number; ERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } else if (Num1 == 0){ printf(&quot;Cannot ln(0); Error 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } else if (Num1 &gt; 0){ printf(&quot;Here is your answer:\nLn(%f) = %.5f (to 5 decimal places)\n\n&quot;, Num1, ans); Sleep(245); } } else if (N == 6){ printf(&quot;Enter the base number, followed by the number: &quot;); scanf(&quot;%f%f&quot;, &amp;Num1, &amp;Num2); ans = ( log(Num2) / log(Num1)); if (Num1 &lt;= 0 || Num2 &lt;=0){ printf(&quot;Cannot log a negative/zero base/number; ERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } else if (Num1 &gt; 0 &amp;&amp; Num2 &gt; 0){ printf(&quot;Here is your answer:\nLog[base %f]%f = %.5f (to 5 decimal places)\n\n&quot;, Num1, Num2, ans); Sleep(245); } } else if (N == 7){ printf(&quot;[1] Entering hypotenuse and opposite of triangle\n[2] Entering the value directly\n\nYour option: &quot;); scanf(&quot;%d&quot;, &amp;K); if (K == 1){ printf(&quot;Enter hypotenuse and opposite sides of the triangle: &quot;); scanf(&quot;%f%f&quot;, &amp;Num1, &amp;Num2); CheckF = Num2 / Num1; if (CheckF &lt; -1 || CheckF &gt; 1){ printf(&quot;The opposite side should not be larger than the hypotenuse side. Please recheck your values!\nERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } else { ans = (asin ( CheckF )); printf(&quot;Sine inverse %f/%f =\n%f (In radians)&quot;, Num2, Num1, ans); ans = ans * 180/PI; printf(&quot;\n%f (In degrees)&quot;, ans); Sleep(250); } } else if (K == 2){ printf(&quot;Enter your value: &quot;); scanf(&quot;%f&quot;, &amp;CheckF); if (CheckF &lt; -1 || CheckF &gt; 1){ printf(&quot;Value cannot be higher than 1/lower than -1. Please recheck your input!\nERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } else { ans = (asin ( CheckF )); printf(&quot;Sine inverse %f =\n%f (In radians)&quot;, CheckF, ans); ans = ans * 180/PI; printf(&quot;\n%f (In degrees)&quot;, ans); Sleep(250); } } else if (K != 1 || K != 2) { printf(&quot;Your input option is not found! ERROR 404\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } } else if (N == 8){ printf(&quot;[1] Entering adjacent and hypotenuse of triangle\n[2] Entering the value directly\n\nYour option: &quot;); scanf(&quot;%d&quot;, &amp;K); if (K == 1){ printf(&quot;Enter adjacent and hypotenuse sides of the triangle: &quot;); scanf(&quot;%f%f&quot;, &amp;Num1, &amp;Num2); CheckF = Num1 / Num2; if (CheckF &lt; -1 || CheckF &gt; 1){ printf(&quot;The adjacent side should not be larger than the hypotenuse side. Please reckeck your values!\nERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } else { ans = (acos ( CheckF )); printf(&quot;Cosine inverse %f/%f =\n%f (In radians)&quot;, Num1, Num2, ans); ans = ans * 180/PI; printf(&quot;\n%f (In degrees)&quot;, ans); Sleep(250); } } else if (K == 2){ printf(&quot;Enter your value: &quot;); scanf(&quot;%f&quot;, &amp;CheckF); if (CheckF &lt; -1 || CheckF &gt; 1){ printf(&quot;Value cannot be higher than 1/lower than -1. Please recheck your input!\nERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } else { ans = (acos ( CheckF )); printf(&quot;Cosine inverse %f = \n%f (In radians)&quot;, CheckF, ans); ans = ans * 180/PI; printf(&quot;\n%f (In degrees)&quot;, ans); Sleep(250); } } else if (K != 1 || K != 2) { printf(&quot;Your input option is not found! Error 404\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } } else if (N == 9){ printf(&quot;[1] Entering opposite and adjacent of triangle\n[2] Entering the value directly\n\nYour option: &quot;); scanf(&quot;%d&quot;, &amp;K); if (K == 1){ printf(&quot;Enter opposite and adjacent sides of the triangle: &quot;); scanf(&quot;%f%f&quot;, &amp;Num1, &amp;Num2); CheckF = Num1 / Num2; ans = (atan ( CheckF )); printf(&quot;Tangent inverse %f/%f =\n%f (In radians)&quot;, Num1, Num2, ans); ans = ans * 180/PI; printf(&quot;\n%f (In degrees)&quot;, ans); Sleep(250); } else if (K == 2){ printf(&quot;Enter your value: &quot;); scanf(&quot;%f&quot;, &amp;CheckF); if (CheckF &lt; -1 || CheckF &gt; 1){ printf(&quot;Value cannot be higher than 1/lower than -1. Please recheck your input!\nERROR 1 Sintek\n\a&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } else { ans = (atan ( CheckF )); printf(&quot;Tangent inverse %f =\n%f (In radians)&quot;, CheckF, ans); ans *= 180/PI; printf(&quot;\n%f (In degrees)&quot;, ans); Sleep(250); } } else if (K != 1 || K != 2) { printf(&quot;Your input option is not found! ERROR 404\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } } else { printf(&quot;Your input option is not found! ERROR 404\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } } if (Opt == '3'){ printf(&quot;Welcome to Fibonacci Series Mode.\n\nPress any key to stop while printing the numbers, to pause.\nEnter how many numbers do you want from the series, from the start: &quot;); scanf(&quot;%d&quot;, &amp;N); x = 0; y = 1; F = 3; Numbering = 3; printf(&quot;Here is Your Series:\n\n&quot;); if (N == 1){ printf(&quot;[1] 0\n&quot;); Sleep(1000); } if (N == 2){ printf(&quot;[1] 0\n&quot;); Sleep(75); printf(&quot;[2] 1\n&quot;); Sleep(1075); } if (N == 3){ printf(&quot;[1] 0\n&quot;); Sleep(75); printf(&quot;[2] 1\n&quot;); Sleep(75); printf(&quot;[3] 1\n&quot;); Sleep(1075); } if (N &gt; 3){ printf(&quot;[1] 0\n&quot;); Sleep(75); printf(&quot;[2] 1\n&quot;); Sleep(75); } while ( N &gt; 3 &amp;&amp; F &lt;= N ){ xy = x + y; printf(&quot;[%.0d] %.5g\n&quot;, Numbering, xy); Sleep(75); x = y; y = xy; F++; Numbering++; while (kbhit()){ printf(&quot;\n\n[+] Interrupted\n\nE to exit\nC to continue printing\n\nOption: &quot;); scanf(&quot; %c&quot;, &amp;H); if (H == 'E'){ printf(&quot;Exiting in 3 seconds. Goodbye!&quot;); Sleep(3000); exit(0); } else if (H == 'C'){ continue; } } } Sleep(1000); } if (Opt == '4'){ srand(time(NULL)); Choice = rand()%3; if (Choice == 0){ a = rand()%5001; b = rand()%5001; c = a + b; printf(&quot;What is %d + %d?\nYour answer: &quot;, a, b); scanf(&quot;%d&quot;, &amp;d); if (d == c){ printf(&quot;Yes. You are right; Congratulations\n\n&quot;); system(&quot;pause&quot;); } else { printf(&quot;No. The correct answer is %.0d. Need to practice more!\n\n&quot;, c); system(&quot;pause&quot;); system(&quot;cls&quot;); } } if (Choice == 1){ a = rand()%5001; b = rand()%5001; c = a - b; printf(&quot;What is %d - %d?\nYour answer: &quot;, a, b); scanf(&quot;%d&quot;, &amp;d); if (d == c){ printf(&quot;Yes. You are right; Congratulations\n\n&quot;); system(&quot;pause&quot;); } else { printf(&quot;No. The correct answer is %.0d. Need to practice more!\n\n&quot;, c); system(&quot;pause&quot;); system(&quot;cls&quot;); } } if (Choice == 2){ a = rand()%20; b = rand()%20; c = a * b; printf(&quot;What is %d times %d?\nYour answer: &quot;, a, b); scanf(&quot;%d&quot;, &amp;d); if (d == c){ printf(&quot;Yes. You are right; Congratulations\n\n&quot;); system(&quot;pause&quot;); } else { printf(&quot;No. The correct answer is %.0d. Need to practice more!\n\n&quot;, c); system(&quot;pause&quot;); system(&quot;cls&quot;); } } } if (Opt == '5'){ printf(&quot;Thank you for using my calculator. Hope to see you again!!&quot;); Sleep(1250); system(&quot;cls&quot;); exit(0); } if (Opt &lt; '1' || Opt &gt; '5'){ printf(&quot;Your option is not found! ERROR 404&quot;); printf(&quot;\a\n&quot;); system(&quot;pause&quot;); system(&quot;cls&quot;); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T13:25:05.143", "Id": "480421", "Score": "6", "body": "Welcome to Code Review. I hope you'll get some nice reviews, as there are certainly some Pythonic elements to your code that have more elegant C counterparts. I took the liberty to change your description to highlight that your calculator already works fine, I hope you're pleased with the new description. If not, feel free to [edit] your post :)" } ]
[ { "body": "<p>Welcome to Code Review, we wish you the best.</p>\n<p><strong>General Observations</strong><br />\nCongratulations on getting this to work, one function that is 356 lines long and almost 17K of text is a bit large and very hard to code and debug.</p>\n<p><strong>Complexity</strong><br />\nThe function <code>main()</code> is too complex and should be broken into functions. A general rule of thumb in all programming is that a function should only be one edit screen in size, because it is to hard to keep track of everything that is going on. Typical software / program design involves breaking the problem up into smaller and smaller pieces to make it easier to understand. An example would be having different functions handle the each of the modes listed in the menu, one for <code>Special Functions</code>, one for <code>Fibonacci Series</code> one for <code>Normal maths operations</code> and one for <code>Random Mathematical Question</code>. Each of these top level functions can call sub functions.</p>\n<p>There are a few software principles involved here:</p>\n<p><em><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRY programming, AKA Don't Repeat Yourself</a></em><br />\nIn a large function such as main there will be code that repeats itself in different places, rather than repeating the code put that code into a function and call that function is necessary, this allows the code to be written and debugged once and that speeds up development and maintenance.</p>\n<p><em>Single Responsibility Principle</em><br />\nThere is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p><em><a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"noreferrer\">The KISS principal</a> which is Keep it Simple</em><br />\nThis is fairly self explanatory, make the code as simple as possible within small blocks.</p>\n<p>The overall design principal is <a href=\"https://en.wikipedia.org/wiki/Top-down_and_bottom-up_design\" rel=\"noreferrer\">Top Down Design</a> or <a href=\"https://www.cs.uct.ac.za/mit_notes/software/htmls/ch07s09.html\" rel=\"noreferrer\">Stepwise Refinement</a>, this is applied generally to procedural languages, Top Down and Bottom Up design can be used in Object Oriented Design.</p>\n<p>An example of one function could be <code>print_menu_return_option()</code>.</p>\n<pre><code>char print_menu_return_option()\n{\n char Opt; /* Declaring the type variables */\n int input_check = 0;\n\n while (input_check == 0)\n {\n printf(&quot;\\n\\nWhich mode do you want to use?\\n[1] Normal maths operations\\n[2] Special Functions\\n[3] Fibonacci Series\\n[4] Random Mathematical Question\\n[5] Exit\\n\\nYour input: &quot;);\n input_check = scanf(&quot; %c&quot;, &amp;Opt);\n }\n\n return Opt;\n}\n</code></pre>\n<p>In the above code you should use the return value of <code>scanf()</code> to check for errors in user input.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:49:24.557", "Id": "480452", "Score": "2", "body": "Given that the user is a [tag:beginner], I'd add some remarks about `switch`/`case` for the menu and submenus. Other than that full ACK on the review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:52:05.450", "Id": "480455", "Score": "1", "body": "I did think about it, but I'd prefer to do it if the user posts a follow up which I strongly suggest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T21:31:03.897", "Id": "480632", "Score": "0", "body": "The while loop in `print_menu_return_option()` is interesting. Under what input or conditions would `scanf(\" %c\", &Opt);` ever return 0 to cause another iteration? I'd expect only 1 or `EOF`. Perhaps this is only template code for further building?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T14:26:32.230", "Id": "244713", "ParentId": "244710", "Score": "18" } }, { "body": "<h1>Code structure</h1>\n<p>Treat <code>main.c</code> as boss who calls other people up to do their job. In this case, functions where one function does one thing. <code>main</code> is doing <em>everything</em> here.</p>\n<pre><code>else{\n printf(&quot;No. The correct answer is %.0d. Need to practice more!\\n\\n&quot;, c);\n system(&quot;pause&quot;);\n system(&quot;cls&quot;);\n}\n</code></pre>\n<p>This error message can be one function which receives one input <code>c</code>.</p>\n<p>The whole block of <code>if (choice == a_number)</code> can go to one function with a better description. It makes maintaining the code much more easier. Debugging, extending functionality and having someone else read/ review your code becomes easy too.</p>\n<h1>Variables.</h1>\n<p>They can certainly have better names than alphabets. It reduces chances of unintentional editing. Describe what a variable stores: an incoming argument ? a return value ? indices ? <code>a</code> doesn't tell anything about what it stores. So whenever I encounter it, I'll have to check all the places where <code>a</code> was modified to see what it is doing.</p>\n<h1>clang-format</h1>\n<p>Please use <code>clang-format</code> to improve readability and consistent coding-style. Also it saves the manual effort of remembering to add indent or move braces etc.</p>\n<ul>\n<li><a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"nofollow noreferrer\">https://clang.llvm.org/docs/ClangFormat.html</a></li>\n<li><a href=\"https://marketplace.visualstudio.com/items?itemName=xaver.clang-format\" rel=\"nofollow noreferrer\">https://marketplace.visualstudio.com/items?itemName=xaver.clang-format</a></li>\n<li><a href=\"https://github.com/mapbox/XcodeClangFormat\" rel=\"nofollow noreferrer\">https://github.com/mapbox/XcodeClangFormat</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:25:52.040", "Id": "244743", "ParentId": "244710", "Score": "2" } }, { "body": "<p>Whereas @pacmaninbw offers some excellent general strategies, let's look at some specific syntax.</p>\n<h2>Pi</h2>\n<p>This is a point of <a href=\"https://stackoverflow.com/questions/5007925/using-m-pi-with-c89-standard\">some contention</a>, but - where a library defines <code>M_PI</code>, and most do - I tend to use it. Since you're including <code>windows.h</code> it's likely that you're using MSVC. In that case, <a href=\"https://docs.microsoft.com/en-us/cpp/c-runtime-library/math-constants?view=vs-2019\" rel=\"nofollow noreferrer\">it gives you math constants</a> if you configure the compiler with <code>_USE_MATH_DEFINES</code>.</p>\n<p>My opinion is that this is a precompiler directive, and the precompiler is build-configurable, so configure it in the build. If you need to port this to Linux, the precompiler configuration necessary to support <code>M_PI</code> would change, but you can cross that bridge when you get there.</p>\n<h2>Prototype</h2>\n<pre><code>load(); //Function Prototype\n</code></pre>\n<p>It is? For what function? I don't see this defined anywhere.</p>\n<h2>Variable declaration</h2>\n<p>Since C99, predeclaring all variables at the top of the function is both unnecessary and, I find, unsightly. You can declare and initialize these where they are used. Also, your naming (Oof?) needs a little love.</p>\n<h2>Implicit string concatenation</h2>\n<p>Split this:</p>\n<pre><code> printf(&quot;\\n\\nWhich mode do you want to use?\\n[1] Normal maths operations\\n[2] Special Functions\\n[3] Fibonacci Series\\n[4] Random Mathematical Question\\n[5] Exit\\n\\nYour input: &quot;);\n</code></pre>\n<p>into</p>\n<pre><code>printf(\n &quot;\\n\\n&quot;\n &quot;Which mode do you want to use?\\n&quot;\n &quot;[1] Normal maths operations\\n&quot;\n &quot;[2] Special Functions\\n&quot;\n &quot;[3] Fibonacci Series\\n&quot;\n &quot;[4] Random Mathematical Question\\n&quot;\n &quot;[5] Exit\\n\\n&quot;\n &quot;Your input: &quot;\n);\n</code></pre>\n<h2>Use a <code>switch</code></h2>\n<p>This, and its related comparisons:</p>\n<pre><code>if (Opt == '1'){\n</code></pre>\n<p>should use a <a href=\"https://docs.microsoft.com/en-us/cpp/c-language/switch-statement-c?view=vs-2019\" rel=\"nofollow noreferrer\">switch</a>.</p>\n<h2>Order of operations</h2>\n<pre><code> ans = ( log(Num2) / log(Num1));\n</code></pre>\n<p>does not need outer parens.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T21:54:34.450", "Id": "244754", "ParentId": "244710", "Score": "4" } }, { "body": "<p>Many reviews, so some additional ideas.</p>\n<p><strong>Programmable precision</strong></p>\n<p>Rather than hard-code the 5, use a flexible variable. Perhaps code later may want to allow the user to adjust the width.</p>\n<pre><code>// printf(&quot;Here is your answer:\\nLg(%f) = %.5f (to 5 decimal places)\\n\\n&quot;, Num1, ans);\nint prec = 5;\nprintf(&quot;Here is your answer:\\nLg(%.*f) = %.*f (to %d decimal places)\\n\\n&quot;, \n prec, Num1, prec, ans, prec);\n</code></pre>\n<p>Also consider <code>&quot;*.g&quot;</code> instead, more informative with small and large values.</p>\n<p><strong><code>float</code> v. <code>double</code></strong></p>\n<p>Little reason to use <code>float</code>, especially since code calls so many <code>double</code> functions. In C, <code>double</code> is the default floating-point type. Save <code>float</code> for code needing restrictions in space or tight performance.</p>\n<p><strong>Defensive coding</strong></p>\n<p><code>if (Num1 &lt; 0){</code> is a good idea, yet deserves to be <em>before</em> <code>ans = log(Num1);</code></p>\n<p>Consider a test before divide:</p>\n<pre><code>if (Num2 == 0.0) Handle_div_by_zero();\nelse ans = (Num1 / Num2);\n</code></pre>\n<p><strong>Machine pi</strong></p>\n<p>Although OP did well with at least 17 digits for <code>pi</code>, more digits do not hurt. Recommend for such popular constants, use twice the expected digit need or the common <code>define</code> when available. When <code>FLT_VAL_METHOD == 2</code> (<code>double</code> math using <code>long double</code>), the greater precision is then employed.</p>\n<pre><code>#ifdef M_PI\n#define PI M_PI\n#else\n#define PI ‭3.1415926535897932384626433832795‬\n#endif\n</code></pre>\n<p><strong>Trig functions and degrees</strong></p>\n<p>Trig functions, especially with large degree angles, benefit with range reduction in degrees first.<br />\n<a href=\"https://stackoverflow.com/a/32304207/2410359\">Why this sin cos look up table inaccurate when radian is large?</a></p>\n<pre><code>// ans = (cos ( Num1 * PI/180 ));\nans = (cos ( fmod(Num1,360) * PI/180 ));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T09:27:55.200", "Id": "480654", "Score": "1", "body": "Why `prec` instead of `precision`? It took me a while to figure out what `prec` stood for. (There's definitely personal preference here though; I'd generally advocate against using abbreviations in the first place, except really common and trivial ones.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:01:37.540", "Id": "480727", "Score": "0", "body": "@tjalling I tend to use a level of verbosity like the OP's with a leaning toward my preference. OP used a mixture with `i, x, xy, y, Opt, Numbering, Oof, Check`, etc. As `prec` is used in `printf()` as a _precision_ (a C library term), I did not see a strong need to dominate the arguments with a lengthy `precision, Num1, precision, ans, precision` which hides a bit the key players of `Num1, ans`. As with such style issues, I recommend to follow your groups' style guide." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T08:03:21.320", "Id": "480761", "Score": "0", "body": "Agreed on following the group/team practices. I mentioned it because variable naming can also be considered part of code review. But I should probably have made my own answer if I wanted to address that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T00:47:26.130", "Id": "244764", "ParentId": "244710", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T13:01:32.500", "Id": "244710", "Score": "15", "Tags": [ "beginner", "c" ], "Title": "Calculator application" }
244710
<p>I'm currently familiarizing myself with reinforcement learning (RL). For convenience, instead of manually entering coordinates in the terminal, I created a very simple UI for testing trained agents and play games against them. You can experiment and play around with it using different hyperparameters but as this is a very basic reinforcement learning algorithm I did not get good results for boards larger than the standard tic tac toe size (3 x 3).</p> <p>For using it just run <code>python3 ui.py</code> the agent will be trained and then the UI will be loaded and you can play against the trained agent.</p> <p>How to improve efficiency / memory requirements, they are negligible but an improvement does not hurt since memory scores are stored for updates. Can I to improve agent accuracy / ability to, win games / prevent human from winning specially on larger boards? And of course general feedback is appreciated. And as I'm currently learning RL concepts, I'm aware that there is a lot more to learn and sooner or later I might find answers to the RL technical questions I have however I'm always open for feedback.</p> <p>Here's what the UI looks like:</p> <p><a href="https://i.stack.imgur.com/1ati5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1ati5.png" alt="enter image description here" /></a></p> <p><code>helper.py</code></p> <pre><code>import numpy as np class TicBase: &quot;&quot;&quot; Base class with useful utils/helpers. &quot;&quot;&quot; def __init__(self, board_size=3, empty_value=0, x_value=2, o_value=3): &quot;&quot;&quot; Initialize common settings. Args: board_size: int, board cell x cell size. empty_value: int, representation of available cells. x_value: int, representation(internal not for display) of X on the board. o_value: int, representation(internal not for display) of O on the board. &quot;&quot;&quot; self.board_size = board_size self.board = np.ones((board_size, board_size)) * empty_value self.empty_value = empty_value self.x_value = x_value self.o_value = o_value def get_empty_cells(self, board=None): &quot;&quot;&quot; Get empty locations that are available. Args: board: numpy array of shape n, n where n: self.board_size. Returns: A list of (x, y) empty indices of the board. &quot;&quot;&quot; board = board if board is not None else self.board empty_locations = np.where(board == self.empty_value) return list(zip(*empty_locations)) def check_game_ended(self, board): &quot;&quot;&quot; Check for empty cells. Args: board: numpy array of shape n, n where n: self.board_size. Returns: True if there are empty cells, False otherwise. &quot;&quot;&quot; return not np.any(board == self.empty_value) def check_win(self, symbol, board=None): &quot;&quot;&quot; Check if there is a winner. Args: symbol: int, representation of the player on the board. board: numpy array of shape n, n where n: self.board_size. Returns: symbol if symbol is winner else None. &quot;&quot;&quot; board = board if board is not None else self.board result = ( np.all(board == symbol, axis=0).any() or np.all(board == symbol, axis=1).any() or np.all(board.diagonal() == symbol) or np.all(board[::-1].diagonal() == symbol) ) if result: return symbol def reset_game(self, symbol=None): &quot;&quot;&quot; Reset board. Args: symbol: int, representation of the winning player on the board. Returns: None &quot;&quot;&quot; self.board = ( np.ones((self.board_size, self.board_size)) * self.empty_value ) </code></pre> <p><code>agent.py</code></p> <pre><code>from helper import TicBase import numpy as np class TicAgent(TicBase): &quot;&quot;&quot; Tic Tac Toe agent. &quot;&quot;&quot; def __init__( self, agent_settings, board_size=3, empty_value=0, x_value=2, o_value=3 ): &quot;&quot;&quot; Initialize agent settings. Args: agent_settings: Dictionary that has the following keys: - 'epsilon': float, value from 0 to 1 representing degree of random(exploratory) moves. - 'learning_rate': float, Learning rate used to update values. - 'symbol': int, representation of the agent on the board. board_size: int, board cell x cell size. empty_value: int, representation of available cells. x_value: int, representation(internal not for display) of X on the board. o_value: int, representation(internal not for display) of O on the board. &quot;&quot;&quot; TicBase.__init__(self, board_size, empty_value, x_value, o_value) self.symbol = agent_settings['symbol'] self.opponent_symbol = x_value if self.symbol == o_value else o_value self.learning_rate = agent_settings['learning_rate'] self.epsilon = agent_settings['epsilon'] self.game_scores = {} @staticmethod def get_game_id(board): &quot;&quot;&quot; Convert game to string representation for storing game scores. Args: board: numpy array of shape n, n where n: self.board_size. Returns: string representation of the game. &quot;&quot;&quot; return ''.join(board.reshape(-1).astype(int).astype(str)) def calculate_score(self, board): &quot;&quot;&quot; Calculate game score which depends on the winner/loser. Args: board: numpy array of shape n, n where n: self.board_size. Returns: score. &quot;&quot;&quot; game_id = self.get_game_id(board) score = self.game_scores.get(game_id) if score is not None: return score score = 0 winner = self.check_win(self.symbol, board) or ( self.check_win(self.opponent_symbol, board) ) if winner == self.symbol: score = 1 if not winner and not self.check_game_ended(board): score = 0.5 self.game_scores[game_id] = score return score def generate_move(self, board, empty_locations, learning=True): &quot;&quot;&quot; Generate a random/best value move according to self.epsilon. Args: board: numpy array of shape n, n where n: self.board_size which represents the game most-recent state. empty_locations: A list of (x, y) empty indices of the board. learning: If True, exploration is allowed. Returns: Chosen empty_locations index. &quot;&quot;&quot; probability = np.random.rand() if probability &lt; self.epsilon and learning: return np.random.choice(len(empty_locations)) possible_moves = [board.copy() for _ in empty_locations] for idx, empty_location in enumerate(empty_locations): r, c = empty_location possible_moves[idx][r, c] = self.symbol scores = [ self.calculate_score(possible) for possible in possible_moves ] return np.argmax(scores) def step(self, board): &quot;&quot;&quot; Take turn. Args: board: numpy array of shape n, n where n: self.board_size which represents the game most-recent state. Returns: None &quot;&quot;&quot; empty_locations = self.get_empty_cells(board) move_idx = self.generate_move(board, empty_locations) r, c = empty_locations[move_idx] board[r, c] = self.symbol def update_game_scores(self, game_history, winner): &quot;&quot;&quot; Update agent weights. Args: game_history: A list of numpy arrays(game boards) of 1 full game. winner: int representation of agent/opponent. Returns: None &quot;&quot;&quot; target = 1 if winner == self.symbol else 0 for game in reversed(game_history): game_id = self.get_game_id(game) old_score = self.calculate_score(game) updated_score = old_score + self.learning_rate * ( target - old_score ) self.game_scores[game_id] = updated_score target = updated_score </code></pre> <p><code>trainer.py</code></p> <pre><code>from helper import TicBase from agent import TicAgent class TicTrainer(TicBase): &quot;&quot;&quot; Tool for agent training. &quot;&quot;&quot; def __init__( self, agent_settings, board_size=3, empty_value=0, x_value=2, o_value=3 ): &quot;&quot;&quot; Initialize agents for training. Args: agent_settings: A list of 2 dictionaries for 2 agents. board_size: int, board cell x cell size. empty_value: int, representation of available cells. x_value: int, representation(internal not for display) of X on the board. o_value: int, representation(internal not for display) of O on the board. &quot;&quot;&quot; TicBase.__init__(self, board_size, empty_value, x_value, o_value) self.agent_1 = TicAgent( agent_settings[0], board_size, empty_value, x_value, o_value ) self.agent_2 = TicAgent( agent_settings[1], board_size, empty_value, x_value, o_value ) def play_one(self, game_history): &quot;&quot;&quot; Play one game. Args: game_history: A list of numpy arrays(game boards) of 1 full game. Returns: symbol or 'end' or None. &quot;&quot;&quot; board = self.board for agent in [self.agent_1, self.agent_2]: agent.step(board) game_history.append(board.copy()) if self.check_win(agent.symbol, board): return agent.symbol if self.check_game_ended(board): return 'end' def train_step(self): &quot;&quot;&quot; 1 training step/iteration and update. Returns: None &quot;&quot;&quot; game_history = [] while True: winner = self.play_one(game_history) if winner in ['end', self.x_value, self.o_value]: break self.agent_1.update_game_scores(game_history, winner) self.agent_2.update_game_scores(game_history, winner) self.reset_game(winner) def train_basic(self, iterations): &quot;&quot;&quot; Train using the most basic value function. Args: iterations: Training loop size. Returns: self.agent_1, self.agent2 &quot;&quot;&quot; for i in range(iterations): percent = round((i + 1) / iterations * 100, 2) print( f'\r Training agent ... iteration: ' f'{i}/{iterations} - {percent}% completed', end='', ) self.train_step() return self.agent_1, self.agent_2 </code></pre> <p><code>ui.py</code></p> <pre><code>from PyQt5.QtWidgets import ( QMainWindow, QDesktopWidget, QApplication, QWidget, QHBoxLayout, QVBoxLayout, QPushButton, QLabel, ) from PyQt5.QtCore import Qt import numpy as np import sys from helper import TicBase from trainer import TicTrainer class TicCell(QPushButton): &quot;&quot;&quot; Tic Tac Toe cell. &quot;&quot;&quot; def __init__(self, location): &quot;&quot;&quot; Initialize cell location. Args: location: Tuple, (row, col). &quot;&quot;&quot; super(QPushButton, self).__init__() self.location = location class TicUI(QMainWindow, TicBase): &quot;&quot;&quot; Tic Tac Toe interface. &quot;&quot;&quot; def __init__( self, window_title='Smart Tic Tac Toe', board_size=3, empty_value=0, x_value=2, o_value=3, agent=None, ): &quot;&quot;&quot; Initialize game settings. Args: window_title: Display window name. board_size: int, the board will be of size(board_size, board_size). empty_value: int representation of an empty cell. x_value: int representation of a cell containing X. o_value: int representation of a cell containing O. agent: Trained TicAgent object. &quot;&quot;&quot; super(QMainWindow, self).__init__() TicBase.__init__( self, board_size=board_size, empty_value=empty_value, x_value=x_value, o_value=o_value, ) self.setWindowTitle(window_title) self.agent = agent if self.agent is not None: self.agent.board = self.board self.text_map = { x_value: 'X', o_value: 'O', empty_value: '', 'X': x_value, 'O': o_value, '': empty_value, } win_rectangle = self.frameGeometry() center_point = QDesktopWidget().availableGeometry().center() win_rectangle.moveCenter(center_point) self.central_widget = QWidget(self) self.main_layout = QVBoxLayout() self.score_layout = QHBoxLayout() self.human_score = 0 self.agent_score = 0 self.score_board = QLabel() self.update_score_board() self.setStyleSheet('QPushButton:!hover {color: yellow}') self.cells = [ [TicCell((c, r)) for r in range(board_size)] for c in range(board_size) ] self.cell_layouts = [QHBoxLayout() for _ in self.cells] self.adjust_layouts() self.adjust_cells() self.update_cell_values() self.show() def adjust_layouts(self): &quot;&quot;&quot; Adjust score board and cell layouts. Returns: None &quot;&quot;&quot; self.main_layout.addLayout(self.score_layout) for cell_layout in self.cell_layouts: self.main_layout.addLayout(cell_layout) self.central_widget.setLayout(self.main_layout) self.setCentralWidget(self.central_widget) def adjust_cells(self): &quot;&quot;&quot; Adjust display cells. Returns: None &quot;&quot;&quot; self.score_layout.addWidget(self.score_board) self.score_board.setAlignment(Qt.AlignCenter) for row_index, row in enumerate(self.cells): for cell in row: cell.setFixedSize(50, 50) cell.clicked.connect(self.game_step) self.cell_layouts[row_index].addWidget(cell) def get_empty_cells(self, board=None): &quot;&quot;&quot; Get empty cell locations. Returns: A list of indices that represent currently empty cells. &quot;&quot;&quot; empty_locations = super().get_empty_cells() for empty_location in empty_locations: r, c = empty_location cell_text = self.cells[r][c].text() assert cell_text == self.text_map[self.empty_value], ( f'location {empty_location} has a cell value of {cell_text}' f'and board value of {self.board[r][c]}' ) return empty_locations def update_score_board(self): &quot;&quot;&quot; Update the display scores. Returns: None &quot;&quot;&quot; self.score_board.setText( f'Human {self.human_score} - ' f'{self.agent_score} Agent' ) def reset_cell_colors(self): &quot;&quot;&quot; Reset display cell text colors. Returns: None &quot;&quot;&quot; for row_idx in range(self.board_size): for col_idx in range(self.board_size): self.cells[row_idx][col_idx].setStyleSheet('color: yellow') def reset_game(self, symbol=None): &quot;&quot;&quot; Reset board and display cells and update display scores. Args: symbol: int, self.x_value or self.o_value. Returns: None &quot;&quot;&quot; super().reset_game(symbol) self.update_cell_values() if symbol == self.x_value: self.human_score += 1 if symbol == self.o_value: self.agent_score += 1 self.update_score_board() self.reset_cell_colors() def modify_step(self, cell_location, value): &quot;&quot;&quot; Modify board and display cells. Args: cell_location: tuple, representing indices(row, col). value: int, self.x_value or self.o_value. Returns: True if the clicked cell is not empty, None otherwise. &quot;&quot;&quot; r, c = cell_location board_value = self.board[r, c] cell_value = self.cells[r][c].text() if not board_value == self.empty_value: return True assert cell_value == self.text_map[self.empty_value], ( f'mismatch between board value({board_value}) ' f'and cell value({cell_value}) for location {(r, c)}' ) if value == self.x_value: self.cells[r][c].setStyleSheet('color: red') self.board[r, c] = value self.cells[r][c].setText(f'{self.text_map[value]}') def game_step(self): &quot;&quot;&quot; Post cell-click step(human step and agent step) Returns: None &quot;&quot;&quot; cell = self.sender() stop = self.modify_step(cell.location, self.x_value) if stop: return x_win = self.check_win(self.x_value) if x_win is not None: self.reset_game(self.x_value) return empty_locations = self.get_empty_cells() if not empty_locations: self.reset_game() return choice = np.random.choice(len(empty_locations)) if self.agent: choice = self.agent.generate_move( self.board, empty_locations, False ) self.modify_step(empty_locations[choice], self.o_value) o_win = self.check_win(self.o_value) if o_win is not None: self.reset_game(self.o_value) def update_cell_values(self): &quot;&quot;&quot; Sync display cells with self.board Returns: None &quot;&quot;&quot; for row_index, row in enumerate(self.board): for col_index, col in enumerate(row): update_value = self.text_map[self.board[row_index][col_index]] self.cells[row_index][col_index].setText(f'{update_value}') if __name__ == '__main__': s = [ {'symbol': 2, 'epsilon': 0.1, 'learning_rate': 0.5}, {'symbol': 3, 'epsilon': 0.1, 'learning_rate': 0.5}, ] train = TicTrainer(s) a1, a2 = train.train_basic(10000) test = QApplication(sys.argv) window = TicUI(agent=a2) sys.exit(test.exec_()) </code></pre>
[]
[ { "body": "<h2>Cell value representation</h2>\n<p>It's good that you've distinguished this:</p>\n<blockquote>\n<p>representation(internal not for display)</p>\n</blockquote>\n<p>however, I'm not clear on the reason for making these integers configurable. You're probably better off making an <code>Enum</code>:</p>\n<pre><code>class TicValue(Enum):\n EMPTY = 0\n X = 2\n O = 3\n</code></pre>\n<p>This can still be compatible with Numpy, because <code>.value</code> will return those integers.</p>\n<h2>Truthy coalesce</h2>\n<pre><code>board = board if board is not None else self.board\n</code></pre>\n<p>has shorthand:</p>\n<pre><code>board = board or self.board\n</code></pre>\n<p>as long as <code>board</code> doesn't have any funny business overriding <code>__bool__</code> or <code>__len__</code>.</p>\n<h2>Boolean equivalent cast</h2>\n<pre><code>target = 1 if winner == self.symbol else 0\n</code></pre>\n<p>can be</p>\n<pre><code>target = int(winner == self.symbol)\n</code></pre>\n<h2>Unpacking</h2>\n<pre><code> self.agent_1 = TicAgent(\n agent_settings[0], board_size, empty_value, x_value, o_value\n )\n self.agent_2 = TicAgent(\n agent_settings[1], board_size, empty_value, x_value, o_value\n )\n</code></pre>\n<p>can be</p>\n<pre><code>self.agent_1, self.agent_2 = (\n TicAgent(settings, board_size, empty_value, x_value, o_value)\n for settings in agent_settings\n)\n</code></pre>\n<h2>In-band signalling</h2>\n<pre class=\"lang-none prettyprint-override\"><code> Returns:\n symbol or 'end' or None.\n</code></pre>\n<p>is not very convenient for other functions to process. Consider splitting this apart into</p>\n<pre><code>def play_one(self, game_history: List[ndarray]) -&gt; (\n bool, # is end\n Optional[str], # symbol or None\n):\n # ...\n return False, agent.symbol\n # ...\n return True, None\n</code></pre>\n<h2>Display map</h2>\n<pre><code> self.text_map = {\n x_value: 'X',\n o_value: 'O',\n empty_value: '',\n 'X': x_value,\n 'O': o_value,\n '': empty_value,\n }\n</code></pre>\n<p>is a little surprising. You're using this as a map in both directions. It would be safer, and a better guarantee of correctness, for this to be split into forward- and back-maps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T17:48:45.313", "Id": "480477", "Score": "1", "body": "Ah, so my warning about overriding `__len__` turns out to be applicable. Adding type hints to your function signatures and member variables will make it clear which variables can receive this kind of treatment." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T17:38:09.210", "Id": "244730", "ParentId": "244711", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T13:09:10.083", "Id": "244711", "Score": "2", "Tags": [ "python", "python-3.x", "numpy", "machine-learning", "pyqt" ], "Title": "Smart Tic Tac Toe, a reinforcement learning approach" }
244711
<p>To try and practice OOP, I've heard making a blackjack game can be really helpful; which it has been. I don't know how 'advanced' an implementation this is; but it has all the standard features, like being able to split/double. as well as actual card representations displayed in the terminal (made from ASCII characters). while my code does in fact in work, id love if somebody can take a look at it; if there's any bad practice going on, and what I can improve. Anything that can help me learn is more then welcome, so please don't hold back. I divided into two files: <code>blackjack.py</code> and <code>visuals.py</code> which has a variety of ways to display actual cards: at first it was all in one file, but I thought it would make more sense to split them into two for organization: each with its own clear purpose. is this frowned upon (making many files) or is that encouraged?</p> <p><em>(I hope its okay that I link the GitHub <a href="https://github.com/zsonnen/blackjack" rel="nofollow noreferrer">BlackJack game click here</a> as it would be a few hundred lines to copy and paste here.</em></p> <p>The player has ability to wager on each hand, and keep playing until balance hits $0.0. As a future project, I'm thinking of maybe having a way to have user provide a login, to remember the balance/ and they can pick off where they left (stored in a database) but that's for the future. I also am new to GitHub, so I welcome any advice on how to utilize the readme: how descriptive I should or should not be/what's worth including etc.</p> <p>I wonder if including <code>assert</code> to ensure the correct type is poorly used or if it is good practice, as it certainly can help in debugging. What is the standard when the project is done- are they left in (seen a few times in the Player class)?</p> <p>I also wonder if I used <code>super().__init__()</code> correctly, when it came to inheritance. I provided an example screenshot of what the game would look like.</p> <p>GitHub: <a href="https://github.com/zsonnen/blackjack" rel="nofollow noreferrer">BlackJack game click here</a></p> <p><a href="https://codereview.stackexchange.com/questions/244785/follow-up-blackjack-with-card-representation-visuals">Follow-up post of Blackjack game</a></p> <pre><code>import random import collections import time import os import visuals &quot;&quot;&quot; BLACKJACK GAME: visuals file imported: numerous pretty ways to display cards &quot;&quot;&quot; def clear(): os.system('cls' if os.name == 'nt' else 'clear') def validate_answer(question, choices): while True: answer = input(question) if answer in choices: return answer == choices[0] yes_no = ['y', 'n'] Card = collections.namedtuple('Card', ['value', 'suit']) class Deck: values = [str(v) for v in range(2, 11)] + list('JQKA') suits = &quot;Spades Diamonds Hearts Clubs&quot;.split() suit_symbols = ['♠','♦','♥','♣'] def __init__(self, num_decks = 1): self.cards = [Card(value, suit) for suit in self.suits for value in self.values] * num_decks self.length = len(self) def __repr__(self): deck_cards = &quot;Deck()\n&quot; for card in self.cards: deck_cards += f&quot;({card.value}-{card.suit})&quot; return deck_cards def __len__(self): return len(self.cards) def __getitem__(self, position): return self.cards[position] def draw_card(self): return self.cards.pop() def shuffle(self): random.shuffle(self.cards) #Shuffle when deck is &lt; 50% full length def is_shuffle_time(self): return len(self) &lt; (self.length / 2) def shuffle_time(self): print(&quot;Reshuffling the Deck...\n&quot;) time.sleep(1) print(&quot;Reshuffling the Deck...\n&quot;) time.sleep(1) print(&quot;Reshuffling the Deck...\n&quot;) time.sleep(1) self.reset() self.shuffle() def reset(self): self.cards = [Card(value, suit) for suit in self.suits for value in self.values] * num_decks class Hand: def __init__(self): self.hand = [] def __repr__(self): hand_cards = &quot;Hand()\n&quot; for card in self.hand: hand_cards += f&quot;({card.value}-{card.suit})&quot; return hand_cards def add_card(self, *cards): for card in cards: self.hand.append(card) def remove_card(self): return self.hand.pop() def hit(self, deck): assert isinstance(deck, Deck) card = deck.draw_card() self.add_card(card) def hand_score(self): self.card_val = [10 if card.value in ['J','Q','K'] else 1 if card.value == 'A' else int(card.value) for card in self.hand] self.card_scores = dict(zip(self.hand, self.card_val)) score = 0 for card in self.hand: card_score = self.card_scores[card] score += card_score if any(card.value == 'A' for card in self.hand) and score &lt;= 11: score += 10 return score def card_visual(self): card_list = [] for card in self.hand: card_vis = visuals.reg_card_visual(card) card_list.append(card_vis) visuals.print_cards(card_list) print(f&quot;\nTotal of: {self.hand_score()}\n&quot;) time.sleep(1) def mini_card_visual(self): card_list = [] for card in self.hand: card_vis = visuals.mini_card_visual(card) card_list.append(card_vis) visuals.print_cards(card_list) print(f&quot;\nTotal of: {self.hand_score()}\n&quot;) time.sleep(1) class Player(Hand): def __init__(self, chips, bet=0, split_cards = False): super().__init__() self.chips = chips self.bet = bet self.profit = 0 self.alive = True self.split_cards = split_cards self.has_blackjack = False def deal_cards(self, deck): self.hit(deck) self.hit(deck) print_line('Player Cards') self.card_visual() self.has_blackjack = self.check_for_blackjack() self.split_cards = self.check_for_split() self.apply_split(deck) def add_chips(self, chips): self.chips += chips def remove_chips(self, chips): self.chips -= chips def print_balance(self): print(f&quot;\nYour balance is currently: ${self.chips:,.2f}\n&quot;) def check_for_blackjack(self): return len(self.hand) == 2 and self.hand_score() == 21 def check_for_split(self): if self.hand[0].value == self.hand[1].value: return validate_answer(&quot;Do you want to split your cards?: [y / n]: &quot;, yes_no) return False def wager(self): while True: self.print_balance() bet = input(f&quot;How much would you like to bet?: $&quot;) if not bet.isdecimal(): continue elif float(bet) &gt; self.chips: print(&quot;sorry, you dont have enough chips. Try again&quot;) else: self.bet = float(bet) self.remove_chips(float(bet)) break def added_wager(self): while True: self.print_balance() bet = input(f&quot;Enter additional wager. You may bet up to your original ${self.bet} or less: $&quot;) if not bet.isdecimal() or float(bet) &gt; self.bet: continue elif float(bet) &gt; self.chips: print(&quot;You dont have enough chips. Try again&quot;) else: self.bet_two = float(bet) self.remove_chips(float(bet)) break def confirm_double(self): return validate_answer(&quot;\nYou will only get 1 more card. Confirm you want to double down: [y / n]: &quot;, yes_no) def double_down(self, deck): self.added_wager() self.bet += self.bet_two self.visual_move(deck) if self.hand_score() &gt; 21: self.alive = False def apply_split(self, deck): if self.split_cards: self.added_wager() self.hand_two = Player(0, split_cards=True, bet=self.bet_two) transfer_card = self.remove_card() self.hand_two.add_card(transfer_card) self.hit(deck) self.hand_two.hit(deck) print(&quot;\nFirst Hand: &quot;) self.mini_card_visual() self.player_move(deck) print(&quot;\nSecond Hand: &quot;) self.hand_two.mini_card_visual() self.hand_two.player_move(deck) time.sleep(1) def visual_move(self, deck): self.hit(deck) if self.split_cards: self.mini_card_visual() else: self.card_visual() def player_move(self, deck): assert isinstance(deck, Deck) while True: if self.hand_score() &gt; 21 or self.has_blackjack: self.alive = False break if self.hand_score() == 21: break if len(self.hand) == 2: action = input(&quot;Would you like to hit, stand, or double-down? Enter [h, s, or d]: &quot;) else: action = input(&quot;Would you like to hit or stand: Enter [h or s]: &quot;) if action == 'd': if len(self.hand) == 2: if self.confirm_double(): self.double_down(deck) break if action == &quot;h&quot;: self.visual_move(deck) if action == &quot;s&quot;: break def compute_results(self, dealer): assert isinstance(dealer, Dealer) if self.alive and dealer.alive: if self.hand_score() &gt; dealer.hand_score(): print(&quot;WINNER!\n&quot;) self.profit = 2 elif self.hand_score() == dealer.hand_score(): print(&quot;PUSH!\n&quot;) self.profit = 1 else: print(&quot;LOSER! Dealer Wins\n&quot;) elif not self.alive: if self.has_blackjack: print(&quot;YOU HAVE BLACKJACK!\n&quot;) self.profit = 2.5 else: print(&quot;BUST! LOSER!\n&quot;) else: print(&quot;DEALER BUSTS. YOU WIN!\n&quot;) self.profit = 2 self.settle() def settle(self): self.add_chips(self.profit*self.bet) def reset(self): self.hand = [] self.alive = True self.split_cards = False self.profit = 0 self.bet, self.bet_two = 0, 0 class Dealer(Hand): def __init__(self): super().__init__() self.alive = True def deal_cards(self, deck): self.hit(deck) self.hit(deck) print_line('Dealer Cards') self.dealer_visual() def reset(self): self.hand = [] self.alive = True def card_reveal(self): print_line('Dealer Cards') time.sleep(1) self.card_visual() def dealer_move(self, deck): self.card_reveal() while True: if self.hand_score() in range(17, 22): return True if self.hand_score() &gt; 21: self.alive = False return False if self.hand_score() &lt; 17: self.hit(deck) time.sleep(1) self.card_visual() def dealer_visual(self): card_list = [] hidden_card = visuals.reg_hidden_card card_list.append(hidden_card) for card in self.hand[1:]: card_vis = visuals.reg_card_visual(card) card_list.append(card_vis) visuals.print_cards(card_list) time.sleep(1) def play_again(): if validate_answer(&quot;Would you like to play another round? [y / n]: &quot;, yes_no): clear() return True return False def print_line(word): print(f&quot;\n______________________[{word}]______________________________\n&quot;) def game(): print_line('WELCOME TO BLACKJACK!!') num_decks = 6 player_chips = 1_000 deck = Deck(num_decks) player = Player(player_chips) dealer = Dealer() deck.shuffle() while True: if player.chips == 0: print(&quot;You're out of money. Game Over&quot;) break print(f&quot;Percentage of shoe not yet dealt: {len(deck)/(52*num_decks):.2%}&quot;) if deck.is_shuffle_time(): deck.shuffle_time() player.wager() dealer.deal_cards(deck) player.deal_cards(deck) if not player.split_cards: player.player_move(deck) if player.alive: dealer.dealer_move(deck) player.compute_results(dealer) # PLAYER SPLIT CARDS else: if player.alive or player.hand_two.alive: dealer.dealer_move(deck) print(&quot;HAND ONE:&quot;) player.compute_results(dealer) print(&quot;HAND TWO:&quot;) player.hand_two.compute_results(dealer) # Any chips won by second hand: Add it to total balance player.chips += player.hand_two.chips player.print_balance() if play_again(): player.reset() dealer.reset() continue else: break print(&quot;Thanks for playing. Goodbye.&quot;) if __name__ == &quot;__main__&quot;: game() </code></pre> <p>Oh, and this is the <code>visuals.py</code> file (most of it):</p> <pre><code>&quot;&quot;&quot; Variety of ways to nicely dislay card representations Width of terminal may impact visual &quot;&quot;&quot; def print_cards(cardlist): for card in zip(*cardlist): print(' '.join(card)) def reg_card_visual(card): suits = &quot;Spades Diamonds Hearts Clubs&quot;.split() suit_symbols = ['♠','♦','♥','♣'] suit_pairs = dict(zip(suits, suit_symbols)) v = card.value s = suit_pairs[card.suit] visual = [ ' ╔════════════╗', f' ║ {v:&lt;5} ║', ' ║ ║', ' ║ ║', f' ║ {s:^3} ║', ' ║ ║', ' ║ ║', ' ║ ║', f' ║ {v:&gt;5} ║', ' ╚════════════╝' ] return visual def mini_card_visual(card): suits = &quot;Spades Diamonds Hearts Clubs&quot;.split() suit_symbols = ['♠','♦','♥','♣'] suit_pairs = dict(zip(suits, suit_symbols)) v = card.value s = suit_pairs[card.suit] visual = [ '╔══════╗', f'║ {v:&lt;3} ║', f'║ ║', f'║ {s:&gt;3} ║', '╚══════╝' ] return visual def large_card_visual(card): suits = &quot;Spades Diamonds Hearts Clubs&quot;.split() suit_symbols = ['♠','♦','♥','♣'] suit_pairs = dict(zip(suits, suit_symbols)) v = card.value s = suit_pairs[card.suit] visual = [ ' ┌─────────────────┐', f' │ {v:&lt;5} │', ' │ │', ' │ │', ' │ │', ' │ │', f' │ {s} │', ' │ │', ' │ │', ' │ │', ' │ │', ' │ │', f' │ {v:&gt;5} │', ' └─────────────────┘' ] return visual reg_hidden_card = [ ' ╔════════════╗', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ╚════════════╝' ] v, s = 'V', 'S' card_visuals = { 'small_card_vis' : [ '╔══════╗', f'║ {v:&lt;3} ║', f'║ {s:&gt;3} ║', f'║ ║', '╚══════╝' ], 'mini_card_vis' : [ '╔══════╗', f'║ {v:&lt;3} ║', '║ ║', f'║ {s:&gt;3} ║', '╚══════╝' ], 'thick_border_vis' : [ ' ╔════════════╗', f' ║ {v:&lt;5} ║', ' ║ ║', ' ║ ║', f' ║ {s:^3} ║', ' ║ ║', ' ║ ║', ' ║ ║', f' ║ {v:&gt;5} ║', ' ╚════════════╝' ], 'thin_border_vis' : [ ' ┌───────────┐', f' │ {v:&lt;5} │', ' │ │', ' │ │', ' │ │', f' │ {s} │', ' │ │', ' │ │', ' │ │', f' │ {v:&gt;5} │', ' └───────────┘' ] } # print_card(card_visuals['thick_border_vis']) hidden_cards = { 'mini_thick_hidden_card' : [ '╔══════╗', '║░░░░░░║', '║░░░░░░║', '║░░░░░░║', '╚══════╝' ], 'reg_thick_hidden_card' : [ ' ╔════════════╗', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ║░░░░░░░░░░░░║', ' ╚════════════╝' ], 'small_thin_hidden_card' : [ '┌────────┐', '│░░░░░░░░│', '│░░░░░░░░│', '│░░░░░░░░│', '│░░░░░░░░│', '│░░░░░░░░│', '└────────┘' ], 'reg_thin_hidden_card' : [ ' ┌───────────┐', ' │░░░░░░░░░░░│', ' │░░░░░░░░░░░│', ' │░░░░░░░░░░░│', ' │░░░░░░░░░░░│', ' │░░░░░░░░░░░│', ' │░░░░░░░░░░░│', ' │░░░░░░░░░░░│', ' │░░░░░░░░░░░│', ' │░░░░░░░░░░░│', ' └───────────┘' ], 'large_thin_hidden_card' : [ ' ┌─────────────────┐', ' │░░░░░░░░░░░░░░░░░│', ' │░░░░░░░░░░░░░░░░░│', ' │░░░░░░░░░░░░░░░░░│', ' │░░░░░░░░░░░░░░░░░│', ' │░░░░░░░░░░░░░░░░░│', ' │░░░░░░░░░░░░░░░░░│', ' │░░░░░░░░░░░░░░░░░│', ' │░░░░░░░░░░░░░░░░░│', ' │░░░░░░░░░░░░░░░░░│', ' │░░░░░░░░░░░░░░░░░│', ' │░░░░░░░░░░░░░░░░░│', ' │░░░░░░░░░░░░░░░░░│', ' └─────────────────┘' ] } # print_card(hidden_cards['reg_thick_hidden_card']) </code></pre> <p>Ex screenshots:</p> <p><a href="https://i.stack.imgur.com/wIJuR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wIJuR.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/1mDkz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1mDkz.png" alt="enter image description here" /></a></p>
[]
[ { "body": "<h2>system()</h2>\n<p>replace <code>os.system</code> with a call to <code>subprocess</code>, which for all intents and purposes replaces the former.</p>\n<h2>Type hints</h2>\n<pre><code>def validate_answer(question, choices):\n</code></pre>\n<p>can be</p>\n<pre><code>def validate_answer(question: str, choices: Sequence[str]) -&gt; str:\n</code></pre>\n<p>The <code>Sequence</code> is appropriate because you need <code>choices</code> to be both iterable and indexable.</p>\n<h2>Global variables</h2>\n<pre><code>yes_no = ['y', 'n']\n</code></pre>\n<p>can be</p>\n<pre><code>YES_NO = 'yn'\n</code></pre>\n<p>In other words, a string is itself a sequence of strings, each one character long.</p>\n<h2>Statics</h2>\n<p>These three:</p>\n<pre><code>values = [str(v) for v in range(2, 11)] + list('JQKA')\nsuits = &quot;Spades Diamonds Hearts Clubs&quot;.split()\nsuit_symbols = ['♠','♦','♥','♣']\n</code></pre>\n<p>should probably all be tuples, since it's expected that none of them should change.</p>\n<p>Also, for both values and suits, you should attempt to model them as <code>Enum</code>s. They have a fixed set of valid values.</p>\n<p>You re-declare these in <code>mini_card_visual</code>, <code>large_card_visual</code> etc. when you should not; just declare them once.</p>\n<h2>Don't lie to your user</h2>\n<pre><code> print(&quot;Reshuffling the Deck...\\n&quot;)\n time.sleep(1)\n print(&quot;Reshuffling the Deck...\\n&quot;)\n time.sleep(1)\n print(&quot;Reshuffling the Deck...\\n&quot;)\n time.sleep(1)\n</code></pre>\n<p>I don't have very many pet peeves when it comes to user interface design, but this is one of them.</p>\n<p>You're implying that during the sleep, something is actually happening, when it isn't. Don't lie to your user. Just output the message once, don't sleep, and do the <code>shuffle()</code>.</p>\n<h2>Set membership</h2>\n<pre><code>any(card.value == 'A' for card in self.hand)\n</code></pre>\n<p>is not bad. Another way to model this is</p>\n<pre><code>'A' in {card.value for card in self.hand}\n</code></pre>\n<p>Since the data are so small there won't really be an impact to performance either way.</p>\n<h2>Typo</h2>\n<p><code>sorry, you dont</code> -&gt; <code>sorry, you don't</code></p>\n<p>Similar for other instances of <code>dont</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:42:27.913", "Id": "480447", "Score": "0", "body": "Appreciate all the feedback. thankyou! Your comments about TypeHints, Global Variables, and Statics, Typos are noted and will make the changes. I'm not familiar with enums, but I will certainly look into. To avoid redeclaring the statics in the card_visuals how would I reference them? regarding lying to user, my intention was far from that, though if that's how it comes off, ill certainly change. given that its played in terminal, everything prints very fast, so time.sleep() was a simply a way to slow the literal printing to make it a more seem more fluid for user. bc it does reshuffle" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:45:17.127", "Id": "480448", "Score": "0", "body": "Sure! If the printing is so fast that the shuffling output is actually lost off-screen, one reasonable alternative is a `press any key to continue` prompt. Otherwise, it's best to simply trust your user and their ability to read text as it scrolls." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:45:47.687", "Id": "480449", "Score": "0", "body": "part(2). it does reshuffle, and restore deck to full size. but I appreciate your honest input. you mentioned subprocess. my clear() function was a way to clear the console, if the user decides to playagain, yet the game keeps running. is the way I did it outdated/ what advantage is calling to subprocess - genuinely curious. but again, thanks so much for reviewing. I will certainly take time to make changes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:48:21.000", "Id": "480450", "Score": "1", "body": "You can keep `clear`; just replace `os.system` with something like `subprocess.run`. For more information read https://docs.python.org/3/library/subprocess.html . Particularly, for the motivation behind replacement, see https://www.python.org/dev/peps/pep-0324/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:48:59.543", "Id": "480451", "Score": "2", "body": "A StackOverflow answer for the difference between `os.system` and `subprocess` [here](https://stackoverflow.com/a/4813571/8968906)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:56:38.890", "Id": "480458", "Score": "0", "body": "@Reinderien oh, interesting. great to know. thank you! the last question I had, and hope I'm not asking too much: in my player class, I used `assert` on a few methods, to ensure that method only be used if the argument is of a certain classtype. did I use that correctly? / is that good/bad implementation of it. I was recently reading about the idea of EAFP and I now realize, what I did might conflict with that principle, though I'm not sure. but again, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T17:02:20.207", "Id": "480461", "Score": "1", "body": "It's fairly reasonable, though that kind of check isn't always strictly necessary. It's much more important IMO to add type hints to the actual parameters to let callers know what the function expects them to pass." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T14:12:17.100", "Id": "480594", "Score": "0", "body": "@Linny and Reinderien I have since done my best to implement the advised changes: with the [followup being here](https://codereview.stackexchange.com/questions/244785/follow-up-blackjack-with-card-representation-visuals)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:22:39.763", "Id": "244723", "ParentId": "244714", "Score": "5" } }, { "body": "<h1><code>Deck.reset</code> bug</h1>\n<p>This function has no access to <code>num_decks</code>, so if you decide to call this function it will fail with a syntax error. A simple fix would be to define this as an instance variable in the constructor, i.e <code>self.num_decks</code>, and use that.</p>\n<h1><code>validate_answer</code></h1>\n<p>This function should be written like this:</p>\n<pre><code>from typing import List\n\ndef validate_answer(question: str, choices: List[str]) -&gt; bool:\n while answer := input(question)[0].lower():\n if answer in choices:\n return answer == choices[0]\n</code></pre>\n<p>This makes use of the <a href=\"https://www.python.org/dev/peps/pep-0572/\" rel=\"nofollow noreferrer\">walrus operator</a>, aka assignment expressions. This also fixes a bug. If a user enters &quot;N&quot; instead of &quot;n&quot;, this function rejects that input and asks again. It's better to lower the input and analyze it that way.</p>\n<p>For specific advice on type hints see <a href=\"https://codereview.stackexchange.com/users/25834/reinderien\">Reinderien</a>'s answer.</p>\n<h1>Misc whitespace</h1>\n<p>You have many places like</p>\n<pre><code>yes_no = ['y', 'n']\n</code></pre>\n<p>where there's extra whitespace. Try to keep one space before and after operators to make it readable without being extraneous.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:55:18.830", "Id": "480457", "Score": "0", "body": "Dude, I had no idea that PEP572 was implemented. This is a really cool thing to learn; thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T17:01:24.830", "Id": "480460", "Score": "0", "body": "thank you for taking the time to review! and oh wow, that's pretty neat. I wasn't aware of the walrus operator. additionally, thank you for spotting some errors that I managed to overlooked. will fix. Is type checking common practice/ encouraged? it certainly looks more readable; I imagine that's the goal?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:42:07.940", "Id": "244726", "ParentId": "244714", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T15:05:18.123", "Id": "244714", "Score": "14", "Tags": [ "python", "python-3.x", "object-oriented", "playing-cards", "classes" ], "Title": "Blackjack with card representation visuals" }
244714
<p>I'm posting my code for a LeetCode problem copied here. If you have time and would like to review, please do so. Thank you!</p> <blockquote> <h3>Problem</h3> <p>Implement the <code>StreamChecker</code> class as follows:</p> <ul> <li><code>StreamChecker(words)</code>: Constructor, init the data structure with the given words.</li> <li><code>query(letter)</code>: returns true if and only if for some k &gt;= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list.</li> </ul> <h3>Example:</h3> <pre><code>StreamChecker streamChecker = new StreamChecker([&quot;cd&quot;,&quot;f&quot;,&quot;kl&quot;]); // init the dictionary. streamChecker.query('a'); // return false streamChecker.query('b'); // return false streamChecker.query('c'); // return false streamChecker.query('d'); // return true, because 'cd' is in the wordlist streamChecker.query('e'); // return false streamChecker.query('f'); // return true, because 'f' is in the wordlist streamChecker.query('g'); // return false streamChecker.query('h'); // return false streamChecker.query('i'); // return false streamChecker.query('j'); // return false streamChecker.query('k'); // return false streamChecker.query('l'); // return true, because 'kl' is in the wordlist </code></pre> <h3>Note:</h3> <ul> <li><span class="math-container">\$1 \le \text{words.length} \le 2000\$</span></li> <li><span class="math-container">\$1 \le \text{words[i].length} \le 2000\$</span></li> <li>Words will only consist of lowercase English letters.</li> <li>Queries will only consist of lowercase English letters.</li> <li>The number of queries is at most 40000.</li> </ul> </blockquote> <h3>Code</h3> <pre><code>#include &lt;unordered_map&gt; #include &lt;string&gt; #include &lt;algorithm&gt; class Trie { std::unordered_map&lt;char, Trie*&gt; alphabet_map; bool is_word; public: Trie() { is_word = false; } // Inserts in the trie void insert(const std::string word) { if (word.length() == 0) { return; } Trie* temp_trie = this; for (auto letter : word) { if (temp_trie-&gt;alphabet_map.find(letter) != temp_trie-&gt;alphabet_map.end()) { temp_trie = temp_trie-&gt;alphabet_map[letter]; } else { temp_trie-&gt;alphabet_map[letter] = new Trie(); temp_trie = temp_trie-&gt;alphabet_map[letter]; } } temp_trie-&gt;is_word = true; } // Searches the word in the trie bool search(const std::string word) { if (word.length() == 0) { return false; } Trie* temp_trie = this; for (auto letter : word) { if (temp_trie-&gt;alphabet_map.find(letter) == temp_trie-&gt;alphabet_map.end()) { return false; } temp_trie = temp_trie-&gt;alphabet_map[letter]; if (temp_trie-&gt;is_word) { return true; } } return temp_trie-&gt;is_word; } }; class StreamChecker { Trie trie_stream; std::string string_stream = &quot;&quot;; int word_length = 0; public: StreamChecker(const std::vector&lt;std::string&gt;&amp; words) { for (auto word : words) { std::reverse(word.begin(), word.end()); word_length = std::max(word_length, (int) word.length()); trie_stream.insert(word); } } bool query(const char letter) { string_stream = letter + string_stream; if (string_stream.length() &gt; word_length) { string_stream.pop_back(); } return trie_stream.search(string_stream); } }; </code></pre> <h3>Reference</h3> <p>LeetCode has a template for answering questions. There is usually a class named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename. For this question, the template is:</p> <pre><code>class StreamChecker { public: StreamChecker(vector&lt;string&gt;&amp; words) { } bool query(char letter) { } }; /** * Your StreamChecker object will be instantiated and called as such: * StreamChecker* obj = new StreamChecker(words); * bool param_1 = obj-&gt;query(letter); */ </code></pre> <ul> <li><p><a href="https://leetcode.com/problems/stream-of-characters/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/stream-of-characters/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> <li><p><a href="https://en.wikipedia.org/wiki/Trie" rel="nofollow noreferrer">Trie</a></p> </li> </ul>
[]
[ { "body": "<h2>Template</h2>\n<p>You can't rename functions; but can you change their signature? i.e.</p>\n<pre><code>StreamChecker(vector&lt;string&gt;&amp; words) {\n</code></pre>\n<p>would be better as</p>\n<pre><code>StreamChecker(const vector&lt;string&gt; &amp;words) {\n</code></pre>\n<p>Similarly,</p>\n<pre><code>void insert(const std::string word) {\n</code></pre>\n<p>should be</p>\n<pre><code>void insert(const std::string &amp;word) {\n</code></pre>\n<p>The same for <code>search</code>.</p>\n<p>Also, the <code>const</code> in</p>\n<pre><code>bool query(const char letter) {\n</code></pre>\n<p>isn't as important, since <code>letter</code> is itself an immutable letter. It would be more important if this were a reference or pointer.</p>\n<p>Finally, your <code>search</code> method does not modify members, so:</p>\n<pre><code>bool search(const std::string &amp;word) const {\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:08:35.593", "Id": "244731", "ParentId": "244718", "Score": "3" } }, { "body": "<p>In addition to what Reinderien said:</p>\n<h1>Move <code>class Trie</code> inside <code>class StreamChecker</code></h1>\n<p>Your <code>class Trie</code> is not a generic class, but rather a specialized trie implementation specifically for <code>StreamChecker</code>. You can move it inside <code>class StreamChecker</code>, so that it is clear that they belong to each other, and so that <code>class Trie</code> does not pollute the global namespace:</p>\n<pre><code>class StreamChecker {\n class Trie {\n ...\n };\n\n Trie trie_stream;\n ...\n};\n</code></pre>\n<h1>Store <code>Trie</code>s by value</h1>\n<p>Your <code>class Trie</code> has a memory leak: it calls <code>new Trie()</code>, but there is no corresponding <code>delete</code> in sight. You could write a destructor that iterates over <code>alphabet_map</code> and calls <code>delete</code> on the values, or even use <code>std::unique_ptr</code> to track ownership of the memory, but there is no need for this at all. After all, <code>std::map</code> already takes care of managing the memory necessary to store the keys and values. So remove that pointer and write:</p>\n<pre><code>class Trie {\n std::unordered_map&lt;char, Trie&gt; alphabet_map;\n ...\n void insert(const std::string &amp;word) {\n if (word.empty()) {\n return;\n }\n\n Trie *temp_trie = this;\n\n for (auto letter: word) {\n temp_trie = &amp;temp_trie-&gt;alphabet_map[letter];\n }\n\n temp_trie-&gt;is_word = true;\n }\n};\n</code></pre>\n<p>Note that in <code>search()</code> you need to do similar modifications, but there you do need to explicitly check whether the <code>letter</code> is present in the <code>alphabet_map</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:10:23.003", "Id": "244741", "ParentId": "244718", "Score": "3" } } ]
{ "AcceptedAnswerId": "244731", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T15:54:49.150", "Id": "244718", "Score": "4", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 1032: Stream of Characters" }
244718
<p>I wrote a function to check if a nested object contains the key-value pair matched as parameter as following.</p> <pre><code>eq: const obj ={ &quot;a&quot;:{ &quot;b&quot;:{ &quot;c1&quot;:[&quot;1&quot;,&quot;2&quot;], &quot;c2&quot;:&quot;3&quot; }, &quot;b2&quot;:&quot;values&quot;, &quot;b3&quot;: {&quot;c5&quot;: &quot;v&quot;}, }, &quot;a2&quot;:[&quot;v1&quot;,&quot;v2&quot;], &quot;a3&quot;:&quot;v1&quot; } checkNestedObjectByKeyValue(obj, &quot;a3&quot;, &quot;v1&quot;) // true checkNestedObjectByKeyValue(obj, &quot;a3&quot;, &quot;v2&quot;) // false checkNestedObjectByKeyValue(obj, &quot;a2&quot;, [&quot;v1&quot;,&quot;v2&quot;]) // true checkNestedObjectByKeyValue(obj, &quot;a3&quot;, &quot;v1&quot;) // true checkNestedObjectByKeyValue(obj, &quot;b3&quot;, {&quot;c5&quot;: &quot;v&quot;}) // true </code></pre> <pre><code>function checkNestedObjectByKeyValue( obj: Record&lt;string, any&gt;, objKey: string, objValue: string | Array&lt;string&gt; ): boolean { if (typeof obj !== 'object') return false; if (obj.hasOwnProperty(objKey)) { return JSON.stringify(obj[objKey]) === JSON.stringify(objValue) } for (const value of Object.values(obj)) { if (checkNestedObjectByKeyValue(value, objKey, objValue)) return true } return false } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:59:42.947", "Id": "480494", "Score": "0", "body": "updated. code totally works" } ]
[ { "body": "<p>Based on your description of the function, I would expect this test to return <code>true</code>, but your implementation returns <code>false</code>. So, either your description is unclear, or your implementation is buggy.</p>\n<pre><code>const obj ={\n &quot;a&quot;:{\n &quot;b&quot;:{\n &quot;a3&quot;:&quot;v2&quot;,\n &quot;c1&quot;:[&quot;1&quot;,&quot;2&quot;],\n &quot;c2&quot;:&quot;3&quot;\n },\n &quot;b2&quot;:&quot;values&quot;,\n &quot;b3&quot;: {&quot;c5&quot;: &quot;v&quot;},\n },\n &quot;a2&quot;:[&quot;v1&quot;,&quot;v2&quot;],\n &quot;a3&quot;:&quot;v1&quot;\n}\ncheckNestedObjectByKeyValue(obj, &quot;a3&quot;, &quot;v2&quot;) // false, but I would expect true\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:34:18.833", "Id": "480512", "Score": "0", "body": "we have \"a3\": \"v1\" as first level that is why it return false. not sure how i can handle that" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:28:07.350", "Id": "244744", "ParentId": "244719", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T15:58:25.153", "Id": "244719", "Score": "1", "Tags": [ "typescript" ], "Title": "Test if a key-value pair exists in nested object in Typescript" }
244719
<p>I built the Set Matrix Zeroes algorithm in JavaScript. I have a lot of loops in my code, so was wondering if there is a better way to implement this algorithm.</p> <p>Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.</p> <p>I loop through the matrix and when I find a 0, I set its entire row and column to a flag ('X'). I do not set 'X' if the position is a 0 because I might need to check this position in the future. At the end I replace all the 'X' to 0.</p> <pre><code> var setZeroes = function(matrix) { if(matrix === null || matrix.length === 0) return []; for(let i=0; i&lt;matrix.length; i++){ for(let j=0; j&lt;matrix[i].length; j++){ if(matrix[i][j] === 0){ setFlag(matrix, i, j); } } } for(i=0; i&lt;matrix.length; i++){ for(j=0; j&lt;matrix[i].length; j++){ if(matrix[i][j] === 'X') matrix[i][j] = 0; } } }; const setFlag = function(matrix, i, j) { matrix[i][j] = 'X'; let tempI = i+1; while(tempI &lt; matrix.length){ if(matrix[tempI][j] !== 0) matrix[tempI][j] = 'X'; tempI++; } tempI = i-1; while(tempI &gt;= 0){ if(matrix[tempI][j] !== 0) matrix[tempI][j] = 'X'; tempI--; } let tempJ = j+1; while(tempJ &lt; matrix[i].length){ if(matrix[i][tempJ] !== 0) matrix[i][tempJ] = 'X'; tempJ++; } tempJ = j-1; while(tempJ &gt;= 0){ if(matrix[i][tempJ] !== 0) matrix[i][tempJ] = 'X'; tempJ--; } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>From a short review;</p>\n<ul>\n<li>You probably want to encapsulate <code>if(matrix === null || matrix.length === 0)</code> into an <code>isValidMatrix</code> function for re-use</li>\n<li>I would drop the whole <code>i</code>/<code>j</code> thing and go for variables named after <code>row</code> and <code>col</code></li>\n<li>I would collect all the rows and columns with a 0 in one set of loops, and then clear the matrix based on the collected rows and columns in another set of loops.</li>\n<li><code>let</code> only declares in the block, so the <code>for(i=0; i&lt;matrix.length; i++){</code> creates a global <code>i</code></li>\n<li>I much prefer <code>function setFlag(matrix, i, j) {</code> over <code>const setFlag = function(matrix, i, j) {</code></li>\n</ul>\n<p>This is my current proposal, I did not test it, but you should get the gist of it;</p>\n<pre><code>//This does not catch everything, but it'll do\nfunction isValidMatrix(matrix){\n return !(!matrix || !matrix.length);\n}\n\nfunction setZeroes(matrix) {\n \n if(!isValidMatrix(matrix))\n return [];\n \n const rows = [], cols = [];\n \n for(let row = 0; row &lt; matrix.length; row++){\n for(let col = 0; col &lt; matrix[row].length; col++){\n if(matrix[row][col] === 0){\n rows.push(row);\n cols.push(col);\n }\n }\n }\n \n for(let row = 0; row &lt; matrix.length; row++){\n for(let col = 0; col &lt; matrix[row].length; col++){\n if(rows.includes(row) || cols.includes(col)){\n matrix[row][col] = 0;\n }\n }\n }\n}\n</code></pre>\n<p>For further refinement, <code>rows</code> and <code>cols</code> might/will get multiple times the same value, so to deal with that gracefully you should use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Sets</a> for that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-07T13:25:24.027", "Id": "245130", "ParentId": "244724", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:23:41.703", "Id": "244724", "Score": "4", "Tags": [ "javascript" ], "Title": "Extend zeroes in a matrix" }
244724
<p>I found out that I can increase the value of a variable inside an if statement like so:</p> <pre><code>int limit = 100; int nrCopies = 2; int maxValue = 100; for(int i = 0; i &lt; limit; ++i) { if((nTotal += (nrCopies)) &gt; maxValue) break; } </code></pre> <p>This works, and I became acostumed to do this, but I want to know if it is a good practice to do so, since I don't want to get bad habits unnecessarily</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T17:26:18.573", "Id": "480470", "Score": "0", "body": "This is a generic best practice question. This is not particularly helpful as a Python programmer would say no, but a JavaScript programmer would say yes. Ultimately we don't have enough context to know if this is good or not." } ]
[ { "body": "<p>I would say this is quite questionable.</p>\n<p>Imagine you never saw this code before, and are trying to understand it, would this make it easier to understand or harder? I say harder.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:09:54.967", "Id": "244732", "ParentId": "244725", "Score": "3" } }, { "body": "<p>I agree with @GeorgeBarwood answer, full stop.</p>\n<p><a href=\"https://codereview.stackexchange.com/questions/244725/incrementing-values-inside-an-if-statement#comment480470_244725\">Next note @ Peilonrayz comment</a> <em>...we don't have enough context</em></p>\n<p><strong>If the contex or intent is</strong> to emphasize &quot;Increment until reaching the max value&quot;, or better: &quot;make this many copies&quot;, then use a <code>while</code> loop.</p>\n<pre><code>int total = 0;\n\nwhile (total &lt;= maxValue) {\n total += nCopies;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:58:23.113", "Id": "244749", "ParentId": "244725", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T16:29:36.593", "Id": "244725", "Score": "1", "Tags": [ "c#" ], "Title": "Incrementing Values inside an if statement" }
244725
<p>I am using LMFIT to fit the transfer function of a large impedance network to measured data, this involves some ~20 parameters and ~40 lines of (naively implemented) computations.</p> <p>there are a lot of computations that go into computing this transfer function, and many of those do not need to be repeated if the parameters that they use have not changed.</p> <p>I have noticed that LMFIT does not vary all parameters all the time, it only varies a few of the ~20 odd parameters at a time, so I would like to rewrite my model to detect which parameters have changed, and then only do the computations that are needed.</p> <p>Ideally I would have liked to not have to &quot;detect&quot; what parameters have changed and to implement this manually, but to instead have LMFIT handle it (know what computations to re-do depending on what parameters have been changed), but I have not been able to find a way to do this with the features already implemented in LMFIT.</p> <p>It currently takes ~1.5 hours to do the fit, and my model will only get more complicated with time, so I really need a solution with absolute minimal overhead!. Keep in mind that is is an attempt to greatly reduce computation time, not increase it.</p> <p>At first I thought that I would have implemented this in an afternoon, because I didn't really think that if would be that complicated/hard to do, now I am here hoping that someone (perhaps with experience in doing a similar thing) can help me with suggestions as to how to go about this, as it turned out to be a lot harder than I had expected.</p> <p>All my computations are currently hard-coded, I did that out of fear of overhead.</p> <pre><code>z_x = 1234.56 def model(s, r1, l1, r2, l2, c2, r3, l3, r4, l4, c4, r5, l5, c5, r6, l6, r7, l7, c7, r8, l8, r9, l9, c9, r10, l10, c10, r11, l11, r12, l12, c12, v_source): z1 = r1 + l1 * s z2 = r2 + l2 * s + 1 / (c2 * s) z3 = r3 + l3 * s z4 = r4 + l4 * s + 1 / (c4 * s) z5 = r5 + l5 * s + 1 / (c5 * s) z12 = r12 + l12 * s + 1 / (c12 * s) z_a = 1/(1/(z1 + 1 / (1/z2 + 1 / (z3 + 1 / (1/z4 + 1/z5)))) + 1/z12) z6 = r6 + l6 * s z7 = r7 + l7 * s + 1 / (c7 * s) z8 = r8 + l8 * s z9 = r9 + l9 * s + 1 / (c9 * s) z10 = r10 + l10 * s + 1 / (c10 * s) z11 = 1 / (1/z7 + 1/(z8 + 1 / (1/z9 + 1/z10))) ratio = z11 / (z6 + z11) z_b = z6 * ratio + r11 + l11 * s v_b = v_source * ratio z_c = z_a + z_b return 20*np.log10(np.abs(v_source * z_x / (z_a + z_x))),\ 20*np.log10(np.abs(v_b * z_x / (z_b + z_x))),\ 20*np.log10(np.abs(v_b * z_x / (z_c + z_x))) </code></pre> <p>What I have &quot;tried&quot; or &quot;considered&quot;;</p> <ul> <li>Somehow putting all input parameters in a np.array, compare it to the previous np.array of parameters to get an array of True/False for changed or not-changed, and then use this array as a &quot;mask&quot; whenever doing any computations on data in the array.</li> </ul> <p>I have been working on implementing this approach, the main problem is that it makes the code so unreadable that before I make it to the end I am unable to read my own code and so fail to get it working.</p> <ul> <li>Wrapping all the math in custom class objects called &quot;Expr&quot;, &quot;Add&quot;, &quot;Sub&quot; etc. (like sympy and mpmath does) and then have each resulting expression object be evaluated in the last moment, and have the expression objects contain their previous value and return that if nothing has changed.</li> </ul> <p>This is a solution, but not one that I am satisfied with, both because I don't want to have to write and to maintain my own library of expression wrappers etc. and because I fear the impact of the overhead that this could cause if I am not careful.</p> <ul> <li>Completely hard coded solution (If a != a_previous: ..., if b != b_previous: ...), as you may understand, this is not a solution that I am satisfied with either.</li> </ul> <p><strong>So the question is; <em>Given the code example above, what is the most efficient method that you can come up with for only doing each of the computations whenever a value that is used in that computation has changed.</em></strong></p> <p><strong>Or alternatively; <em>If you have experience with a similar situation when using LMFIT, how did you solve it?</em></strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:39:47.200", "Id": "480488", "Score": "0", "body": "@Reinderien Thank you for the comment, I added \"..when curve-fitting with LMFIT\" to include the application, I think this generalizes well to \"How to avoid repeating computations\" though, so I still think that is a good title, don't you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:44:16.280", "Id": "480490", "Score": "0", "body": "@Reinderien Read it, that didn't make me think any less of my original title." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:59:59.793", "Id": "480495", "Score": "0", "body": "Much better; thanks :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:00:52.430", "Id": "480496", "Score": "0", "body": "@Reinderien You're welcome, appreciate your guidance ;)." } ]
[ { "body": "<h2>Vectorization</h2>\n<p>You already use Numpy, so this should not be too difficult for you.</p>\n<p>For a set of calculations such as</p>\n<pre><code>z2 = r2 + l2 * s + 1 / (c2 * s)\nz4 = r4 + l4 * s + 1 / (c4 * s)\nz5 = r5 + l5 * s + 1 / (c5 * s)\nz7 = r7 + l7 * s + 1 / (c7 * s)\nz9 = r9 + l9 * s + 1 / (c9 * s)\n</code></pre>\n<p>Put capacitances 2, 4, 5, 7, 9 all into one <code>ndarray</code>, and the same for the corresponding resistances and inductances. Then,</p>\n<pre><code>z24579 = r24579 + l24579*s + 1/c24579/s\n</code></pre>\n<p>Unless you can think of a better name than what I've shown. This will both execute more quickly and require fewer lines of code.</p>\n<h2>Admittance</h2>\n<p>Since you have lines like this:</p>\n<pre><code>z_a = 1/(1/(z1 + 1 / (1/z2 + 1 / (z3 + 1 / (1/z4 + 1/z5)))) + 1/z12)\n</code></pre>\n<p>Consider putting all of your impedances in one vector and reciprocating it so that you get a vector of admittances. You could then unpack the vector to <code>a1</code>, <code>a2</code>, etc. for the purposes of this calculation.</p>\n<h2>Result caching</h2>\n<blockquote>\n<p>I would like to rewrite my model to detect which parameters have changed, and then only do the computations that are needed</p>\n</blockquote>\n<p>This is what <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"nofollow noreferrer\"><code>lru_cache</code></a> has specifically been designed to do. It is very (very) easy to use - try prepending <code>@lru_cache</code> and see if that gets you somewhere.</p>\n<p>To benefit from this, you will probably have to split up your current function into three or four functions, since it is likely that the optimizer will modify at least some variables; so you will need partial caching. Each of the subroutines would need its own <code>@lru_cache</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:14:30.123", "Id": "480500", "Score": "0", "body": "Great answer, thx!. This is also the primary solution that I have been thinking about, and working on/experimenting with, and you make a good point about reciprocating all the impedances at once.. But you don't really address the primary element in the question which is; \"How do I avoid repeating the computations when the parameters have not changed?\". Doing it the way you suggest makes it easier to carry the change around with the calculations in a separate array and perhaps use that as a mask, I still would like a concrete suggestion as to how to do that though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:29:28.160", "Id": "480507", "Score": "0", "body": "Edited. As with most things Python, there is a built-in library for this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:31:27.050", "Id": "480509", "Score": "0", "body": "Accepted. Perfect thx! Exactly what I need!. I thought that there aught to be a \"common way\" in python, I just didn't know how :)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:45:18.843", "Id": "480518", "Score": "0", "body": "..While it is a very useful answer, I just realized that the two suggestions; Vectorization and using lru_cache are mutually exclusive. Why? because model will almost never be called with all the same arguments. Only some of the computations inside the function should be avoided at times, never the entire function, this means that to use lru_cache I will have to split the computations into smaller functions (a LOT of smaller functions) and that makes the vectorization approach impossible. Or have I misunderstood something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:46:26.637", "Id": "480520", "Score": "1", "body": "Read the last paragraph in my latest edit :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:05:38.067", "Id": "244740", "ParentId": "244734", "Score": "1" } } ]
{ "AcceptedAnswerId": "244740", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:28:00.983", "Id": "244734", "Score": "3", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Curve-fitting the transfer-function of an impedance network with LMFIT" }
244734
<p>This script was previously reviewed here: <a href="https://codereview.stackexchange.com/questions/244387/send-http-request-for-each-row-in-excel-table-part-1">Send HTTP request for each row in Excel table (Part 1)</a></p> <p>I've made the changes that were suggested in the Code Review answers as well as added a few of my own.</p> <p>The code is quite a bit different now. Are there any more improvements that should be made?</p> <hr /> <blockquote> <p>Description:</p> <ol> <li>A custom function concatenates columns with parameters into the <code>Concatenated Variables</code> column.</li> <li>Loops through each row in the table where <code>Load? = y</code></li> <li>Sends an HTTP request to an external system using the value in the <code>URL</code> column.</li> <li>Returns a message (created, updated, or problem/error) and stores it in the <code>Message</code> column.</li> </ol> <p><a href="https://i.stack.imgur.com/mpBI2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mpBI2.png" alt="enter image description here" /></a></p> </blockquote> <hr /> <p>New code:</p> <pre><code>Option Explicit Public Const tblName = &quot;tblData&quot; Public Const colNameLoad = &quot;Load?&quot; Public Const colNameMessage = &quot;Message&quot; Public Const colNameURL = &quot;URL&quot; Public Const colNameTimestamp = &quot;Message Timestamp&quot; Function CodeName() As Worksheet Set CodeName = DataSheet End Function Public Sub LoadRecords() Application.CalculateFull Dim message As String, response As String Dim n As Long 'Keep an eye on unecessary calls to the ConcatVars function. With CodeName.ListObjects(tblName) .ListColumns(colNameMessage).Range.Interior.Color = rgbWhite .ListColumns(colNameMessage).Range.Font.Color = rgbLightGrey For n = 1 To .ListRows.Count If UCase(.ListColumns(colNameLoad).DataBodyRange(n).Value) = &quot;Y&quot; Then response = GetHTTP(.ListColumns(colNameURL).DataBodyRange(n).Value) .ListColumns(colNameMessage).DataBodyRange(n) = response .ListColumns(colNameMessage).DataBodyRange(n).Font.Color = rgbBlack .ListColumns(colNameTimestamp).DataBodyRange(n) = Now() With .ListColumns(colNameMessage).DataBodyRange(n) message = Left(response, 7) .Interior.Color = Switch(message = &quot;Created&quot;, rgbLightGreen, message = &quot;Updated&quot;, rgbSkyBlue, message = &quot;Problem&quot;, rgbYellow, True, rgbOrangeRed) End With End If Next End With End Sub Public Function GetHTTP(ByVal url As String) As String On Error GoTo ConnectionError: With CreateObject(&quot;MSXML2.XMLHTTP&quot;) .Open &quot;GET&quot;, url, False: .Send GetHTTP = VBA.StrConv(.responseBody, vbUnicode) End With On Error GoTo 0 Exit Function ConnectionError: GetHTTP = &quot;Problem with URL or server: &quot; &amp; Err.Number &amp; &quot; &quot; &amp; Err.Description End Function Function ConcatVars(RowNum As Integer) As String Dim Column As ListColumn Dim s As String For Each Column In CodeName.ListObjects(tblName).ListColumns If Column.Name Like &quot;f_*&quot; Then s = s &amp; IIf(Len(s) &gt; 0, &quot;&amp;&quot;, &quot;&quot;) _ &amp; Mid(Column.Name &amp; &quot;=&quot; &amp; Column.Range.Cells(RowNum).Value, 3) End If Next ConcatVars = s End Function </code></pre> <hr /> <p>I have a follow-up question here: <a href="https://codereview.stackexchange.com/questions/244803/create-or-update-record-via-http-request">Create or update record via HTTP request </a> (Python/Jython).</p>
[]
[ { "body": "<p>Your code is pretty solid. I so have a couple of minor tweaks.</p>\n<blockquote>\n<pre><code>Function CodeName() As Worksheet\nSet CodeName = DataSheet\nEnd Function\n</code></pre>\n</blockquote>\n<p>This function is just adding a layer obfuscation. You should just change the worksheets code name.</p>\n<ul>\n<li><kbd>Ctrl</kbd> + <kbd>R</kbd> will Open the Folder Explorer</li>\n<li><kbd>Alt</kbd> + <kbd>F4</kbd></li>\n</ul>\n<p>From here you can change the Worksheet's Name property.</p>\n<p><a href=\"https://i.stack.imgur.com/2OjXH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2OjXH.png\" alt=\"Change the Worksheets Codename\" /></a></p>\n<p>Combining lines should be avoided. It detracts from the readability of the code. I am not opposed to declaring a variable and initiating its value in one line but only because you are allowed to assign values when declaring variables in most other languages.</p>\n<p>Dim Target as Range: Set Target = Sheet1.Range(&quot;A1&quot;)</p>\n<p>Here you are combing two actions into a single line. Not only does it make it harder to read but it may run into problems later on when you are writing similar code.</p>\n<blockquote>\n<p>.Open &quot;GET&quot;, url, False: .Send</p>\n</blockquote>\n<p>Consider for instance that weeks down the you are having problems writing a new function because you forgot to <code>.Send</code> your request. So what do you do? You reference your code base. Combing the <code>.Open</code> and <code>.Send</code> request into one line makes it hard to distinguish the ↑code above↑ from the ↓code below↓.</p>\n<blockquote>\n<p>.Open &quot;GET&quot;, url, False</p>\n</blockquote>\n<p>Although you never asked about speed I think its worth mentioning.</p>\n<p>Adding <code>Application.ScreenUpdating = False</code> to the beginning of your code will make it run considerably faster.</p>\n<p>Setting the <code>varAsync</code> parameter of the <code>MSXML2.XMLHTTP.Open()</code> method to True will allow the rest of the code to run while the HTTP <code>XMLHTTP.Request()</code> is processing. This will allow you to create more connections. Having 50 or more connections processing at once will greatly sped up the code.</p>\n<blockquote>\n<p>Sub open(bstrMethod As String, bstrUrl As String, [varAsync],\n[bstrUser], [bstrPassword])</p>\n</blockquote>\n<hr />\n<p><a href=\"https://i.stack.imgur.com/5RHEN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5RHEN.png\" alt=\"Object Browser\" /></a></p>\n<p>In my answers to the questions below I create a connection pool. I initiate the pool with x number of connections. As the requests are completed the newly freed connection is given a new request.</p>\n<p>Shameless plug:</p>\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/a/210404/171419\">Data scraping from Internet with Excel-VBA</a></li>\n<li><a href=\"https://codereview.stackexchange.com/a/196922/171419\">Retrieve data from eBird API and create multi-level hierarchy of locations</a></li>\n</ul>\n<p>In truth, setting up a connection pool, is probably over kill. But it is nice to know that it can be done in case you every need the extra speed boast.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T18:18:03.737", "Id": "480616", "Score": "0", "body": "For what it's worth, I have a follow-up question here: [Create or update record via HTTP request](https://codereview.stackexchange.com/questions/244803/create-or-update-record-via-http-request)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T22:11:50.280", "Id": "244756", "ParentId": "244736", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T18:36:31.457", "Id": "244736", "Score": "2", "Tags": [ "vba", "excel", "error-handling", "http" ], "Title": "Part 2: Send HTTP request for each row in Excel table" }
244736
<p>I started studying programming in January of this year and found a free online course that teaches Ruby. Below is my solution to the Eight Queens problem.</p> <p>I wanted my solution to be able to return any valid n-queens puzzle solution in a non-specific order.</p> <p>I'm looking for feedback such as:</p> <ol> <li>On the continuum of good or bad, where do you think my code lies?</li> <li>What are one or two things I should be working on or focusing on becoming more familiar with?</li> </ol> <pre><code>require 'set' class EightQueens attr_reader :invalid_pos, :queen_pos attr_accessor :grid def initialize(n) @grid = Array.new(n) { Array.new(n, '_') } @invalid_pos = Set.new @queen_pos = Set.new end def solve until @queen_pos.size == self.size + 1 random_pos = self.pick_random_pos row = random_pos[0] col = random_pos[1] if @grid[row][col] != 'Q' &amp;&amp; open_move?(random_pos, self.size ) self.place_queen(random_pos) @queen_pos &lt;&lt; random_pos elsif @grid[row][col] == 'Q' || !open_move?(random_pos, self.size) @invalid_pos &lt;&lt; random_pos end if @invalid_pos.length == self.full_grid_count - @grid.length self.reset_grid @invalid_pos.clear @queen_pos.clear end end puts 'Eight Queens puzzle solved, observe board.' self.print return true end def size @grid.length - 1 end def full_grid_count count = 0 @grid.each { |row| count += row.count } count end def reset_grid @grid.map! do |row| row.map! do |el| el = '_' end end end def pick_random_pos idx1 = rand(0...@grid.length) idx2 = rand(0...@grid.length) [ idx1, idx2 ] end def print @grid.each do |row| puts row.join(' ') end end def open_move?(position, grid_size) row = position[0] col = position[1] return false if queen_in_col?(col) || queen_in_row?(row) || queen_in_diagonal?(position, grid_size) true end def []=(pos, val) row, col = pos @grid[row][col] = val @diag_check_start_points = { 0=&gt;[0,0]} end def place_queen(pos) row, col = pos @grid[row][col] = 'Q' end def is_queen?(pos) row, col = pos @grid[row][col] == 'Q' end def queen_in_row?(row) @grid[row].any? { |pos| pos == 'Q' } end def queen_in_col?(col) transposed = @grid.transpose transposed[col].any? { |pos| pos == 'Q' } end def queen_in_diagonal?(position, n) all_diagonals = (right_lower_diagonal(position, n) + right_upper_diagonal(position, n) + left_lower_diagonal(position, n) + left_upper_diagonal(position, n)) all_diagonals.any? { |pos| is_queen?(pos) } end def right_lower_diagonal(position, n) row = position[0] col = position[1] diagonals = [] until row == n || col == n diagonals &lt;&lt; [ row += 1, col += 1 ] end diagonals end def right_upper_diagonal(position, n) row = position[0] col = position[1] diagonals = [] until row == 0 || col == n diagonals &lt;&lt; [ row -= 1, col += 1 ] end diagonals end def left_upper_diagonal(position, n) row = position[0] col = position[1] diagonals = [] until row == 0 || col == 0 diagonals &lt;&lt; [ row -= 1, col -= 1 ] end diagonals end def left_lower_diagonal(position, n) row = position[0] col = position[1] diagonals = [] until row == n || col == 0 diagonals &lt;&lt; [ row += 1, col -= 1 ] end diagonals end end </code></pre>
[]
[ { "body": "<blockquote>\n<p>On the continuum of good or bad, where do you think my code lies?</p>\n</blockquote>\n<p>The Eight Queens puzzle is already some advanced programming and if we consider that you just started programming ~6 months ago it is great that you came up with a working solution.</p>\n<p>I think it is a clever approach to store the valid and invalid position in a set which is an efficient way for look up.</p>\n<p>However, there is of course room for some improvements.</p>\n<blockquote>\n<p>What are one or two things I should be working on or focusing on becoming more familiar with?</p>\n</blockquote>\n<p>I think you should focus on object oriented design as you basically just have one class which does everything and is quite hard to understand and change.</p>\n<p>So good candidates to extract into classes are methods with the same parameters and / or body. If we look at your code, all the <code>_diagonal</code> methods are good candidates.</p>\n<h1>Diagonal</h1>\n<pre class=\"lang-rb prettyprint-override\"><code>class Diagonal\n def initialize(position, size, delta)\n @row, @column = position\n @row_delta, @column_delta = delta\n @size = size\n end\n\n def all\n [].tap do |result|\n result &lt;&lt; update_position until border_reached?\n end\n end\n\n def self.for(position, size)\n Diagonal.new(position, size, [-1, -1]).all +\n Diagonal.new(position, size, [1, 1]).all +\n Diagonal.new(position, size, [-1, 1]).all +\n Diagonal.new(position, size, [1, -1]).all\n end\n\n private\n\n attr_reader :row, :column, :row_delta, :column_delta, :size\n\n def update_position\n [\n update_row,\n update_column\n ]\n end\n\n def update_row\n @row += row_delta\n end\n\n def update_column\n @column += column_delta\n end\n\n def border_reached?\n row.zero? ||\n column.zero? ||\n row == size ||\n column == size\n end\nend\n</code></pre>\n<p>So we now DRYed this up a little bit and reuse the <code>Diagonal</code> class and just pass in the different deltas depending if it's upper right/left or lower right/left. Note that the abort function <code>border_reached?</code> is basically the same for all diagonals too.</p>\n<p>We can use this class now with <code>Diagonal.for([1,1], 8).any?</code> to get all diagonals for position 1,1 in a 8 sized grid.</p>\n<h1>GridPrinter</h1>\n<p>We could also extract the grid printing like this</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class ConsolePrinter\n def initialize(grid)\n @grid = grid\n end\n\n def print\n grid.each do |row|\n puts row.join(' ')\n end\n end\n\n private\n\n attr_reader :grid\nend\n</code></pre>\n<p>You might wonder why we want to extract only 3 lines of code but it makes the code a lot more extensible. For instance, if we want to reuse your code on a website, we can implement a <code>HtmlPrinter</code> which just prints the grid as HTML code.</p>\n<h2>Move</h2>\n<p>We can now also extract a <code>Move</code> or <code>ValidMove</code> class. Something like this</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class Move\n def initialize(position, grid)\n @row, @column = position\n @grid = grid\n end\n\n def valid?\n !invalid?\n end\n\n def invalid?\n queen_in_col? || queen_in_row? || queen_in_diagonal?\n end\n\n private\n\n attr_reader :row, :column, :grid\n\n def size\n grid.length - 1\n end\n\n def queen_in_row?\n grid[row].any? { |pos| pos == 'Q' }\n end\n\n def queen_in_col?\n transposed = grid.transpose\n transposed[column].any? { |pos| pos == 'Q' }\n end\n\n def queen_in_diagonal?\n Diagonal.for([row, column], size).any? { |pos| queen?(pos) }\n end\n\n def queen?(pos)\n row, col = pos\n grid[row][col] == 'Q'\n end\nend\n</code></pre>\n<h1>Grid</h1>\n<p>And finally a <code>Grid</code> class.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class Grid\n def initialize(n, printer = GridPrinter)\n @printer = printer\n @store = Array.new(n) { Array.new(n, '_') }\n end\n\n def place_queen(row, column)\n return false if store[row][column] == 'Q' || Move.new([row, column], store).invalid?\n\n store[row][column] = 'Q'\n true\n end\n\n def length\n store.length\n end\n\n def full_grid_count\n store.flatten.count\n end\n\n def print\n printer.new(store).print\n end\n\n private\n\n attr_reader :store, :printer\nend\n</code></pre>\n<p>Notice that we moved the <code>place_queen</code> method in the <code>Grid</code> class and also moved the 'validation' there. This is called <a href=\"https://martinfowler.com/bliki/TellDontAsk.html\" rel=\"nofollow noreferrer\">tell, don't ask</a> and instead checking if the move is valid and then placing the queen we now just say, place the queen and let us know if it worked. This simplifies our code in the <code>EightQueens</code> class.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class EightQueens\n def initialize(n)\n @grid = Grid.new(n)\n @invalid_pos = Set.new\n @queen_pos = Set.new\n end\n\n def solve\n until queen_pos.size == grid.length\n place_queen\n reset\n end\n\n puts 'Eight Queens puzzle solved, observe board.'\n grid.print\n\n true\n end\n\n private\n\n attr_reader :invalid_pos, :queen_pos, :grid\n\n def place_queen\n random_pos = pick_random_pos\n\n if grid.place_queen(*pick_random_pos)\n queen_pos &lt;&lt; random_pos\n else\n invalid_pos &lt;&lt; random_pos\n end\n end\n\n def pick_random_pos\n idx1 = rand(0...grid.length)\n idx2 = rand(0...grid.length)\n\n [idx1, idx2]\n end\n\n def reset\n return unless invalid_pos.length == grid.full_grid_count - grid.length\n\n @grid = Grid.new(grid.length)\n @invalid_pos = Set.new\n @queen_pos = Set.new\n end\nend\n</code></pre>\n<h1>Corner cases</h1>\n<p>It's not working for grids smaller 3 and just ends up in a infinite loop. You might want to have a look at these cases when no solution exists.</p>\n<p>This is mostly focused on object oriented design (and by no means a perfect solution either). There might be ways to make this more efficient too but often readable and maintainable code if preferred over efficiency.</p>\n<p>Some books about object oriented design in Ruby I can highly recommend are</p>\n<ul>\n<li><a href=\"https://www.poodr.com/\" rel=\"nofollow noreferrer\">https://www.poodr.com/</a></li>\n<li><a href=\"https://martinfowler.com/books/refactoringRubyEd.html\" rel=\"nofollow noreferrer\">https://martinfowler.com/books/refactoringRubyEd.html</a></li>\n</ul>\n<h2>Edit:</h2>\n<p>In your solution you also use some sort of brute forcing (pick a random queen position until you have a valid solution, if no valid solution is possible reset grid). This is a simple solution! However, try to solve a 32 grid and it will take 'forever'. With your updated solution you can now easily implement new algorithms to solve the problem as you can reuse <code>Grid</code> and <code>Move</code> and we just need to implement a new <code>EightQueens</code> class (and maybe rename the old one to e.g. <code>RandomEighQueensSolver</code>. A better algorithm you might want to try to implement is called backtracking (<a href=\"https://en.wikipedia.org/wiki/Backtracking\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Backtracking</a>).</p>\n<h2>Edit2:</h2>\n<p>As discussed in the comments, my assumption to merge the abortion condition in diagonal together does not work.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class Diagonal\n def initialize(position:, delta:, to:)\n @row, @column = position\n @row_delta, @column_delta = delta\n @to_row, @to_column = to\n end\n\n def all\n [].tap do |result|\n result &lt;&lt; update_position until border_reached?\n end\n end\n\n def self.for(position, size)\n Diagonal.new(position: position, delta: [-1, -1], to: [0, 0]).all +\n Diagonal.new(position: position, delta: [1, 1], to: [size, size]).all +\n Diagonal.new(position: position, delta: [-1, 1], to: [0, size]).all +\n Diagonal.new(position: position, delta: [1, -1], to: [size, 0]).all\n end\n\n private\n\n attr_reader :row, :column, :row_delta, :column_delta, :to_row, :to_column\n\n def update_position\n [\n update_row,\n update_column\n ]\n end\n\n def update_row\n @row += row_delta\n end\n\n def update_column\n @column += column_delta\n end\n\n def border_reached?\n row == to_row ||\n column == to_column\n end\nend\n</code></pre>\n<p>See also a working example here <a href=\"https://github.com/ChrisBr/queen-puzzle\" rel=\"nofollow noreferrer\">https://github.com/ChrisBr/queen-puzzle</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T23:35:27.820", "Id": "480637", "Score": "0", "body": "This is excellent, thank you. I do have one question, in the 'reset' function, would there be any concern about creating new grids and sets in terms of memory? Is my impression that clearing the originally initialized grid and vald/invalid sets saves space in memory, or is this maybe too little of a concern? Or is it just another way to solve the problem? Thanks again, really enjoying Ruby I'll be studying this answer over the next day or two." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T07:29:23.910", "Id": "480651", "Score": "0", "body": "Creating new objects should not be a memory concern as you don't hold the reference anymore and eventually Ruby's garbage collection will remove the objects. If you would create millions of objects it might make sense to reuse them, most of the team it's more clear to just create new objects though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T07:51:44.700", "Id": "480652", "Score": "0", "body": "Please note my edit regarding trying out different algorithms too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T23:26:58.223", "Id": "480742", "Score": "0", "body": "Okay, that's an interesting feature of Ruby, thanks for the clarification. I will definitely circle back around to understand and implement the 'backtracking' method. Interestingly according to wiki the highest n-queen board size that has been fully enumerated is 27x27. I was actually surprised by my method, it was still giving me answers within 30 seconds or so up until 17x17 or 18x18, I was wondering if I had a stronger computer might the method not be able to make it all the way up to 27x27 in a reasonable amount of time, but I'm interested to see how backtracking does..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T08:24:12.543", "Id": "480763", "Score": "0", "body": "If you're satisfied with the answer, please consider voting up and accepting it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-08T22:01:46.433", "Id": "481498", "Score": "0", "body": "Still new to codereview, so I made the mistake of accepting your answer before actually running it. Still working full time while I study and practice so didn't have the chance to until yesterday. Unfortunately it looks like your solution is still giving only partially correct solutions. Is there a tip you could give me for debugging? I'd like to be able to debug this to understand it but I'm still new to OOD and the private methods are stopping me from digging in to things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-09T08:43:12.643", "Id": "481530", "Score": "0", "body": "Can you elaborate what you mean with partially correct solutions and how private methods stopping you from debugging? Generally you can still add e.g. a `puts` or use a real debugger like the `byebug` gem to look what is going on in the private methods. Another idea could be to write tests / specs for the classes which is also a very useful skill to learn. RSpec is a good place to start (https://github.com/rspec/rspec)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-10T00:05:54.913", "Id": "481599", "Score": "0", "body": "Yes, I'm using byebug. I think I may try to write the tests and specs for the separate classes. From what I can tell your solution is failing with diagonals but working for columns and rows. Q's are not being placed on same rows and columns but are being placed on diagonals, returning incorrect solutions. There were a few main challenges when I was writing my original version, so I'm really interested in seeing how the logic changed from my version to yours, as when I've been going over it so far all the logic seems to be sound." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-10T07:24:26.363", "Id": "481629", "Score": "1", "body": "So I had another look and turns out my assumption to merge the breaking condition for the diagonals was wrong. I implemented some specs and a fixed solution here https://github.com/ChrisBr/queen-puzzle. The code is in the lib directory, specs are in specs. Feel free to add some more specs (e.g. for rows, columns and if the position is already occupied) and send me a PR if you fancy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-10T23:50:23.133", "Id": "481708", "Score": "0", "body": "Just started the Github section of the course I've been following online, perfect timing." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T20:19:40.023", "Id": "244809", "ParentId": "244739", "Score": "2" } } ]
{ "AcceptedAnswerId": "244809", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:02:17.643", "Id": "244739", "Score": "4", "Tags": [ "beginner", "ruby", "n-queens" ], "Title": "Solution to the n-queens puzzle in Ruby" }
244739
<p>A few days ago I made a &quot;Rock Paper Scissors&quot; game in C# and got my code reviewed on this site. Someone suggested writing a &quot;Rock Paper Scissors Lizard Spock&quot; game and I did. I tried to follow the given advices but I'm not sure if this code is better or way worse than the other. I am not satisfied with my code and would be very grateful if you tell me how to write it better and also how I can learn to write cleaner, well-structured code.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace RockPaperScissorsLizardSpock { public enum Choice { Rock = 1, Paper = 2, Scissors = 3, Lizard = 4, Spock = 5 } public enum Opponent { None, Computer, Human, } class Rule { public Choice roundWinner; public Choice roundLoser; public string verb; public Rule(Choice roundWinner_in, string verb_in, Choice roundLoser_in) { roundWinner = roundWinner_in; verb = verb_in; roundLoser = roundLoser_in; } public override string ToString() { return string.Format(&quot;{0} {1} {2}&quot;, roundWinner, verb, roundLoser); } } static class CompareMoves { private static Rule winningRule; private static bool? HasPlayerWon; public static Rule FindRulePlayer(HumanPlayer p, ComputerPlayer cpu) { return Game.Rules.FirstOrDefault(rule =&gt; rule.roundWinner == p.Move_Enum &amp;&amp; rule.roundLoser == cpu.Move_Enum); } public static Rule FindRuleCPU(ComputerPlayer cpu, HumanPlayer p) { return Game.Rules.FirstOrDefault(rule =&gt; rule.roundWinner == cpu.Move_Enum &amp;&amp; rule.roundLoser == p.Move_Enum); } public static Rule FindRule2P(HumanPlayer p1, HumanPlayer p2) { return Game.Rules.FirstOrDefault(rule =&gt; rule.roundWinner == p1.Move_Enum &amp;&amp; rule.roundLoser == p2.Move_Enum); } public static void Compare(HumanPlayer p, ComputerPlayer cpu) { Rule rule1 = FindRulePlayer(p, cpu); Rule rule2 = FindRuleCPU(cpu, p); if(rule1 != null) { HasPlayerWon = true; winningRule = rule1; p.Score++; } else if (rule2 != null) { HasPlayerWon = false; winningRule = rule2; cpu.Score++; } else { HasPlayerWon = null; } } public static void Compare(HumanPlayer p1, HumanPlayer p2) { Rule rule1 = FindRule2P(p1, p2); Rule rule2 = FindRule2P(p2, p1); if (rule1 != null) { HasPlayerWon = true; winningRule = rule1; p1.Score++; } else if (rule2 != null) { HasPlayerWon = false; winningRule = rule2; p2.Score++; } else { HasPlayerWon = null; } } public static string WhoWonTheRound(HumanPlayer p, ComputerPlayer cpu) { string msg = string.Empty; if (HasPlayerWon == null) { msg = &quot;\nTie.&quot;; } if (HasPlayerWon == true) { msg = string.Format(&quot;\n{0} wins this round. {1}&quot;, p.Name, winningRule); } if (HasPlayerWon == false) { msg = string.Format(&quot;\nComputer wins this round. {0}&quot;, winningRule); } return msg; } public static string WhoWonTheRound(HumanPlayer p1, HumanPlayer p2) { string msg = string.Empty; if (HasPlayerWon == null) { msg = &quot;\nTie.&quot;; } if (HasPlayerWon == true) { msg = string.Format(&quot;\n{0} wins this round.{1}&quot;, p1.Name, winningRule); } if (HasPlayerWon == false) { msg = string.Format(&quot;\n{0} wins this round.{1}&quot;, p2.Name, winningRule); } return msg; } } class Player { public int Score { get; set; } public int Move_Int; public Choice Move_Enum; } class HumanPlayer : Player { public string Name { get; set; } public static void SetPlayerName(HumanPlayer p) { Console.Write(&quot;Enter name --&gt; &quot;); p.Name = Console.ReadLine(); } public static void SetPlayerName(HumanPlayer p1, HumanPlayer p2) { Console.Write(&quot;Player 1 - Enter name --&gt; &quot;); p1.Name = Console.ReadLine(); Console.Clear(); Console.Write(&quot;Player 2 - Enter name --&gt; &quot;); p2.Name = Console.ReadLine(); } public Choice PlayerMove(HumanPlayer p) { do { Console.Write(&quot;\n\n{0} - Rock [1], Paper [2], Scissors [3], Lizard [4], Spock? [5] --&gt; &quot;,p.Name); p.Move_Int = int.Parse(Console.ReadLine()); } while (p.Move_Int != 1 &amp;&amp; p.Move_Int != 2 &amp;&amp; p.Move_Int != 3 &amp;&amp; p.Move_Int != 4 &amp;&amp; p.Move_Int != 5); p.Move_Enum = (Choice)p.Move_Int; return p.Move_Enum; } } class ComputerPlayer : Player { public Choice ComputerRandomMove(ComputerPlayer cpu) { Random random = new Random(); cpu.Move_Int = random.Next(1, 6); cpu.Move_Enum = (Choice) cpu.Move_Int; return cpu.Move_Enum; } } class Display { public static void MainMenu() { Console.WriteLine(&quot;Welcome to the \&quot;Rock Paper Scissors Lizard Spock\&quot;.\n&quot;); Thread.Sleep(500); Console.Write(&quot;Do you really want to play the game? [Y/N] --&gt; &quot;); } public static void Settings(HumanPlayer p) { Console.Clear(); Game.winScore = Game.HowManyPoints(ref Game.scr); Console.Clear(); Console.Write(&quot;Play against the computer or an another player? [C/H] --&gt; &quot;); Game.opponent = Game.ChooseOpponent(ref Game.opponentStr); Console.Clear(); } public static void Board(HumanPlayer p, ComputerPlayer cpu) { Console.WriteLine(&quot;\n\t\t{0}: {1}\n\n\t\tComputer: {2}\n&quot;,p.Name, p.Score, cpu.Score); } public static void Board(HumanPlayer p1, HumanPlayer p2) { Console.WriteLine(&quot;\n\t\t{0}: {1}\n\n\t\t{2}: {3}\n&quot;, p1.Name, p1.Score, p2.Name, p2.Score); } public static void Rules() { Console.WriteLine(&quot;\n Remember:\n&quot;); foreach(Rule item in Game.Rules) { Console.WriteLine(item); } } public static void HumanVsCPU(HumanPlayer p, ComputerPlayer cpu) { Display.Board(p, cpu); Display.Rules(); p.PlayerMove(p); cpu.ComputerRandomMove(cpu); Console.Clear(); CompareMoves.Compare(p, cpu); Display.ShowMoves(p, cpu); Display.ShowTheRoundWinner(p, cpu); } public static void HumanVsHuman(HumanPlayer p1, HumanPlayer p2) { Display.Board(p1, p2); Display.Rules(); p1.PlayerMove(p1); Console.Clear(); Display.Board(p1, p2); Display.Rules(); p2.PlayerMove(p2); Console.Clear(); CompareMoves.Compare(p1, p2); Display.ShowMoves(p1, p2); Display.ShowTheRoundWinner(p1, p2); } public static void ShowMoves(HumanPlayer p, ComputerPlayer cpu) { Console.WriteLine(&quot;{0} chose {1}.&quot;, p.Name, p.Move_Enum); Console.WriteLine(&quot;Computer chose {0}&quot;, cpu.Move_Enum); } public static void ShowMoves(HumanPlayer p1, HumanPlayer p2) { Console.WriteLine(&quot;{0} chose {1}.&quot;, p1.Name, p1.Move_Enum); Console.WriteLine(&quot;{0} chose {1}&quot;, p2.Name, p2.Move_Enum); } public static void ShowTheRoundWinner(HumanPlayer p, ComputerPlayer cpu) { string message = CompareMoves.WhoWonTheRound(p, cpu); Console.WriteLine(message); } public static void ShowTheRoundWinner(HumanPlayer p1, HumanPlayer p2) { string message = CompareMoves.WhoWonTheRound(p1, p2); Console.WriteLine(message); } public static void AskForReplay(HumanPlayer p1, HumanPlayer p2, ComputerPlayer cpu) { Console.Write(&quot;\nReplay? [Y/N) --&gt; &quot;); Game.StartGameOrNot(ref Game.startgame); Game.Initialize(p1, p2, cpu); Console.Clear(); } } static class Game { public static string startgame; public static bool play; public const int MAX_SCORE = 50; public static int winScore; public static int scr; public static string opponentStr; public static Opponent opponent; public static List&lt;Rule&gt; Rules = new List&lt;Rule&gt; { new Rule(Choice.Scissors, &quot;cuts&quot;, Choice.Paper), new Rule(Choice.Paper, &quot;covers&quot;, Choice.Rock), new Rule(Choice.Rock, &quot;crushes&quot;, Choice.Lizard), new Rule(Choice.Lizard, &quot;poisons&quot;, Choice.Spock), new Rule(Choice.Spock, &quot;smashes&quot;, Choice.Scissors), new Rule(Choice.Scissors, &quot;decapitates&quot;, Choice.Lizard), new Rule(Choice.Lizard, &quot;eats&quot;, Choice.Paper), new Rule(Choice.Paper, &quot;disproves&quot;, Choice.Spock), new Rule(Choice.Spock, &quot;vaporizes&quot;, Choice.Rock), new Rule(Choice.Rock, &quot;crushes&quot;, Choice.Scissors), }; public static bool StartGameOrNot(ref string startgame_in) { bool play_in = false; do { startgame_in = Console.ReadLine().ToUpper(); if (startgame_in == &quot;Y&quot;) { play_in = true; } else if (startgame_in == &quot;N&quot;) { play_in = false; Console.WriteLine(&quot;\nOkay then, goodbye.&quot;); Environment.Exit(0); } else { Console.Write(&quot;\nInvalid. Write \&quot;Y\&quot; or \&quot;N\&quot; --&gt; &quot;); } } while (startgame_in != &quot;Y&quot; &amp;&amp; startgame_in != &quot;N&quot;); return play_in; } public static int HowManyPoints(ref int winScore_in) { do { Console.Write(&quot;How many points? [1-{0}] --&gt; &quot;, Game.MAX_SCORE); winScore_in = int.Parse(Console.ReadLine()); } while (winScore_in &lt;= 0 || winScore_in &gt; MAX_SCORE); return winScore_in; } public static Opponent ChooseOpponent(ref string opponentStr_in) { Opponent opponent_in = Opponent.None; do { opponentStr_in = Console.ReadLine().ToUpper(); } while (opponentStr_in != &quot;C&quot; &amp;&amp; opponentStr_in != &quot;H&quot;); switch (opponentStr_in) { case &quot;C&quot;: opponent_in = Opponent.Computer; break; case &quot;H&quot;: opponent_in = Opponent.Human; break; } return opponent_in; } public static void Initialize(HumanPlayer p1, HumanPlayer p2, ComputerPlayer cpu) { p1.Score = 0; p2.Score = 0; cpu.Score = 0; } public static bool WhoWins(HumanPlayer p1, HumanPlayer p2, ComputerPlayer cpu) { if (p1.Score == winScore) { Console.WriteLine(&quot;\n{0} wins the game.&quot;, p1.Name); return true; } else if (p2.Score == winScore) { Console.WriteLine(&quot;\n{0} wins the game.&quot;, p2.Name); return true; } else if (cpu.Score == winScore) { Console.WriteLine(&quot;\nComputer wins the game.&quot;); return true; } return false; } } class Program { static void Main(string[] args) { Display.MainMenu(); Game.play = Game.StartGameOrNot(ref Game.startgame); HumanPlayer player1 = new HumanPlayer(); HumanPlayer player2 = new HumanPlayer(); ComputerPlayer computer = new ComputerPlayer(); Display.Settings(player1); Game.Initialize(player1, player2, computer); switch(Game.opponent) { case Opponent.Computer: HumanPlayer.SetPlayerName(player1); break; case Opponent.Human: HumanPlayer.SetPlayerName(player1, player2); break; } Console.Clear(); while (Game.play) { switch(Game.opponent) { case Opponent.Computer: Display.HumanVsCPU(player1, computer); break; case Opponent.Human: Display.HumanVsHuman(player1, player2); break; } if(Game.WhoWins(player1, player2, computer)) { Display.AskForReplay(player1, player2, computer); } } } } } </code></pre> <p>Note: Normally I was going to write lots of if-statements to compare moves but I think this way (which I found on another question) is better.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T20:15:43.657", "Id": "480527", "Score": "0", "body": "Are you aware there's such a thing as `else if`? Would be great for your `HasPlayerWon` comparisons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T20:50:46.430", "Id": "480533", "Score": "0", "body": "@Mast OP is obviously aware of that. Just questionable, why they didn't use it for these specific conditional statements." } ]
[ { "body": "<p>Rewrite the code so all references are &quot;Player&quot;, not &quot;Human and/or Computer&quot; Your code will shrink by more than half.</p>\n<hr />\n<p><strong>Do not use class name in method names</strong></p>\n<p>In <code>ComputerPlayer</code></p>\n<ul>\n<li><code>ComputerRandomMove</code> would be <code>RandomMove</code></li>\n<li><code>SetPlayerName</code> : <code>SetName</code> (<code>Name</code> may be ok too )</li>\n<li><code>PlayerMove</code> : <code>Move</code></li>\n</ul>\n<hr />\n<p><strong>Do not name classes as their inheritance chain</strong></p>\n<p><code>HumanPlayer : Player</code> should be <code>Human : Player</code></p>\n<p>That &quot;Human&quot; is a player is obvious.</p>\n<hr />\n<p><strong>Inheritance and Polymorphism</strong></p>\n<p>Yes, inheritance is used to extend a class - adding new properties and methods. But also and <em>far more important</em> is polymorphism - that is to say &quot;all players do the same thing, but differently. All players have a name, but different names&quot;</p>\n<pre><code>class Player {\n public int Score { get; set; }\n public int Move_Int;\n public Choice Move_Enum;\n public string Name {set; get;}\n \n public override Move(); // each subclass will have different implementation\n}\n\nPlayer Bob = new Human(...);\nPlayer Hal2000 = new Computer (...);\n</code></pre>\n<p>No need for &quot;Human vs Computer&quot;, &quot;Computer vs Computer&quot;, etc. methods, just &quot;Player vs Player&quot;\nSo the only &quot;Vs&quot; method needed is:</p>\n<pre><code> public static void Versus (Player ThisOne, Player ThatOne) {\n \n ThisOne.Move();\n ThatOne.Move();\n }\n \n</code></pre>\n<p>And is used thus:</p>\n<pre><code>Versus(Bob, Hal2000); //Bob is &quot;ThisOne&quot;, Hal2000 is &quot;ThatOne&quot;\n</code></pre>\n<p>I expect that all subtype-specific-redundant-methods can be reduced to a single method: <code>Compare</code>, <code>WhoWonTheRound</code>, etc.</p>\n<hr />\n<p><strong>overriding ToString()</strong></p>\n<p>Big thumbs up!!!</p>\n<p>I like toString() for outputting all the property values. Great for debugging. Also <code>WriteLine (Bob)</code>, for example, is actually calling <code>Bob.ToString()</code></p>\n<hr />\n<p><strong>Opponent Enum</strong></p>\n<p>another thumbs up! And two thumbs up for <code>Opponent.None</code>. I do this all the time.</p>\n<p>I like the idea of an initial value of &quot;not assigned yet&quot;, great debugging aid. If it defaults to &quot;Human&quot; it is harder to tell we forgot to assign the right kind. &quot;None&quot; forces explicit assignment.</p>\n<p>You will appreciate this the first time you have an enum with lots of values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T21:56:43.790", "Id": "244755", "ParentId": "244745", "Score": "2" } }, { "body": "<h2>Namespaces</h2>\n<p>Have a read through <a href=\"https://stackoverflow.com/questions/125319/should-using-directives-be-inside-or-outside-the-namespace\">https://stackoverflow.com/questions/125319/should-using-directives-be-inside-or-outside-the-namespace</a> . I agree with StyleCop's default recommendation of moving <code>using</code> within the namespace:</p>\n<pre><code>namespace RockPaperScissorsLizardSpock\n{\n using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Threading;\n</code></pre>\n<h2>Public members</h2>\n<p>If you leave these public:</p>\n<pre><code> public Choice roundWinner;\n public Choice roundLoser;\n public string verb;\n</code></pre>\n<p>then there is no point to your constructor at all. The user can assign member values whenever they want. But that's not a great idea; it makes debugging and verifiability more difficult. Instead, keep your constructor, and mark these <code>public readonly</code>. See <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly</a> for more details.</p>\n<h2>C# now has interpolation!</h2>\n<pre><code>string.Format(&quot;\\n{0} wins this round. {1}&quot;, p.Name, winningRule);\n</code></pre>\n<p>can be</p>\n<pre><code>$&quot;\\n{p.Name} wins this round. {winningRule}&quot;\n</code></pre>\n<h2>Integer intervals</h2>\n<pre><code>p.Move_Int != 1 &amp;&amp; p.Move_Int != 2 &amp;&amp; p.Move_Int != 3 &amp;&amp; p.Move_Int != 4 &amp;&amp; p.Move_Int != 5\n</code></pre>\n<p>Assuming that this is non-nullable, then this should be</p>\n<pre><code>p.Move_Int &lt; 1 || p.Move_Int &gt; 5\n</code></pre>\n<p>That said, you're parsing user input in a somewhat non-friendly way:</p>\n<pre><code>int.Parse(Console.ReadLine())\n</code></pre>\n<p>If a person enters a letter accidentally, this will explode with an exception. Consider <code>TryParse</code> instead, and deal with the failure case nicely.</p>\n<h2>Side effects</h2>\n<p><code>PlayerMove</code> does two things - sets the player's <code>Move_Enum</code> <em>and</em> returns it. To confuse things even further, you're modifying an argument player's move rather than <code>this</code>. I propose that you instead</p>\n<ul>\n<li>Do not return anything</li>\n<li>Do not accept a <code>HumanPlayer p</code></li>\n<li>Set <code>this.Move_Enum</code> based on the input.</li>\n</ul>\n<h2>Re-entrance</h2>\n<p>There's no reason for <code>Game</code> to be <code>static</code>. For testing purposes in particular, it's useful for this to be instantiated as a normal class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T22:55:01.923", "Id": "244758", "ParentId": "244745", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:34:40.277", "Id": "244745", "Score": "2", "Tags": [ "c#", "beginner" ], "Title": "Rock Paper Scissors Lizard Spock in C#" }
244745
<p>I am trying to convert a <code>BLOB</code> that is stored in a database to a <code>JPG</code> and then I need to display it on an <code>html form</code> in a <code>C#</code> application.</p> <p>A little backstory first - this is an older web app that was designed to take a <code>JPG</code> (photo) that was stored as a path in the database, resize it, then show as a <code>BLOB</code>. This functionality needs to stay in place, but now one of the systems is changing and the photo is going to be stored in the database as a <code>BLOB</code> instead of a path to a photo (\servername\images\xyz.jpg).</p> <p>One system still needs the image to be resized then sent back as a <code>BLOB</code> to display. The other systems that call this web-app will need the <code>BLOB</code> converted to a <code>JPG</code> to display.</p> <p>The code below works, but I think it might have put an unnecessary load on the server, because this morning the system was laggy and some features were impossible to use. I have a feeling that the <code>.Save</code> is the troublemaker here since I am calling it twice. I know the image doesn't need to be saved anywhere physically, as long as the web-app can call and have it display to the site. Is there anything I can change here to skip saving an image on the server and just display it so it doesn't use up a ton of resources?</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { byte[] byteImage = null; string ID = Request.QueryString[&quot;id&quot;]; string imageFile = &quot;\\\\server\\c$\\inetpub\\wwwroot\\web-app\\images\\&quot; + ID+ &quot;.jpg&quot;; string server = Request.ServerVariables[&quot;server_name&quot;]; var serverNameList = db.Servers.Select(x =&gt; x.ServerName).ToList(); connection.Open(); SqlCommand sqlCommand = new SqlCommand(&quot;sp&quot;, connection); sqlCommand.Parameters.Add(&quot;@ID&quot;, SqlDbType.VarChar); sqlCommand.Parameters[&quot;@ID&quot;].Value = ID; sqlCommand.CommandType = CommandType.StoredProcedure; SqlDataReader dr = sqlCommand.ExecuteReader(); while (dr.Read()) { byteImage = (byte[])dr[&quot;BLOB&quot;]; } if (byteImage != null) { using (MemoryStream ms = new MemoryStream(byteImage)) { //saving to jpg image Image img = new Bitmap(ms); img.Save(imageFile, ImageFormat.Jpeg); Response.Clear(); Response.CacheControl = &quot;public&quot;; Response.Cache.SetExpires(DateTime.Now.AddDays(1.0)); Response.ContentType = &quot;Image/jpeg&quot;; if (serverNameList.Contains(server)) // if user is coming from a specific server, resize the image then send back { byte[] resizedImage = GetResizedImage(imageFile, 300, 400); Response.OutputStream.Write(resizedImage, 0, resizedImage.Length); } else // skip resize and show image as jpg { Response.BinaryWrite(byteImage); } } } else // image is null { imageFile = HttpRuntime.AppDomainAppPath + &quot;PERSON.GIF&quot;; } } private byte[] GetResizedImage(string path, int width, int height) { Bitmap bitmap1 = new Bitmap(path); double height1 = bitmap1.Height; double width1 = bitmap1.Width; double num = 1.0; if (width &gt; 0) num = width / width1; else if (height &gt; 0) num = height / height1; MemoryStream memoryStream = new MemoryStream(); Bitmap bitmap2 = new Bitmap((int)(width1 * num), (int)(height1 * num)); bitmap2.SetResolution(150f, 150f); Graphics graphics = Graphics.FromImage(bitmap2); graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.Clear(Color.White); graphics.DrawImage(bitmap1, new Rectangle(0, 0, (int)(num * width1), (int)(num * height1)), new Rectangle(0, 0, (int)width1, (int)height1), GraphicsUnit.Pixel); bitmap2.Save(memoryStream, ImageFormat.Jpeg); return memoryStream.ToArray(); } </code></pre>
[]
[ { "body": "<p>Welcome to CodeReview! I hope you get some good feedback.</p>\n<h2>Absolute paths</h2>\n<pre><code>string ID = Request.QueryString[&quot;id&quot;];\nstring imageFile = &quot;\\\\\\\\server\\\\c$\\\\inetpub\\\\wwwroot\\\\web-app\\\\images\\\\&quot; + ID+ &quot;.jpg&quot;;\n</code></pre>\n<p>This has a few issues. First, it's typical for a server to be in a &quot;jail&quot; where it shouldn't have access to the filesystem at large, and should only access data from its own local directory. This is for security purposes. Though I haven't done this in a long time, it seems the ASP.NET way of safely accessing such paths is <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.web.httpserverutility.mappath?view=netframework-4.8\" rel=\"nofollow noreferrer\">MapPath</a>.</p>\n<p>Second: it's crucially important that you do some validation on ID. In its current state a hacker could easily construct a path navigation exploit where the ID contains <code>..\\..\\..</code> (etc) to explore the rest of the filesystem if the server is misconfigured.</p>\n<h2>Managing your connection</h2>\n<p>If <code>connection</code> is an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection?view=dotnet-plat-ext-3.1\" rel=\"nofollow noreferrer\">SqlConnection</a>, it implements <code>IDisposable</code>, and as such you should put it in a <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement\" rel=\"nofollow noreferrer\"><code>using</code></a>. The same is true of <code>SqlCommand</code>.</p>\n<h2>Add-with-value</h2>\n<p>You should prefer <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparametercollection.addwithvalue?view=dotnet-plat-ext-3.1\" rel=\"nofollow noreferrer\">AddWithValue</a> over a separated <code>Add</code>/<code>.Value</code> assignment here;</p>\n<pre><code>sqlCommand.Parameters.Add(&quot;@ID&quot;, SqlDbType.VarChar);\nsqlCommand.Parameters[&quot;@ID&quot;].Value = ID;\n</code></pre>\n<h2>Read-in-loop</h2>\n<p>This:</p>\n<pre><code>while (dr.Read())\n{\n byteImage = (byte[])dr[&quot;BLOB&quot;];\n}\n</code></pre>\n<p>should probably not use a loop. Since it seems you expect only one row returned,</p>\n<ul>\n<li><code>Read()</code> once;</li>\n<li>assert that it returned <code>true</code>;</li>\n<li>assign <code>byteImage</code>;</li>\n<li><code>Read()</code> again;</li>\n<li>assert that it returned <code>false</code>.</li>\n</ul>\n<h2>Streamed image creation</h2>\n<p><code>GetResizedImage</code> creates a memory stream. It should not. <code>Response</code> already has an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.web.httpresponse.outputstream?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>OutputStream</code></a>, and you should be writing to that directly. The one thing to double-check with this approach is that <code>Content-Length</code> is still set correctly, which is probably only possible if <code>BufferOutput</code> is enabled.</p>\n<h2>Avoiding files</h2>\n<p>As to your original question, which I never really addressed:</p>\n<blockquote>\n<p>Is there anything I can change here to skip saving an image on the server and just display it so it doesn't use up a ton of resources?</p>\n</blockquote>\n<p>Yes! As long as you get an image from the database, you always <code>Save()</code> it to the disc. However, this file is only used if the server name is approved. Move your save within the name check, and fewer cases will require disc I/O.</p>\n<p>Even further: if this is the only code that touches that file, that file should not exist at all and you should not be doing a round trip to the disc. Once you have your <code>img</code>, pass that to <code>GetResizedImage</code> instead of a path string.</p>\n<h2>Bug?</h2>\n<p>There is a mechanism here:</p>\n<pre><code>imageFile = HttpRuntime.AppDomainAppPath + &quot;PERSON.GIF&quot;;\n</code></pre>\n<p>which looks like it's supposed to substitute a default image if none is returned from the database. However, that file is never used. This logic needs to be rearranged so that it is. If you get back a null from the database, load this file into your byteImage.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T17:26:06.723", "Id": "480612", "Score": "1", "body": "Thank you! I was able to make all the updates you suggested and the systems are working beautifully together. Can't even tell there is another call there to resize the images. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T00:27:34.273", "Id": "244763", "ParentId": "244746", "Score": "7" } }, { "body": "<p>Consider not using System.Drawing to manipulate images in ASP.NET:</p>\n<blockquote>\n<p>Classes within the System.Drawing namespace are not supported for use\nwithin a Windows or ASP.NET service. Attempting to use these classes\nfrom within one of these application types may produce unexpected\nproblems, such as diminished service performance and run-time\nexceptions.<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.drawing#remarks\" rel=\"nofollow noreferrer\">1</a></p>\n</blockquote>\n<p>An alternative could be the new <a href=\"https://github.com/SixLabors/ImageSharp\" rel=\"nofollow noreferrer\">ImageSharp</a> library currently in pre-release or <a href=\"https://github.com/saucecontrol/PhotoSauce\" rel=\"nofollow noreferrer\">ImageScaler</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T17:26:52.340", "Id": "480613", "Score": "0", "body": "Thanks! I will definitely look into using either one of those in the future. I'm not a fan of using this outdated code either. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T14:28:02.940", "Id": "244788", "ParentId": "244746", "Score": "3" } } ]
{ "AcceptedAnswerId": "244763", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T19:35:56.940", "Id": "244746", "Score": "8", "Tags": [ "c#", "image", "asp.net" ], "Title": "C# Convert BLOB to jpg, resize, then back to BLOB" }
244746
<p>I'm learning TypeScript while doing my portfolio, and I wrote a class to make a fetch request to the API that holds my data.</p> <p>It is working fine. I use localStorage to set a cache to avoid calling the API often as the data won't change.</p> <p>I know I could improve this a lot, and haven't used many TypeScript features, so it would be great to have some pointers on how to improve this class generally, and also how to improve it by adding some more TypeScript features.</p> <p>This is the class:</p> <pre class="lang-js prettyprint-override"><code>export interface PortfolioData { basics: Basics; projects?: Project[]; } interface Cache { portfolio: PortfolioData; expiration: number; } class Portfolio { private url = 'https://gitconnected.com/v1/portfolio/mauriciorobayo'; private cacheDurationInMilliseconds: number; constructor(cacheDurationInMinutes: number) { this.cacheDurationInMilliseconds = cacheDurationInMinutes * 60 * 1000; } private getCache(): Cache | undefined { const data = localStorage.getItem('portfolio'); if (!data) { return; } const cache = JSON.parse(data); if (Date.now() &gt; cache.expiration) { return; } return cache; } private setCache(data: Cache) { localStorage.setItem('portfolio', JSON.stringify(data)); } async getPortfolio(): Promise&lt;PortfolioData&gt; { const cache = this.getCache(); if (cache) { return cache.portfolio; } const response = await fetch(this.url); if (response.ok) { const portfolio = await response.json(); this.setCache({ portfolio, expiration: Date.now() + this.cacheDurationInMilliseconds, }); return portfolio; } throw new Error(response.statusText); } } export default Portfolio; </code></pre>
[]
[ { "body": "<p>The review will be focused on readability and testability.</p>\n<h1>Naming</h1>\n<p>I read (I think it was in Clean Code) that <a href=\"https://blog.usejournal.com/naming-your-variables-f9477ba002e9#c159\" rel=\"nofollow noreferrer\">variables should not have a postfix like <code>Data</code> and <code>Information</code></a> and instead we should give things a name that they represent.</p>\n<p><code>PortfolioData</code> is actually a <code>Portfolio</code> while your current <code>Portfolio</code> is more a <code>PortfolioRepository</code> or <code>PortfolioCollection</code>.</p>\n<p>Additionally I couldn't figure out, what <code>Basic</code> could mean and I looked up the json-representation of the <em>gitconnected</em> api:</p>\n<blockquote>\n<pre><code>&quot;basics&quot;: {\n &quot;name&quot;: &quot;...&quot;,\n &quot;picture&quot;: &quot;https://avatars2.githubusercontent.com/u/2121481?v=4&quot;,\n &quot;label&quot;: &quot;...&quot;,\n &quot;headline&quot;: &quot;...&quot;,\n &quot;summary&quot;: &quot;...&quot;,\n &quot;website&quot;: &quot;...&quot;,\n &quot;blog&quot;: &quot;...&quot;,\n &quot;yearsOfExperience&quot;: 2,\n &quot;id&quot;: &quot;...&quot;,\n &quot;username&quot;: &quot;...&quot;,\n &quot;karma&quot;: 22,\n &quot;email&quot;: &quot;...&quot;,\n &quot;region&quot;: &quot;...&quot;,\n &quot;location&quot;: {},\n &quot;phone&quot;: &quot;...&quot;,\n &quot;followers&quot;: 63,\n &quot;following&quot;: 94,\n &quot;profiles&quot;: []\n}\n</code></pre>\n</blockquote>\n<p>For me a more descriptive name would be <code>User</code> or <code>Owner</code>. A <code>Portfolio</code> has an <code>Owner</code> and a <code>PortfolioRepository</code> stores <code>Portfolio</code>-Objects:</p>\n<pre class=\"lang-js prettyprint-override\"><code>export interface Portfolio {\n owner: Owner;\n projects?: Project[];\n}\n\ninterface Cache {\n portfolio: Portfolio;\n expiration: number;\n}\n\nclass PortfolioRepository { /* ... */ }\n</code></pre>\n<h1>Concerns</h1>\n<p>The class <code>Portfolio</code> handles multiple concerns. There are two principles which can be named to emphasize the importance for separation:</p>\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">Separation of Concerns</a> (SoC)</li>\n<li><a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> (SRP)</li>\n</ul>\n<p>The concerns are</p>\n<ul>\n<li>fetching (<code>await fetch(this.url)</code>)</li>\n<li>caching (<code>this.setCache(...)</code>)</li>\n<li>querying (<code>async getPortfolio(): Promise&lt;PortfolioData&gt;</code>)</li>\n</ul>\n<p>When we separate the concerns we could accomplish something like</p>\n<pre class=\"lang-js prettyprint-override\"><code>interface PortfolioRepository {\n get(): Promise&lt;Portfolio&gt;;\n}\n\nclass ApiPortfolioRepository implements PortfolioRepository {\n constructor(private cache: Cache, \n private api: API) {}\n\n async get(): Promise&lt;Portfolio&gt; {\n if (this.cache.containsPortfolio()) {\n return this.cache.get();\n }\n\n const portfolio = await this.api.fetch();\n this.cache.update(portfolio);\n \n return portfolio;\n }\n}\n</code></pre>\n<p>This has multiple advantages. Beside the descriptive and shorter method body we can accomplish through the dependency injection via the constructor a better way to test the class.</p>\n<p>Now the <code>PortfolioRepository</code> does not need to know about how caching works like the <code>cacheDurationInMilliseconds</code> and it does not need to know the http endpoint any more.</p>\n<p>If we want to test the class we could simply mock the api (for exampe with mocha and chai):</p>\n<pre class=\"lang-js prettyprint-override\"><code>import { assert } from &quot;chai&quot;;\n\nsuite('API Portfolio Repository', () =&gt; {\n\n const cache = ...;\n const fakeAPI = new FakeAPI();\n\n test('when API returns no portfolio -&gt; return undefined', () =&gt; {\n const repository = new ApiPortfolioRepository(cache, fakeAPI.withoutResponse);\n \n const portfolio = repository.get();\n\n assert.isUndefined(portfolio);\n });\n\n test('when API returns a portfolio -&gt; return portfolio', () =&gt; {\n const repository = new ApiPortfolioRepository(cache, fakeAPI.withResponse);\n \n const portfolio = repository.get();\n\n assert.deepEqual(portfolio, fakeAPI.portfolio);\n });\n\n})\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T23:28:34.623", "Id": "480636", "Score": "0", "body": "This is incredibly helpful. Thank you so much for taking the time to provide so much valuable feedback. Really appreciate it. Learned from every point you mentioned, and the links are great... refactoring." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T12:13:47.517", "Id": "244782", "ParentId": "244750", "Score": "1" } } ]
{ "AcceptedAnswerId": "244782", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T20:40:16.110", "Id": "244750", "Score": "1", "Tags": [ "javascript", "object-oriented", "typescript", "classes", "cache" ], "Title": "TypeScript fetch wrapper class with localStorage cache" }
244750
<p>A protein is composed of amino acids (also called residues). The amide nitrogen and hydrogens (N and H in the script), carbonyl carbon (C), alpha carbon (Ca), beta carbon (Cb), and alpha hydrogen (HA) form the backbone. Each amino acid has the N,H,C,CA,HA atoms, with most amino acids containing the Cb as well. Each amino acid will have a particular value (chemical shift) determined from experiments. However the experiments just give you raw values for each atom type, they do not tell you which value belongs to which amino acid (as a scientist, it is my job to determine which value fits to what amino acid) There is a program that can predict these values, for each amino acid (SPARTA). I have created a program to calculate the RMSD from the experimental value to the predicted value for each amino acid.</p> <p>Both the experimental values, and predicted values, have a particular format (NMRSTAR and SPARTA). I have decided to convert the format of each file so that each amino acid has 6 atom types in both files (I use placeholders with values of 1000 if that atom type is not there, makes it easy to ignore when calculating RMSD), and filter both files to one another so they are the same size. This makes it much easier to calculate RMSDs between the 2.</p> <p>To ensure ease of use, I have created a GUI. Initially I had the GUI script, and the functions that did all the convertions for both files, in the same script. This turned out to be a pain to troubleshoot, and difficult to read. Thus, I have split the GUI and convertions into separate files, import these separate files into the GUI script.</p> <p>This is the first time that I've tried using functions and splitting into separate files and importing (I've always done everything in one long script, no functions or imports). As well as first time adding comments. Thus any feedback on structure and function use would also be greatly appreciated!</p> <pre><code>#The GUI Script (only the parts relevant to the code) def nmrstarrun3(): text_area.delete(1.0,END) #user inputs if sparta_file == (): text_area.insert(tk.INSERT,'please upload your sparta file (make sure to use browse)\n') if seq_file == (): text_area.insert(tk.INSERT,'please upload your seq file (make sure to use browse)\n') if save_file_sparta == (): text_area.insert(tk.INSERT,'please indicate sparta save file (make sure to use browse)\n') if save_file_peaklist == (): text_area.insert(tk.INSERT,'please indicate peaklist save file (make sure to use browse)\n') if set_threshold == (): text_area.insert(tk.INSERT,'please enter a threshold (make sure to hit enter)\n') if seq_start == (): text_area.insert(tk.INSERT,'please enter a seq number (make sure to hit enter)\n') if nmrstarfile == (): text_area.insert(tk.INSERT,'please upload your nmrstar file (make sure to use browse)\n') else: text_area.insert(tk.INSERT,'Starting Program\n') text_area.insert(tk.INSERT,'Creating Sparta File\n') text_area.update_idletasks() acid_map = { 'ASP':'D', 'THR':'T', 'SER':'S', 'GLU':'E', 'PRO':'P', 'GLY':'G', 'ALA':'A', 'CYS':'C', 'VAL':'V', 'MET':'M', 'ILE':'I', 'LEU':'L', 'TYR':'Y', 'PHE':'F', 'HIS':'H', 'LYS':'K', 'ARG':'R', 'TRP':'W', 'GLN':'Q', 'ASN':'N' } os.chdir(nmrstarfile_directory) #NMRSTAR files contain a variety of information, and side chain chemical shift values #We only want residues with backbone N,HA,C,CA,CB,H chemical shifts #Additionally, NMRSTAR file amino acids numbers are not always correct (they contain additional values). Thus the user defines what the starting value should be #NMRSTAR uses 3 letter amino acid abbreviations, we want single-letter, the acid map is used to convert exctracted_and_compiled_data=[] with open(nmrstarfile) as file: for lines in file: modifier=lines.strip() extract_data_only=re.search(r'\b\d+\s+[A-Z]{3}\s+\w+\s+\w+\s+\d+\s+\d+',modifier) if extract_data_only != None: atom_search=extract_data_only.string split_data=atom_search.split() amino_acid_number=str(int(split_data[5])+int(seq_start)-1) residue_type=split_data[6] atom_type=split_data[7] converted=acid_map[residue_type] chemical_shift=split_data[10] compile_data=[amino_acid_number]+[converted]+[atom_type]+[chemical_shift] if atom_type == 'N' or atom_type == 'HA' or atom_type =='CA' or atom_type == 'CB' or atom_type=='H' or atom_type=='C': joined=' '.join(compile_data) exctracted_and_compiled_data.append(joined) from sparta_file_formatter import check_sparta_file_boundaries from nmrstar import dict_create from nmrstar import fill_missing_data dict_create(seq_file,seq_start,seq_directory) sparta_file_boundaries=check_sparta_file_boundaries(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start) data_files=fill_missing_data(final_list,seq_start) #The peaklist may have additional chemical shifts not present in the crystal structure, and thus sparta file #We filter out and create a new list containing only the residues found in the sparta file peaklist_filtered_to_match_sparta=[] count=0 for lines in data_files: modify=lines.strip() splitting=modify.split() number_search=re.search('^-*\d+[A-Z]',splitting[0]) r=re.compile(number_search.group(0)) comparison_to_sparta=list(filter(r.match,sparta_file_boundaries)) if comparison_to_sparta != []: peaklist_filtered_to_match_sparta.append(modify) else: count+=1 if count==6: #if any amino acid is the peaklist, but not SPARTA file, it will be excluded and printed out here count=0 text_area.insert(tk.INSERT,f'{splitting[0]} was excluded\n') #RMSD values are calculated summing the deviations of the experimental with predicted values, and dividing it by the number of atoms used in the calculation amino_acid_square_deviation_values=[] number=0 for experimental,predictions in zip(peaklist_filtered_to_match_sparta,sparta_file_boundaries): number+=1 experimental_split=experimental.split() predictions_split=predictions.split() square_deviation=((float(predictions_split[1])-float(experimental_split[1]))**2)/((float(predictions_split[2]))**2) if square_deviation&gt;100: square_deviation=0 else: amino_acid_square_deviation_values.append(square_deviation) if number%6 ==0: if len(amino_acid_square_deviation_values)==0: continue else: rmsd=math.sqrt((1/int(len(amino_acid_square_deviation_values)))*sum(amino_acid_square_deviation_values)) amino_acid_square_deviation_values.clear() if rmsd&gt;float(set_threshold): text_area.insert(tk.INSERT,f'{experimental_split[0]} had a rmsd of {rmsd}\n') #Both files are saved for use in other programs os.chdir(save_directory) with open(save_file_sparta,'w') as file, open(save_file_peaklist,'w') as file2: for stuff_to_write in sparta_file_boundaries: file.write(stuff_to_write+'\n') for stuff_to_write2 in peaklist_filtered_to_match_sparta: file2.write(stuff_to_write2+'\n') </code></pre> <pre><code>#sparta file formatter import re import os #This creates a sequence list that will later be used to filter residues in the sparta file outside the range we want def create_seq_list(seq_file,seq_directory,seq_start): os.chdir(seq_directory) amino_acid_count=(0+seq_start)-1 sequence_list=[] with open(seq_file) as sequence_file: for amino_acid in sequence_file: stripped_amino_acid=amino_acid.strip().upper() for word in stripped_amino_acid: amino_acid_count+=1 sequence_list.append(str(amino_acid_count)+word) return sequence_list #SPARTA files contain a lot of miscellanious info, this removes that and only extracts the residue type, number, atom type, chemical shift, and error values #Additioanlly, prolines only contain info for 4 atom types, placeholders are set in for the nitrogen and hydrogen def format_sparta(sparta_file,sparta_directory): os.chdir(sparta_directory) sparta_file_list1=[] proline_counter=0 with open(sparta_file) as sparta_predictions: for line in sparta_predictions: modifier=line.strip().upper() if re.findall('^\d+',modifier): A=modifier.split() del A[5:8] del A[3] A[0:3]=[&quot;&quot;.join(A[0:3])] joined=&quot; &quot;.join(A) proline_searcher=re.search('\BP',joined) if proline_searcher != None: proline_counter+=1 proline_count=re.search('^\d+',joined) if proline_counter&lt;2: sparta_file_list1.append(f'{proline_count.group(0)}PN'+' 1000'+' 1000') else: if proline_counter == 4: sparta_file_list1.append(joined) sparta_file_list1.append(f'{proline_count.group(0)}PHN'+' 1000'+' 1000') proline_counter=0 continue sparta_file_list1.append(joined) return sparta_file_list1 #The user may have a protein that has a mutation, causing the sequence of the sparta file to differ from theirs #The sparta predicted value for that mutant is useless, thus it is replaced with a placeholder def add_mutation(mutation_list1,mutation_list2,sparta_file,sparta_directory): sparta_file_list2=[] if mutation_list1==() or mutation_list2==(): for amino_acids in format_sparta(sparta_file,sparta_directory): sparta_file_list2.append(amino_acids) else: for mutations,mutations2 in zip(mutation_list1,mutation_list2): for amino_acids in format_sparta(sparta_file,sparta_directory): if re.findall(mutations,amino_acids): splitting=amino_acids.split() mutation=re.sub(mutations,mutations2,splitting[0]) mutation_value=re.sub('\d+.\d+',' 1000',splitting[1]) mutation_value2=re.sub('\d+.\d+',' 1000',splitting[2]) mutation_replacement=mutation+mutation_value+mutation_value2 sparta_file_list2.append(mutation_replacement) else: sparta_file_list2.append(amino_acids) return sparta_file_list2 #The SPARTA file may have residues beyond the scope of the users protein, those residues are filtered out def filter_sparta_using_seq(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start): sparta_file_list3=[] sparta_comparison=create_seq_list(seq_file,seq_directory,seq_start) for aa in add_mutation(mutation_list1,mutation_list2,sparta_file,sparta_directory): modifiers=aa.strip() splitter=modifiers.split() searcher=re.search('^\d+[A-Z]',splitter[0]) compiler=re.compile(searcher.group(0)) sparta_sequence_comparison=list(filter(compiler.match,sparta_comparison)) if sparta_sequence_comparison != []: sparta_file_list3.append(aa) return sparta_file_list3 #The first amino acid and last amino acid will only have 4 and 5 atom respectively, breaking the rule of 6 #If the user picks somewhere in the middle of the protein, than this is not the case, thus a check is done, and if the entire protein is not divisible by 6 #The sides are removed def check_sparta_file_boundaries(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start): residue_number=[] number_of_residues_looped_through=0 sparta_filtered_list=filter_sparta_using_seq(seq_file,seq_directory,mutation_list1,mutation_list2,sparta_file,sparta_directory,seq_start) for checker in sparta_filtered_list: remove_whitespace=checker.strip() split_values=remove_whitespace.split() exctract_residue_number=re.search('^\d+',split_values[0]) residue_number.append(exctract_residue_number.group(0)) number_of_residues_looped_through+=1 if number_of_residues_looped_through==5: if int(exctract_residue_number.group(0))==int(residue_number[0]): break else: del sparta_filtered_list[0:4] break if len(sparta_filtered_list)%6 != 0: del sparta_filtered_list[-5:-1] return sparta_filtered_list </code></pre> <pre><code>#nmrstar import re import os #The NMRSTAR file is sorted HA,C,CA,CB,H,N, we want to format it N,HA,C&lt;CA,CB,H #The below function stores the residue number of each amino acid, then stores the appropriate atom in the appropriate list #Using the residue_number_list we will know when we have moved on to the next amino acids #When you move onto the next amino acid, the previous amino acids atoms are sorted into the appropriate order def atom_ordering(exctracted_and_compiled_data): sorted_atom_types=[] residue_number_list=[] hydrogen_value=[] nitrogen_value=[] side_chain_cabonyl_values=[] x=0 for amino_acids in exctracted_and_compiled_data: splitter2=amino_acids.split() x+=1 if x &gt;= 2: if splitter2[0] != residue_number_list[0]: list_compiler=nitrogen_value+side_chain_cabonyl_values+hydrogen_value sorted_atom_types.append(list_compiler) residue_number_list.clear() hydrogen_value.clear() nitrogen_value.clear() side_chain_cabonyl_values.clear() residue_number_list.append(splitter2[0]) if splitter2[2] == 'H': hydrogen_value.append(amino_acids) elif splitter2[2] == 'N': nitrogen_value.append(amino_acids) else: side_chain_cabonyl_values.append(amino_acids) else: if splitter2[2] == 'H': hydrogen_value.append(amino_acids) elif splitter2[2] == 'N': nitrogen_value.append(amino_acids) else: side_chain_cabonyl_values.append(amino_acids) else: residue_number_list.append(splitter2[0]) if splitter2[2] == 'H': hydrogen_value.append(amino_acids) elif splitter2[2] == 'N': nitrogen_value.append(amino_acids) else: side_chain_cabonyl_values.append(amino_acids) return sorted_atom_types #Due to the above concatenation of lists, we form a list of lists that needs to be flattened_list #Additionally, we wish to add a hyphen between the residue number and atom type that will be used for regex later def flatten_list(exctracted_and_compiled_data): flattened_list=[] for lists in atom_ordering(exctracted_and_compiled_data): for elements in lists: splitting=elements.split() joined=''.join(splitting[0:2]) flattened_list.append(joined+'-'+splitting[2]+ ' ' + splitting[3]) return flattened_list #Not every residue will have a chemical shift value for every atom types #We want to fill in placeholders for all the missing data, but maintain that N,HA,C,CA,CB,H format #At this point, every atom will only have the 6 desired atom types, in the appropriate atom order #Therefore, we go through every atom for each amino acid, and check to see if we have data for that atom types in the N,HA,C order def fill_empty_data(exctracted_and_compiled_data): missing_values_added=[] atom_value_holder=[] count=0 for values in flatten_list(exctracted_and_compiled_data): atom_find=re.search('^-*\d+[A-Z]',values) count+=1 atom_value_holder.append(atom_find.group(0)) if count == 1: if re.findall('-N',values) != []: missing_values_added.append(values+'\n') else: missing_values_added.append(atom_value_holder[0]+'-N'+' 1000'+'\n') count+=1 if count == 2: if re.findall('-HA',values) != []: missing_values_added.append(values+'\n') else: missing_values_added.append(atom_value_holder[0]+'-HA'+' 1000'+'\n') count+=1 if count == 3: if re.findall('-C\s',values) != []: missing_values_added.append(values+'\n') else: missing_values_added.append(atom_value_holder[0]+'-C'+' 1000'+'\n') count+=1 if count == 4: if re.findall('-CA',values) != []: missing_values_added.append(values+'\n') else: missing_values_added.append(atom_value_holder[0]+'-CA'+' 1000'+'\n') count+=1 if count == 5: if re.findall('-CB',values) != []: missing_values_added.append(values+'\n') else: missing_values_added.append(atom_value_holder[0]+'-CB'+' 1000'+'\n') count+=1 if count == 6: if re.findall('-H\s',values) != []: missing_values_added.append(values+'\n') count=0 atom_value_holder.clear() else: missing_values_added.append(atom_value_holder[0]+'-H'+' 1000'+'\n') atom_value_holder.clear() if re.findall('-N',values) != []: missing_values_added.append(values+'\n') count=1 if re.findall('-HA',values) != []: missing_values_added.append(atom_find.group(0)+'-N'+' 1000'+'\n') missing_values_added.append(values+'\n') count=2 if re.findall('-C',values) != []: missing_values_added.append(atom_find.group(0)+'-N'+' 1000'+'\n') missing_values_added.append(atom_find.group(0)+'-HA'+' 1000'+'\n') missing_values_added.append(values+'\n') count=3 if re.findall('-CA',values) != []: missing_values_added.append(atom_find.group(0)+'-N'+' 1000'+'\n') missing_values_added.append(atom_find.group(0)+'-HA'+' 1000'+'\n') missing_values_added.append(atom_find.group(0)+'-C'+' 1000'+'\n') missing_values_added.append(values+'\n') count=4 if re.findall('-CB',values) != []: missing_values_added.append(atom_find.group(0)+'-N'+' 1000'+'\n') missing_values_added.append(atom_find.group(0)+'-HA'+' 1000'+'\n') missing_values_added.append(atom_find.group(0)+'-C'+' 1000'+'\n') missing_values_added.append(atom_find.group(0)+'-CA'+' 1000'+'\n') missing_values_added.append(values+'\n') count=5 return missing_values_added #Glycines do not have CBs, and they have additional HA. The above script will add an CB, this creates a new list without it def add_glycine_HA(exctracted_and_compiled_data): glycine_search_list=[] for stuff in fill_empty_data(exctracted_and_compiled_data): if re.findall('\BG-HA',stuff) != []: splitting=stuff.split() glycine_search_list.append(stuff) glycine_search_list.append(splitting[0]+'2'+' 1000'+'\n') elif re.findall('\BG-CB',stuff) != []: pass else: glycine_search_list.append(stuff) return glycine_search_list #This function creates a dictionary of residue numbers to residue type, that will be used below dict={} def dict_create(seq_file,seq_start,seq_directory): os.chdir(seq_directory) x=(0+seq_start)-1 global dict dict={} with open(seq_file) as sequence_file: for line in sequence_file: white_spaces_removed=line.strip().upper() for word in white_spaces_removed: x+=1 dict[x]=word #The above function filled in missing data only for amino acids that had some data, but were missing data for other atom types #This fills in placeholders for amino acids that have no data for any atom type def fill_missing_data(exctracted_and_compiled_data,seq_start): outskirts_added=[] current_amino_acid=[] x=0 y=0 for atoms in add_glycine_HA(exctracted_and_compiled_data): A=re.search('^-*\d+',atoms) outskirts_added.append(atoms) x+=1 y+=1 if x == 6: if len(current_amino_acid)&gt;0: if int(current_aa_residue_number) == (int(current_amino_acid[0])+1): x=0 current_amino_acid.clear() current_amino_acid.append(current_aa_residue_number) pass else: number_of_missing_amino_acid=int(current_amino_acid[0])+1 offset=0 while number_of_missing_amino_acid != int(current_aa_residue_number): outskirts_added.insert((y+offset-6),f'{number_of_missing_amino_acid}{dict[number_of_missing_amino_acid]}N-H' + ' 1000' +'\n') outskirts_added.insert((y+offset-6),f'{number_of_missing_amino_acid}{dict[number_of_missing_amino_acid]}N-CB' + ' 1000' +'\n') outskirts_added.insert((y+offset-6),f'{number_of_missing_amino_acid}{dict[number_of_missing_amino_acid]}N-CA' + ' 1000' +'\n') outskirts_added.insert((y+offset-6),f'{number_of_missing_amino_acid}{dict[number_of_missing_amino_acid]}N-C' + ' 1000' +'\n') outskirts_added.insert((y+offset-6),f'{number_of_missing_amino_acid}{dict[number_of_missing_amino_acid]}N-HA' + ' 1000' +'\n') outskirts_added.insert((y+offset-6),f'{number_of_missing_amino_acid}{dict[number_of_missing_amino_acid]}N-HN' + ' 1000' + '\n') number_of_missing_amino_acid+=1 offset+=6 x=0 y+=offset current_amino_acid.clear() current_amino_acid.append(current_aa_residue_number) else: current_amino_acid.append(current_aa_residue_number) x=0 return outskirts_added </code></pre> <pre><code>#NMRSTAR file input (this is only a portion to get an idea on the format Content for NMR-STAR saveframe, &quot;assigned_chem_shift_list_1&quot; save_assigned_chem_shift_list_1 _Assigned_chem_shift_list.Sf_category assigned_chemical_shifts _Assigned_chem_shift_list.Sf_framecode assigned_chem_shift_list_1 _Assigned_chem_shift_list.Entry_ID 26909 _Assigned_chem_shift_list.ID 1 _Assigned_chem_shift_list.Sample_condition_list_ID 1 _Assigned_chem_shift_list.Sample_condition_list_label $sample_conditions_1 _Assigned_chem_shift_list.Chem_shift_reference_ID 1 _Assigned_chem_shift_list.Chem_shift_reference_label $chemical_shift_reference_1 _Assigned_chem_shift_list.Chem_shift_1H_err . _Assigned_chem_shift_list.Chem_shift_13C_err . _Assigned_chem_shift_list.Chem_shift_15N_err ... #part we are interested in 1 . 1 1 2 2 SER HA H 1 4.477 0.003 . 1 . . . . . -1 Ser HA . 26909 1 2 . 1 1 2 2 SER HB2 H 1 3.765 0.001 . 1 . . . . . -1 Ser HB2 . 26909 1 3 . 1 1 2 2 SER HB3 H 1 3.765 0.001 . 1 . . . . . -1 Ser HB3 . 26909 1 4 . 1 1 2 2 SER C C 13 173.726 0.2 . 1 . . . . . -1 Ser C . 26909 1 5 . 1 1 2 2 SER CA C 13 58.16 0.047 . 1 . . . . . -1 Ser CA . 26909 1 6 . 1 1 2 2 SER CB C 13 64.056 0.046 . 1 . . . . . -1 Ser CB . 26909 1 7 . 1 1 3 3 HIS H H 1 8.357 0.004 . 1 . . . . . 0 His H . 26909 1 8 . 1 1 3 3 HIS HA H 1 4.725 0.003 . 1 . . . . . 0 His HA . 26909 1 9 . 1 1 3 3 HIS HB2 H 1 3.203 0.003 . 2 . . . . . 0 His HB2 . 26909 1 10 . 1 1 3 3 HIS HB3 H 1 2.996 0.005 . 2 . . . . . 0 His HB3 . 26909 1 11 . 1 1 3 3 HIS C C 13 174.33 0.2 . 1 . . . . . 0 His C . 26909 1 12 . 1 1 3 3 HIS CA C 13 55.353 0.044 . 1 . . . . . 0 His CA . 26909 1 13 . 1 1 3 3 HIS CB C 13 31.166 0.043 . 1 . . . . . 0 His CB . 26909 1 14 . 1 1 3 3 HIS N N 15 120.402 0.041 . 1 . . . . . 0 His N . 26909 1 </code></pre> <pre><code>#SPARTA file format (again, only an excerpt) REMARK SPARTA+ Protein Chemical Shift Prediction Table REMARK All chemical shifts are reported in ppm: ... #part we are interested in 1 M HA 0.000 4.384 4.480 -0.161 0.000 0.227 1 M C 0.000 176.242 176.300 -0.096 0.000 1.140 1 M CA 0.000 55.217 55.300 -0.139 0.000 0.988 1 M CB 0.000 32.488 32.600 -0.187 0.000 1.302 2 I N 1.287 121.802 120.570 -0.092 0.000 2.680 2 I HA -0.123 4.012 4.170 -0.058 0.000 0.286 2 I C -0.818 175.259 176.117 -0.066 0.000 1.144 ... </code></pre>
[]
[ { "body": "<h2>Working directory</h2>\n<p>It's not necessary to do this:</p>\n<pre><code> os.chdir(nmrstarfile_directory)\n</code></pre>\n<p>and having other code rely on the working directory makes that code more fragile and debugging trickier. <code>pathlib</code> has excellent facilities for building full paths off of a base path.</p>\n<h2>Regular expressions</h2>\n<p>This regex:</p>\n<pre><code> extract_data_only=re.search(r'\\b\\d+\\s+[A-Z]{3}\\s+\\w+\\s+\\w+\\s+\\d+\\s+\\d+',modifier)\n</code></pre>\n<p>would benefit from being <code>re.compile</code>'d outside of your loops - maybe as a global constant, or at the least near the top of the function. That way you don't have to re-compile it on every loop iteration.</p>\n<h2>Unpacking</h2>\n<pre><code> amino_acid_number=str(int(split_data[5])+int(seq_start)-1)\n residue_type=split_data[6]\n atom_type=split_data[7]\n converted=acid_map[residue_type]\n chemical_shift=split_data[10]\n</code></pre>\n<p>if you only need items 5-10, then</p>\n<pre><code>amino_acid, residue_type, atom_type, _, _, chemical_shift = split_data[5:11]\n</code></pre>\n<p>Generally, you should avoid repeated references to difficult-to-understand index expressions like <code>splitter2[0]</code>. Attempt to give them their own meaningfully-named variable.</p>\n<h2>Set membership</h2>\n<pre><code>if atom_type == 'N' or atom_type == 'HA' or atom_type =='CA' or atom_type == 'CB' or atom_type=='H' or atom_type=='C':\n \n</code></pre>\n<p>can be</p>\n<pre><code>if atom_type in {'N', 'HA', 'CA', 'CB', 'H', 'C'}:\n</code></pre>\n<p>That set should likely be stored outside of the function as a constant.</p>\n<h2>Imports</h2>\n<p>Don't do these:</p>\n<pre><code> from sparta_file_formatter import check_sparta_file_boundaries\n from nmrstar import dict_create\n from nmrstar import fill_missing_data\n</code></pre>\n<p>in the middle of your function. Do them at the top of the file.</p>\n<h2>String interpolation</h2>\n<pre><code>atom_value_holder[0]+'-C'+' 1000'+'\\n'\n</code></pre>\n<p>can be</p>\n<pre><code>f'{atom_value_holder[0]}-C 1000\\n'\n</code></pre>\n<p>Even if you didn't use an f-string, there is no need to separate those last three string literals into concatenations.</p>\n<h2>Extend</h2>\n<pre><code> missing_values_added.append(atom_find.group(0)+'-N'+' 1000'+'\\n')\n missing_values_added.append(atom_find.group(0)+'-HA'+' 1000'+'\\n')\n missing_values_added.append(atom_find.group(0)+'-C'+' 1000'+'\\n')\n missing_values_added.append(atom_find.group(0)+'-CA'+' 1000'+'\\n')\n</code></pre>\n<p>should be</p>\n<pre><code>atom = atom_find.group(0)\nmissing_values_added.extend((\n f'{atom}-N 1000\\n',\n f'{atom}-HA 1000\\n',\n f'{atom}-C 1000\\n',\n f'{atom}-CA 1000\\n',\n))\n</code></pre>\n<h2>Checking for any match</h2>\n<p>Do not use <code>findall</code> here:</p>\n<pre><code>re.findall('\\BG-CB',stuff) != []\n</code></pre>\n<p>Use <code>search</code>. If it returns <code>None</code>, there are no hits; otherwise there is at least one hit; pair this with <code>is not None</code>.</p>\n<h2>Shadowing</h2>\n<p>This:</p>\n<pre><code>dict={}\n</code></pre>\n<p>is nasty, and setting you up for failure. <code>dict</code> is a (very commonly used) built-in name, so don't shadow it with your own variable - <em>particularly</em> at the global level.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T22:25:19.940", "Id": "480539", "Score": "0", "body": "A couple of questions. 1) Why would I use pathlib versus os? I use it to determine the directory, since the user may have files in different directories. 2) I'm a bit confused by what you mean by \"recompile it every loop\". 3) For unpacking, does putting an underscore _, mean that value will not be taken? Because I don't want everything from 5:11, only 6,7 and 10. 4) For membership, why would I leave these outside of the function as constants? What difference would it make inside vs outside? 5) I'm not too faimilar with extend, however it appears you can't index it (which is crucial)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T22:26:52.107", "Id": "480540", "Score": "0", "body": "_Why would I use pathlib versus os_ - `pathlib.Path` is a nice, self-contained, object-oriented representation of a path, whereas the `os` methods use an older, more procedural style. It's a matter of convenience and aesthetics." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T22:28:43.807", "Id": "480541", "Score": "0", "body": "_recompile it every loop_ - if you call `re.search` / `re.match`, it has to parse your regex all over again, and in the middle of a loop (such as iterating over file lines) this may prove costly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T22:29:32.733", "Id": "480542", "Score": "0", "body": "_does putting an underscore _, mean that value will not be taken?_ By convention, yes; it indicates you won't use that variable but it has to exist for the syntax to be correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T22:30:29.770", "Id": "480543", "Score": "0", "body": "_For membership, why would I leave these outside of the function as constants?_ If that set of strings is fundamental to the program and reused anywhere else; I'd be surprised if that's the only place that could use it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T22:31:59.850", "Id": "480544", "Score": "0", "body": "I don't know what you mean by _you can't index [extend]_. `extend` is a function that adds an iterable to the end of a list. The list can still be indexed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T04:17:50.200", "Id": "480548", "Score": "0", "body": "Thank you for the explanations! As for membership, that set of strings is only used there. And is there an advantage for using extend over insert?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T22:13:54.247", "Id": "244757", "ParentId": "244753", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T21:51:34.790", "Id": "244753", "Score": "2", "Tags": [ "python" ], "Title": "NMRSTAR and,SPARTA file converter for Data RMSD calculations" }
244753
<p>I am a beginner programmer and I would like to improve in coding and develop my skills. That is why I am asking this question, what should I focus on improving in this code ?</p> <pre><code>import random import re # this is the file that contains all the words from words import words # the word that the user needs to guess the_guess_word = random.choice(words) n = 0 t = 0 # puts the random picked word in a list l_guess = list(the_guess_word) box = l_guess # somethings are not yet finished print(&quot;Welcome To The Guessing Game . \n You get 6 Guesses . The Words Are In Dutch But There Is 1 English Word . &quot; f&quot;\n \n Your Word Has {len(the_guess_word)} letters &quot;) class hangman(): t = len(box) right_user_input = [] # should create the amount of letters in the word right_user_input = [&quot;.&quot; for i in range(len(the_guess_word))] k = len(right_user_input) while True: # the user guesses the letter user_guess = input(&quot;guess the word : &quot;) # if user guesses it wrong 6 times he or she loses if n &gt;= 6 : print(&quot;you lose!&quot;) print(f'\n the word was {the_guess_word}') break # loops over until user gets it right or loses if user_guess not in the_guess_word: print(&quot;\n wrong guess try again &quot;) n += 1 if len(user_guess) &gt; 1 : print(&quot;chose 1 letter not mulitple words &quot;) # when user gets it right the list with the dots gets replaced by the guessed word of the user if user_guess in the_guess_word : print(&quot;you got it right&quot;) # finds the position of the guessed word in the to be guessed the word for m in re.finditer(user_guess, the_guess_word): right_user_input[m.end()-1] = user_guess print(right_user_input) # checks to see if user guessed all the words right if '.' not in right_user_input: # user now needs to put in the full word to finish the game. final = input(&quot;what is the final word? : &quot;) if final == the_guess_word: print('YOU GOT IT ALL RIGHT GOOD JOB !!!') break # loses if he gets it wrong end ends the game else: print(&quot;you got it wrong , you lose ! &quot;) break </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T07:16:54.610", "Id": "480569", "Score": "0", "body": "is words a python file? Shouldn't it be a text file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T12:33:37.743", "Id": "480589", "Score": "0", "body": "It's unclear what n and t are, can you explain more plz?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T15:51:14.520", "Id": "480606", "Score": "0", "body": "@VisheshMangla the 't' was not useful . i forgot to take it out and for the python file . i don't know how it would work if i tried to implement the text file ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T16:15:54.973", "Id": "480608", "Score": "0", "body": "Please see the edits. Please also add a larger summary of your problem with explanation of what you are doing. Not everyone knows hangman here but we do know python." } ]
[ { "body": "<p><strong>Cleaner print with <code>implicit string concatenation</code></strong></p>\n<pre><code>print(&quot;Welcome To The Guessing Game .&quot; \n &quot;\\n You get 6 Guesses .&quot;\n &quot;The Words Are In Dutch But There Is 1 English Word.&quot;\n &quot;\\n \\n Your Word Has {len(the_guess_word)} letters &quot;)\n</code></pre>\n<p><strong>This</strong></p>\n<pre><code>right_user_input = [&quot;.&quot; for i in range(len(the_guess_word))]\n</code></pre>\n<p>can be</p>\n<pre><code>right_user_input = [&quot;.&quot;]*len(the_guess_word)\n</code></pre>\n<p><strong>Rename variables</strong></p>\n<pre><code>n to chances_over/counter/chances_provided\nt to box_length\n</code></pre>\n<p><strong>Remove unnecessary initialization of variables</strong></p>\n<pre><code>right_user_input = []\nt = 0\n</code></pre>\n<p><strong>Take out while loop out of the class</strong></p>\n<p><strong>Edit:</strong>\nYou might like : <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">Dataclasses</a> after reading @AJNeufeld post</p>\n<p>For using a txt file to store list of words follow these steps.</p>\n<p>Create a text file with list of all words each in a new line.\nThen use</p>\n<pre><code>with open(&quot;filename.txt&quot;) as fp:\n words = fp.readlines() # words = [&quot;apple&quot;, &quot;grapes&quot;, .... ]\n</code></pre>\n<p>Alternatively you can store a Python object in a <code>pickle(.pk)</code> file.See <a href=\"https://docs.python.org/3/library/pickle.html\" rel=\"nofollow noreferrer\">Pickle</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T12:32:52.693", "Id": "244784", "ParentId": "244761", "Score": "2" } }, { "body": "<h1>Classes</h1>\n<p>You have completely failed at implementing a class.</p>\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8 -- Style Guide for Python</a> suggests naming conventions that every Python program should (must!) follow. For classes,\n<code>CapWords</code> should be used, so <code>class hangman():</code> should be <code>class Hangman:</code> or perhaps <code>class HangMan:</code>.</p>\n<p>But more seriously, your entire class implementation is broken.</p>\n<p>Python scripts are executed, line-by-line, from top to bottom, unless loops, control structures, or call statements cause a branch to another location. A <code>def</code> statement is &quot;executed&quot; by recording the indented program lines, and storing them under the function's name. This means a function doesn't exist until it is executed. For example, consider this script:</p>\n<pre><code>try:\n f() # Call a non-existent function\nexcept NameError:\n print(&quot;The f() function doesn't exist&quot;)\n\ndef f(): # Create the &quot;f&quot; function\n print(&quot;Hello&quot;)\n\nf() # Call the &quot;f&quot; function, and &quot;Hello&quot; is printed.\n\ndef f(): # Change the &quot;f&quot; function by defining a new one.\n print(&quot;Goodbye&quot;)\n\nf() # Call the &quot;f&quot; function, and now &quot;Goodbye&quot; is printed.\n</code></pre>\n<p>Similarly, when a <code>class</code> statement is executed, it creates a new namespace and executes indented statements in that namespace, such that any <code>def</code> statements record code as named methods inside that class namespace. Other statements &quot;executed&quot; in the class's name space are intended to create class global variables. You are not supposed to execute complex code directly inside the class definition; code should be inside methods defined inside <code>def</code> statements inside the class.</p>\n<p>You don't have a statements creating class global variables inside <code>class hangman():</code>; you have statements executing code in loops, with conditionals. It isn't until the entire execution of the guessing game is complete that the class namespace being constructed finally saved under the <code>hangman</code> name. In short, the class definition isn't finished and the <code>hangman</code> class finally defined until the the moment program exits, so the class was completely useless.</p>\n<p>A proper class definition should look more like:</p>\n<pre><code>class Hangman:\n\n MAX_GUESSES = 6\n\n def __init__(self, secret_word):\n self._secret_word = secret_word\n self._guesses = 0\n self._right_user_input = &quot;.&quot; * len(secret_word)\n\n def _check_guess(self, letter):\n ... code to check a user guess\n\n def play(self):\n print(f&quot;&quot;&quot;Welcome To The Guessing Game .\nYou get 6 Guesses . The Words Are In Dutch But There Is 1 English Word .\n\nYour Word Has {len(self._secret_word)} letters&quot;&quot;&quot;)\n\n for _ in range(Hangman.MAX_GUESSES):\n user_guess = input( ... )\n self._check_guess(user_guess)\n ...\n\n else:\n print(&quot;You lose!&quot;)\n print(f&quot;The word was {self._secret_word}&quot;)\n\nif __name__ == '__main__':\n the_guess_word = random.choice(words)\n game = Hangman(the_guess_word)\n game.play()\n</code></pre>\n<p>Of course, much here has been omitted.</p>\n<p>Note the use of <code>self</code> in the class methods. Note the use of <code>Hangman(the_guess_word)</code> which creates an instance of the <code>Hangman</code> class, and assigns it to <code>game</code>, and then <code>game.play()</code> calls the <code>play(self)</code> method of the <code>Hangman</code> class with the <code>game</code> object as <code>self</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T16:05:34.360", "Id": "480607", "Score": "0", "body": "WOW , I didn't know that . I appreciate you telling me this . I will work on implementing this in the future projects. You have been a BIG HELP thanks !!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T15:54:08.110", "Id": "244791", "ParentId": "244761", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T23:32:27.503", "Id": "244761", "Score": "4", "Tags": [ "python", "random", "hangman" ], "Title": "Mini guessing-game" }
244761
<p>I've started learning bash today, but I knew basics of javascript.</p> <p>It would be very nice if anyone can point me at least a few advices on the code.</p> <p>Because there are so many details in bash, I hope you won't be too harsh.</p> <p><strong>Expected behavior</strong></p> <p>The code is supposed:</p> <ul> <li>to set the value of a variable named 'charge' from the input files</li> <li>create a few directories and subdirectories based on the input files</li> </ul> <p><strong>Concrete Example</strong></p> <p>Let's say there is a mol2 file named <code>glucose-minus1.mol2</code>.</p> <ul> <li>I expect the code to set up a variable charge with value -1, so charge=&quot;-1&quot;. So you can see there is a translation from minus1 --&gt; -1 If the filename is 'wrong' the user should be notified &quot;we can't find the charge value in the filename&quot; or something like that.</li> <li>And to create a directory named <code>glucose-minus1</code> (without the extension) plus the 3 sub-directories &quot;solv&quot; &quot;sin-solv&quot; and &quot;thermo&quot;. All this if the directories are do no exist already.</li> </ul> <pre><code>#!/bin/bash touch &quot;mol-minus1.mol2&quot; &quot;mol-minus2.mol2&quot; molecules=(*.mol2) subdirs=(&quot;solv&quot; &quot;sin-solv&quot; &quot;thermo&quot;) setCharge () { #input molfile #if it finds any chargeLabel in molfile, sets the charge value (and we use it later). chargeLabels=( &quot;minus3&quot; &quot;minus2&quot; &quot;minus1&quot; &quot;cero&quot; &quot;plus1&quot; &quot;plus2&quot; ) charges=(&quot;-3&quot; &quot;-2&quot; &quot;-1&quot; &quot;0&quot; &quot;+1&quot; &quot;+2&quot;) echo &quot;${chargeLabels[*]}&quot; for index in &quot;${!chargeLabels[@]}&quot; do if [[ &quot;$1&quot; == *&quot;${chargeLabels[index]}&quot;* ]] then charge=&quot;${charges[index]}&quot; echo &quot;$charge&quot; else echo &quot;Im not setting charges...&quot; continue fi done } createDir(){ #pass dir as an argument. if [ ! -d &quot;$1&quot; ] then mkdir &quot;$1&quot; else printf &quot; %s is already there &quot; &quot;$1&quot; fi } for mol in &quot;${molecules[@]}&quot; do [ -f &quot;$mol&quot; ] || exit 0 #sets the carge variable to a value included in molfile. echo &quot;$mol&quot; setCharge &quot;$mol&quot; #acreate molecule directory if not there. IFS=&quot;.&quot; read -ra splitted &lt;&lt;&lt; &quot;$mol&quot; if [[ ! -d &quot;${splitted[0]}&quot; ]] then mkdir &quot;${splitted[0]}&quot; printf &quot;directory %s has been created. Molecule charge is %s&quot; &quot;${splitted[0]}&quot; &quot;$charge&quot; else printf &quot;directory %s already exists. Molecule charge is %s&quot; &quot;${splitted[0]}&quot; &quot;$charge&quot; continue fi #create subdirectories if not there. cd &quot;${splitted[0]}&quot; || printf &quot;No directory with name %s&quot; &quot;${splitted[0]}&quot; &amp;&amp; exit 0 for dir in &quot;${subdirs[@]}&quot; #create subdirs if not there. do createDir &quot;$dir&quot; done cd '../' #single quotes for string literals. cp &quot;$mol&quot; &quot;${splitted[0]}/sin-solv/&quot; #python -c'import flexo_api.py; flexo_api.flexo(&quot;$)' done <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-29T23:47:11.980", "Id": "244762", "Score": "1", "Tags": [ "bash" ], "Title": "a beginner's approach & confusion bash script" }
244762
<p>The source code within this question aims to provide a <em>short-cut</em> for mirroring a local XWindow (or session) to a remote host via SSH port forwarding, such as:</p> <pre><code>x11vnc-push-xwindow --id=none raspberrypi </code></pre> <p>The <a href="https://github.com/rpi-curious/x11vnc-push-xwindow/tree/main/.github" rel="nofollow noreferrer" title="Documentation for x11vnc-push-xwindow project">Readme</a> file contains more detailed instructions for setup, but the TLDR is...</p> <ul> <li><p>Clone</p> <pre><code>mkdir -vp ~/git/hub/rpi-curious cd ~/git/hub/rpi-curious git clone --recurse-submodules git@github.com:rpi-curious/x11vnc-push- xwindow.git </code></pre> </li> <li><p>Link/Install</p> <pre><code>cd x11vnc-push-xwindow ln -s &quot;${PWD}/x11vnc-push-xwindow&quot; &quot;${HOME}/bin/&quot; </code></pre> </li> <li><p>Use</p> <pre><code>x11vnc-push-xwindow raspberrypi ## Select a XWindow, or use `--id=none` to mirror entire session # x11vnc-push-xwindow --id=none raspberrypi </code></pre> </li> <li><p>Exit when done</p> <pre><code>q # Ctrl^c </code></pre> </li> </ul> <p>I wrote this project because it helps my own posture to look up at my remote device's screen, and currently everything seems to function as intended, but as always there's room for improvement.</p> <h2>Questions</h2> <ul> <li><p>Are there any obvious mistakes?</p> </li> <li><p>Any features that are both missing and necessary?</p> </li> <li><p>Is there a better way to fully terminate the connection when <kbd>q</kbd> is pressed? Currently this is a two-step process of pressing <kbd>q</kbd> then <kbd>Ctrl</kbd><kbd>c</kbd> to quit and then terminate the connection.</p> </li> </ul> <hr /> <h2>Source Code</h2> <blockquote> <p>Note, source code for this question is maintained on GitHub at <a href="https://github.com/rpi-curious/x11vnc-push-xwindow/blob/main/x11vnc-push-xwindow" rel="nofollow noreferrer" title="Main source code for x11vnc-push-xwindow project">rpi-curious/x11vnc-push-xwindow</a>, what is included here are the scripts and shared functions required to test/review without need of any Git <em>fanciness</em>.</p> </blockquote> <h3><a href="https://github.com/rpi-curious/x11vnc-push-xwindow/blob/main/x11vnc-push-xwindow" rel="nofollow noreferrer" title="Main source code for x11vnc-push-xwindow project">x11vnc-push-xwindow</a></h3> <pre><code>#!/usr/bin/env bash ## Find true directory script resides in, true name, and true path __SOURCE__=&quot;${BASH_SOURCE[0]}&quot; while [[ -h &quot;${__SOURCE__}&quot; ]]; do __SOURCE__=&quot;$(find &quot;${__SOURCE__}&quot; -type l -ls | sed -n 's@^.* -&gt; \(.*\)@\1@p')&quot; done __DIR__=&quot;$(cd -P &quot;$(dirname &quot;${__SOURCE__}&quot;)&quot; &amp;&amp; pwd)&quot; __NAME__=&quot;${__SOURCE__##*/}&quot; __AUTHOR__='S0AndS0' __DESCRIPTION__='Pushes/mirrors selected XWindow to remote via SSH port forwarding' ## Source module code within this script source &quot;${__DIR__}/shared_functions/modules/argument-parser/argument-parser.sh&quot; source &quot;${__DIR__}/shared_functions/modules/trap-failure/failure.sh&quot; trap 'failure &quot;LINENO&quot; &quot;BASH_LINENO&quot; &quot;${BASH_COMMAND}&quot; &quot;${?}&quot;' ERR __license__(){ local _date_year=&quot;$(date +'%Y')&quot; cat &lt;&lt;EOF ${__DESCRIPTION__} Copyright (C) ${_date_year:-2020} ${__AUTHOR__:-S0AndS0} This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. EOF } usage() { local _message=&quot;${1}&quot; cat &lt;&lt;EOF ${__DESCRIPTION__} ## Augments ${__NAME__%.*} responds to --help | -h Prints this message and exits --x11vnc-listen-port=&quot;${_x11vnc_listen_port}&quot; Default '5900', port that x11vnc will serve XWindow session on 'localhost' for this device. Note, if listen port is already in use then session will be reused, otherwise a new session will be initialized. --vnc-viewer-port=&quot;${_vnc_viewer_port}&quot; Default '5900', port that remote host will connect to on their relative 'localhost' to view forwarded XWindow session. Note, if 'xscreensaver' is detected on remote host, then it will be disabled until x11vnc session is terminated --vnc-viewer-name=&quot;${_vnc_viewer_name}&quot; Default 'vncviewer', executable name of VNC Viewer. Note, if troubles are had when using a VNC Viewer other than 'vncviewer', please try 'vncviewer' before opening a new Issue. --id=&quot;${_id}&quot; Default 'pick', XWindow ID to forward to remote host. Note, if set to 'none' then entire XWindow session will be forwarded. ${_target_host:-&lt;target-host&gt;} Required, remote SSH host that XWindow session will be forwarded to. ## Example ${__NAME__} raspberrypi EOF [[ &quot;${#_message}&quot; -gt '0' ]] &amp;&amp; { printf &gt;&amp;2 '\n## Error: %s\n' &quot;${_message}&quot; } } ## Defaults _target_host='' _x11vnc_listen_port='5900' _vnc_viewer_port='5900' _id='pick' _vnc_viewer_name='vncviewer' ## Save passed arguments and acceptable arguments to Bash arrays _passed_args=(&quot;${@:?No arguments provided}&quot;) _acceptable_args=( '--help|-h:bool' '--x11vnc-listen-port:alpha_numeric' '--vnc-viewer-port:alpha_numeric' '--id:alpha_numeric' '--target-host:path-nil' ) ## Pass arrays by reference/name to the `argument_parser` function argument_parser '_passed_args' '_acceptable_args' _exit_status=&quot;$?&quot; ## Print documentation for the script and exit, or allow further execution ((_help)) || ((_exit_status)) &amp;&amp; { usage exit &quot;${_exit_status:-0}&quot; } ((&quot;${#_target_host}&quot;)) || { usage 'Missing target host parameter' exit 1 } ## Note, '-shared' with '-forever' and '-threads' or '-once' may be wanted ## in addition to the following options _x11vnc_server_opts=( '-quiet' '-noshared' '-viewonly' '-noremote' '-nobell' '-nosel' '-noprimary' '-nosetprimary' '-noclipboard' '-nosetclipboard' # '-disablefiletransfer' ## Un-comment for older versions '-cursor' 'most' '-noipv6' '-allow' '127.0.0.1' '-autoport' &quot;${_x11vnc_listen_port}&quot; '-listen' '127.0.0.1' '-nopw' '-nossl' '-bg' ) [[ &quot;${_id}&quot; =~ 'none' ]] || { _x11vnc_server_opts+=( '-id' &quot;${_id}&quot; ) } _vnc_viewer_opts=( '-viewonly' '-fullscreen' &quot;localhost::${_vnc_viewer_port}&quot; ) grep -q -- &quot;${_x11vnc_listen_port}&quot; &lt;&lt;&lt;&quot;$(netstat -plantu 2&gt;/dev/null)&quot; || { printf '# Running: x11vnc %s\n' &quot;${_x11vnc_server_opts[*]}&quot; x11vnc ${_x11vnc_server_opts[@]} } initialize_connection() { ssh -R localhost:${_vnc_viewer_port}:localhost:${_x11vnc_listen_port} &quot;${_target_host}&quot; &lt;&lt;EOF reinitalize_xscreensaver(){ echo 'Resuming: xscreensaver' DISPLAY=:0 xscreensaver -no-splash 2&gt;&amp;1 &gt;/dev/null &amp; sleep 3 DISPLAY=:0 xscreensaver-command -activate } initalize_viewer(){ _xscreensaver_time=&quot;<span class="math-container">\$(DISPLAY=:0 xscreensaver-command -time 2&gt;&amp;1)" [[ "\$</span>{_xscreensaver_time}&quot; =~ 'no screensaver is running' ]] || { trap 'reinitalize_xscreensaver' RETURN SIGINT SIGTERM EXIT echo 'Halting: xscreensaver' DISPLAY=:0 xscreensaver-command -deactivate DISPLAY=:0 xscreensaver-command -exit } printf 'Starting: <span class="math-container">\$(which ${_vnc_viewer_name}) %s\n' "${_vnc_viewer_opts[*]}" DISPLAY=:0 \$</span>(which ${_vnc_viewer_name}) ${_vnc_viewer_opts[@]} return &quot;${?}&quot; } initalize_viewer EOF } initialize_connection &amp; _connection_pid=&quot;$!&quot; printf 'Press %s to quit...\n' &quot;q&quot; while read -n1 -r _input; do case &quot;${_input,,}&quot; in q) printf 'Killing PID %i\n' &quot;${_connection_pid}&quot; kill &quot;${_connection_pid}&quot; sleep 2 printf 'Please use Ctrl^c to exit!' ;; esac sleep 1 done </code></pre> <hr /> <h3><a href="https://github.com/bash-utilities/argument-parser/blob/master/argument-parser.sh" rel="nofollow noreferrer" title="Main source code for argument-parser project">shared_functions/modules/argument-parser/argument-parser.sh</a></h3> <pre><code>#!/usr/bin/env bash # argument-parser.sh, source it in other Bash scripts for argument parsing # Copyright (C) 2019 S0AndS0 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation; version 3 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. shopt -s extglob _TRUE='1' _DEFAULT_ACCEPTABLE_ARG_LIST=('--help|-h:bool' '--foo|-f:print' '--path:path-nil') arg_scrubber_alpha_numeric(){ printf '%s' &quot;${@//[^a-z0-9A-Z]/}&quot;; } arg_scrubber_regex(){ printf '%s' &quot;$(sed 's@.@\\.@g' &lt;&lt;&lt;&quot;${@//[^[:print:]$'\t'$'\n']/}&quot;)&quot;; } arg_scrubber_list(){ printf '%s' &quot;$(sed 's@\.\.*@.@g; s@--*@-@g' &lt;&lt;&lt;&quot;${@//[^a-z0-9A-Z,+_./@:-]/}&quot;)&quot; } arg_scrubber_path(){ printf '%s' &quot;$(sed 's@\.\.*@.@g; s@--*@-@g' &lt;&lt;&lt;&quot;${@//[^a-z0-9A-Z ~+_./@:-]/}&quot;)&quot; } arg_scrubber_posix(){ _value=&quot;${@//[^a-z0-9A-Z_.-]/}&quot; _value=&quot;$(sed 's@^[-_.]@@g; s@[-_.]$@@g; s@\.\.*@.@g; s@--*@-@g' &lt;&lt;&lt;&quot;${_value}&quot;)&quot; printf '%s' &quot;${_value::32}&quot; } return_scrubbed_arg(){ _raw_value=&quot;${1}&quot; _opt_type=&quot;${2:?## Error - no option type provided to return_scrubbed_arg}&quot; case &quot;${_opt_type}&quot; in 'bool'*) _value=&quot;${_TRUE}&quot; ;; 'raw'*) _value=&quot;${_raw_value}&quot; ;; 'path'*) _value=&quot;$(arg_scrubber_path &quot;${_raw_value}&quot;)&quot; ;; 'posix'*) _value=&quot;$(arg_scrubber_posix &quot;${_raw_value}&quot;)&quot; ;; 'print'*) _value=&quot;${_raw_value//[^[:print:]]/}&quot; ;; 'regex'*) _value=&quot;$(arg_scrubber_regex &quot;${_raw_value}&quot;)&quot; ;; 'list'*) _value=&quot;$(arg_scrubber_list &quot;${_raw_value}&quot;)&quot; ;; 'alpha_numeric'*) _value=&quot;$(arg_scrubber_alpha_numeric &quot;${_raw_value}&quot;)&quot; ;; esac if [[ &quot;${_opt_type}&quot; =~ ^'bool'* ]] || [[ &quot;${_raw_value}&quot; == &quot;${_value}&quot; ]]; then printf '%s' &quot;${_value}&quot; else printf '## Error - return_scrubbed_arg detected differences in values\n' &gt;&amp;2 return 1 fi } argument_parser(){ local -n _arg_user_ref=&quot;${1:?# No reference to an argument list/array provided}&quot; local -n _arg_accept_ref=&quot;${2:-_DEFAULT_ACCEPTABLE_ARG_LIST}&quot; _args_user_list=(&quot;${_arg_user_ref[@]}&quot;) unset _assigned_args for _acceptable_args in ${_arg_accept_ref[@]}; do ## Take a break when user supplied argument list becomes empty [[ &quot;${#_args_user_list[@]}&quot; == '0' ]] &amp;&amp; break ## First in listed acceptable arg is used as variable name to save value to ## example, '--foo-bar fizz' would transmute into '_foo_bar=fizz' _opt_name=&quot;${_acceptable_args%%[:|]*}&quot; _var_name=&quot;${_opt_name#*[-]}&quot; _var_name=&quot;${_var_name#*[-]}&quot; _var_name=&quot;_${_var_name//-/_}&quot; ## Divine the type of argument allowed for this iteration of acceptable args case &quot;${_acceptable_args}&quot; in *':'*) _opt_type=&quot;${_acceptable_args##*[:]}&quot; ;; *) _opt_type=&quot;bool&quot; ;; esac ## Set case expressions to match user arguments against and for non-bool type ## what alternative case expression to match on. ## example '--foo|-f' will also check for '--foo=*|-f=*' _arg_opt_list=&quot;${_acceptable_args%%:*}&quot; _valid_opts_pattern=&quot;@(${_arg_opt_list})&quot; case &quot;${_arg_opt_list}&quot; in *'|'*) _valid_opts_pattern_alt=&quot;@(${_arg_opt_list//|/=*|}=*)&quot; ;; *) _valid_opts_pattern_alt=&quot;@(${_arg_opt_list}=*)&quot; ;; esac ## Attempt to match up user supplied arguments with those that are valid for (( i = 0; i &lt; &quot;${#_args_user_list[@]}&quot;; i++ )); do _user_opt=&quot;${_args_user_list[${i}]}&quot; case &quot;${_user_opt}&quot; in ${_valid_opts_pattern}) ## Parse for script-name --foo bar or --true if [[ &quot;${_opt_type}&quot; =~ ^'bool'* ]]; then _var_value=&quot;$(return_scrubbed_arg &quot;${_user_opt}&quot; &quot;${_opt_type}&quot;)&quot; _exit_status=&quot;${?}&quot; else i+=1 _var_value=&quot;$(return_scrubbed_arg &quot;${_args_user_list[${i}]}&quot; &quot;${_opt_type}&quot;)&quot; _exit_status=&quot;${?}&quot; unset _args_user_list[$(( i - 1 ))] fi ;; ${_valid_opts_pattern_alt}) ## Parse for script-name --foo=bar _var_value=&quot;$(return_scrubbed_arg &quot;${_user_opt#*=}&quot; &quot;${_opt_type}&quot;)&quot; _exit_status=&quot;${?}&quot; ;; *) ## Parse for script-name direct_value case &quot;${_opt_type}&quot; in *'nil'|*'none') _var_value=&quot;$(return_scrubbed_arg &quot;${_user_opt}&quot; &quot;${_opt_type}&quot;)&quot; _exit_status=&quot;${?}&quot; ;; esac ;; esac if ((_exit_status)); then return ${_exit_status}; fi ## Break on matched options after clearing temp variables and re-assigning ## list (array) of user supplied arguments. ## Note, re-assigning is to ensure the next looping indexes correctly ## and is designed to require less work on each iteration if [ -n &quot;${_var_value}&quot; ]; then declare -g &quot;${_var_name}=${_var_value}&quot; declare -ag &quot;_assigned_args+=('${_opt_name}=\&quot;${_var_value}\&quot;')&quot; unset _user_opt unset _var_value unset _args_user_list[${i}] unset _exit_status _args_user_list=(&quot;${_args_user_list[@]}&quot;) break fi done unset _opt_type unset _opt_name unset _var_name done } </code></pre> <blockquote> <p>Note, the source code for <a href="https://github.com/bash-utilities/argument-parser/blob/master/argument-parser.sh" rel="nofollow noreferrer" title="Main source code for argument-parser project">argument-parser.sh</a> is a Git Submodule maintained on GitHub at <a href="https://github.com/bash-utilities/argument-parser" rel="nofollow noreferrer" title="Repository for argument-parser project">`bash-utilities/argument-parser</a>, and can be cloned individually via...</p> </blockquote> <pre><code>mkdir -vp ~/git/hub/bash-utilities cd ~/git/hub/bash-utilities git clone git@github.com:bash-utilities/argument-parser.git </code></pre> <hr /> <h3><a href="https://github.com/bash-utilities/trap-failure/blob/master/failure.sh" rel="nofollow noreferrer" title="Main source code for trap-failure project">shared_functions/modules/trap-failure/failure.sh</a></h3> <pre><code>#!/usr/bin/env bash # Bash Trap Failure, a submodule for other Bash scripts tracked by Git # Copyright (C) 2019 S0AndS0 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation; version 3 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. ## Outputs Front-Mater formatted failures for functions not returning 0 ## Use the following line after sourcing this file to set failure trap ## trap 'failure &quot;LINENO&quot; &quot;BASH_LINENO&quot; &quot;${BASH_COMMAND}&quot; &quot;${?}&quot;' ERR failure(){ local -n _lineno=&quot;${1:-LINENO}&quot; local -n _bash_lineno=&quot;${2:-BASH_LINENO}&quot; local _last_command=&quot;${3:-${BASH_COMMAND}}&quot; local _code=&quot;${4:-0}&quot; ## Workaround for read EOF combo tripping traps ((_code)) || { return &quot;${_code}&quot; } local _last_command_height=&quot;$(wc -l &lt;&lt;&lt;&quot;${_last_command}&quot;)&quot; local -a _output_array=() _output_array+=( '---' &quot;lines_history: [${_lineno} ${_bash_lineno[*]}]&quot; &quot;function_trace: [${FUNCNAME[*]}]&quot; &quot;exit_code: ${_code}&quot; ) [[ &quot;${#BASH_SOURCE[@]}&quot; -gt '1' ]] &amp;&amp; { _output_array+=('source_trace:') for _item in &quot;${BASH_SOURCE[@]}&quot;; do _output_array+=(&quot; - ${_item}&quot;) done } || { _output_array+=(&quot;source_trace: [${BASH_SOURCE[*]}]&quot;) } [[ &quot;${_last_command_height}&quot; -gt '1' ]] &amp;&amp; { _output_array+=( 'last_command: -&gt;' &quot;${_last_command}&quot; ) } || { _output_array+=(&quot;last_command: ${_last_command}&quot;) } _output_array+=('---') printf '%s\n' &quot;${_output_array[@]}&quot; &gt;&amp;2 exit ${_code} } </code></pre> <blockquote> <p>Note, the source code for <a href="https://github.com/bash-utilities/trap-failure/blob/master/failure.sh" rel="nofollow noreferrer" title="Main source code for trap-failure project">failure.sh</a> is a Git Submodule maintained on GitHub at <a href="https://github.com/bash-utilities/trap-failure" rel="nofollow noreferrer" title="Repository for trap-failure project">bash-utilities/trap-failure</a>, and can be cloned individually via...</p> </blockquote> <pre><code>mkdir -vp ~/git/hub/bash-utilities cd ~/git/hub/bash-utilities git clone git@github.com:bash-utilities/trap-failure.git </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T00:48:53.183", "Id": "244765", "Score": "3", "Tags": [ "bash", "linux", "ssh", "x11" ], "Title": "Bash script to mirror XWindow to remote SSH host" }
244765
<p>I am making a fractions calculator that can calculate fractions, whole numbers and mixed fractions.</p> <p>So there is a String fraction, which is the input.</p> <p>Also, the user will enter the fraction in a specified format which is:</p> <ul> <li>For normal fraction, &quot;a/b&quot; (a and b are integers)</li> <li>For whole numbers, &quot;c&quot; (c is an integer)</li> <li>For mixed fraction, &quot;c a/b&quot; (c is integer, a/b is the fraction separated by a space)</li> </ul> <p>I want the program to check and find out which type of fraction the user has entered and then proceed. I'm using If-Else If-Else for this.</p> <pre><code>fun fractionalize(fraction: String): List&lt;Int&gt;{ //Finds type of number (input) and converts to List&lt;Int&gt; with [numerator, denominator, whole number] var result: List&lt;Int&gt; = listOf(0,1,0) var numerator: Int = 0 var denominator:Int = 1 var whole_number:Int = 0 try { if ((fraction.contains('/') &amp;&amp; fraction.indexOf('/') == fraction.lastIndexOf('/')) &amp;&amp; !fraction.contains(&quot; &quot;)) { //input is a regular fraction var fraction_string = fraction.split(&quot;/&quot;) numerator = fraction_string[0].toInt() denominator = fraction_string[1].toInt() result = listOf(numerator, denominator, 0) } else if (fraction.isDigitsOnly()) { //input is a whole number result = listOf(fraction.toInt(), 1, 0) } else if ((fraction.contains('/') &amp;&amp; fraction.indexOf('/') == fraction.lastIndexOf('/')) &amp;&amp; (fraction.contains(&quot; &quot;) &amp;&amp; fraction.indexOf(' ') == fraction.lastIndexOf(' '))) { //input is mixed fraction var wholeNumber_split = fraction.split(&quot; &quot;) whole_number = wholeNumber_split[0].toInt() numerator = wholeNumber_split[1].split(&quot;/&quot;)[0].toInt() numerator += whole_number * denominator denominator = wholeNumber_split[1].split(&quot;/&quot;)[1].toInt() result = listOf(numerator, denominator, 0) } else { Toast.makeText(applicationContext, &quot;The number you entered is not in a valid format.&quot;, Toast.LENGTH_LONG).show() } //simplifying input if (result[2] != 0){ numerator += whole_number * denominator result = listOf(numerator, denominator, 0) } return result } catch (e: Exception){ Toast.makeText(applicationContext, &quot;The number you entered is not in a valid format.&quot;, Toast.LENGTH_LONG).show() return result } } </code></pre> <p>Is this the best way I can do that or is there cleaner and more efficient code I can make (personally I think this is too messy and can be made more efficient)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T04:47:03.663", "Id": "480551", "Score": "2", "body": "A regular expression is the first thing that comes to my mind when I have to check if input matches a certain pattern. It would allow you to check full validity of the input, not just if it contains a '/' character. E.g. 'a/3' would be rejected immediately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T04:57:55.563", "Id": "480553", "Score": "0", "body": "@TorbenPutkonen So what should I keep as parameters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T06:53:33.083", "Id": "480563", "Score": "4", "body": "Please adjust the title of your \"question\" to confirm to [this site's standards](/help/how-to-ask)." } ]
[ { "body": "<p>Your code has several areas where it can be improved.</p>\n<p>The first is that you should separate the parsing code from the platform code (<code>Toast</code>). Kotlin has a great testing framework, in which it is easy to write &quot;parsing <code>&quot;1 2/3&quot;</code> should return <code>listOf(1, 2, 3)</code>&quot;. This testing code works best if you run it directly on your developing machine, and without any <code>Toast</code> or <code>Activity</code>.</p>\n<p>The next thing is that you should not use <code>List&lt;Int&gt;</code> in places where you originally wanted to say <code>Fraction</code> or maybe, to be more specific, <code>MixedFraction</code>. The point is that <code>listOf(1, 2, 3, 4, 5)</code> is a valid list but not a valid fraction. By using a specifically constrained type you force the Kotlin compiler to check your code for you.</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>class Fraction(\n val int: Int,\n val num: Int,\n val den: Int\n)\n</code></pre>\n<p>To make your parser extensible to expressions that are more complicated, you must not use <code>contains</code>. Instead, the best-practice way is to split the input into tokens first (often using regular expressions) and then to combine these tokens to expression trees (using <a href=\"https://en.m.wikipedia.org/wiki/Canonical_LR_parser\" rel=\"nofollow noreferrer\">a parser that only looks at the very next token to decide what to do next</a>). The details of all of this are covered in any good book on compiler construction.</p>\n<p>In your case, the tokens would be:</p>\n<ul>\n<li>unsigned integer</li>\n<li>fraction slash</li>\n<li>unary minus sign</li>\n</ul>\n<p>Note that there is no &quot;space&quot; token, as that is usually left out when defining an expression language.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T05:46:12.547", "Id": "480555", "Score": "0", "body": "I am fairly new to android development, so I don't understand a lot of things you told me.....Making a Fraction class is a great idea. I don't get making the parser thing. Please help me. Also, I'll edit the code to include the whole function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T06:19:53.337", "Id": "480557", "Score": "1", "body": "Just google for \"kotlin testing\", and you should find a tutorial for that topic. Invest some time in this topic since testing is a fundamental requirement to writing reliable and robust code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T06:23:13.317", "Id": "480559", "Score": "4", "body": "Please, don't answer incomplete questions. Now there are 2 options: either you remove the remark about the code being incomplete or we rollback the added code. I'll leave it up to you which is preferred. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T06:31:11.113", "Id": "480560", "Score": "0", "body": "@Mast I think removing the remark would be better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T06:33:36.990", "Id": "480561", "Score": "2", "body": "@DeathVenom Next time, please make sure the first revision of your question is complete. We don't deal well with snippets, as indicated in the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T15:43:18.707", "Id": "480605", "Score": "0", "body": "Hey can you please explain 'splitting the input into tokens' or point me to a resource/tutorial? I don't get that part." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T05:31:41.947", "Id": "244769", "ParentId": "244767", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T03:33:57.450", "Id": "244767", "Score": "3", "Tags": [ "beginner", "android", "kotlin" ], "Title": "Finding the type of number entered by the user" }
244767
<p>I implemented the <a href="https://en.wikipedia.org/wiki/Hex_(board_game)" rel="nofollow noreferrer">boardgame Hex</a> using the OpenAI gym framework with the aim of building a bot/AI player that can learn through self-play and expert iteration (<a href="https://arxiv.org/abs/1705.08439" rel="nofollow noreferrer">details</a> Note: not my paper; I am merely reproducing it).</p> <p>The initial agent uses Monte-Carlo tree search (MCTS), and I will compare myself against it to evaluate the strength of different bots. MCTS involves simulating the game with random moves (called a rollout) and this is done A LOT (&gt;1,000 games played per move in the actual game), so this rollout speed matters to me. Indeed, when I profile my code, the bottleneck is said rollout, and, more specifically, the test if the game has ended.</p> <p>Currently, I check if the game is finished using the following mechanism (I'm sure there is a name for it, but I don't know it):</p> <ol> <li>Pad the board with 1 extra row/column and place stones on the west/east side (player white/blue) or north/south side (player black/red) (cached at the start of the game)</li> <li>Find all the connected regions for the current player (cached from previous turn)</li> <li>Place stone on board</li> <li>check neighborhood of stone and (a) start new region if unconnected, (b) add to the region with lowest region index</li> <li>if multiple regions are in the neighborhood, merge them with the region that has the lowest index</li> </ol> <p>I assign index 1 to the stones in the north/west (black/white) padding, and can then efficiently test if the game is over by checking the south-east corner. If it has region index 1, it is connected to the opposite side and the game has finished.</p> <p>The full code of the game is available on <a href="https://github.com/FirefoxMetzger/minihex" rel="nofollow noreferrer">GitHub</a> together with a MWE that performs a random rollout. It's not a big repo (maybe 500 lines). The critical function is this one</p> <pre class="lang-py prettyprint-override"><code> def flood_fill(self, position): regions = self.regions[self.active_player] current_position = (position[0] + 1, position[1] + 1) low_x = current_position[1] - 1 high_x = current_position[1] + 2 low_y = current_position[0] - 1 high_y = current_position[0] + 2 neighbourhood = regions[low_y:high_y, low_x:high_x].copy() neighbourhood[0, 0] = 0 neighbourhood[2, 2] = 0 adjacent_regions = sorted(set(neighbourhood.flatten().tolist())) adjacent_regions.pop(0) if len(adjacent_regions) == 0: regions[tuple(current_position)] = self.region_counter[self.active_player] self.region_counter[self.active_player] += 1 else: new_region_label = adjacent_regions.pop(0) regions[tuple(current_position)] = new_region_label for label in adjacent_regions: regions[regions == label] = new_region_label </code></pre> <p>with the most expensive line being <code>adjacent_regions = sorted(set(neighbourhood.flatten().tolist()))</code>. I'm wondering if this can be implemented in a nicer way, either by using a different algorithm or vectorizing the code more, more intelligent caching, ...</p> <p>Of course, I'm also happy with any other comment on the code.</p> <p>Disclaimer: I found a basic hex implementation in an old commit in the OpenAI gym repo, which I used as a base to work off. Most of the code has changed, but some of it (e.g., the render function) I did not write myself.</p>
[]
[ { "body": "<p>When reading this function alone, without any surrounding code, I wonder where the initial <code>+ 1</code> for the <code>position</code> comes from. That looks like an off-by-one bug to me. I don't know whether it is indeed a bug, it's just suspicious.</p>\n<p>The calls to <code>tuple()</code> look redundant since the <code>current_position</code> already is a tuple. Doesn't your IDE warn about such things?</p>\n<p>The word <code>position</code> is a bad name since it is ambiguous. It could either mean an <code>(x, y)</code> tuple or the complete <code>(board, player_to_move)</code> tuple, like in the sentence &quot;in this position, Red should resign&quot;. A better name would be <code>last_move</code> or <code>prev_move</code>.</p>\n<p>Is there a good reason why you use a tuple at all? Having two variables <code>x</code> and <code>y</code> would make the code pretty clear. These variable names are short enough that you don't need the <code>low_x</code> and related variables anymore.</p>\n<p>Do you need the call to <code>tolist()</code> at all?</p>\n<p>Instead of generating a 2-dimensional matrix, it could be more efficient if you just took the 6 neighbor regions explicitly and individually. That way you also get rid of the <code>pop(0)</code>. I don't know whether that is faster in Python though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T09:27:26.427", "Id": "480575", "Score": "1", "body": "Thank you for the answer! The additional +1 comes from a \"coordinate transformation\". I am adding a padding of 1 around the board to make checks easier, so I need to account for that by offseting the position (which is given in actual board coordinates, not padded coordinates)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T09:30:36.447", "Id": "480576", "Score": "0", "body": "Interestingly, in my profiling, the `tolist()` call caused a significant (about 10 games/s on 11x11) speed up, so I left it there. I totally agree that it seems redundant. Thank you for the other suggestions, too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T08:57:21.657", "Id": "244772", "ParentId": "244771", "Score": "2" } }, { "body": "<p>Without the profile numbers you have, I can't suggest changes that make assumptions about the input to the function. For instance, if you knew that most times the 'check if the game is over' fails, you could only run the check once the player has a piece in every row and a piece in every column. I will also be picking off small things, as I don't know what specific parts of the function are too slow. The changes below are a little agnostic to your code in a sense, and might not help all that much.</p>\n<hr />\n<p>As a personal preference, I don't like code that makes liberal use of indexing. I find it is often harder to read than it needs to be.</p>\n<pre><code>current_position = (position[0] + 1, position[1] + 1)\nlow_x = current_position[1] - 1\nhigh_x = current_position[1] + 2\nlow_y = current_position[0] - 1\nhigh_y = current_position[0] + 2\n</code></pre>\n<p>There is a little bit of unnecessary adding and subtracting here. You can simplify it a little.</p>\n<pre><code>low_x = current_position[1] - 1\nlow_x = position[1] + 1 - 1 # Replace current_position[1] with its definition: position[1] + 1\nlow_x = position[1]\n</code></pre>\n<p>and the same holds for the other variables here</p>\n<pre><code>current_position = (position[0] + 1, position[1] + 1)\nlow_x = position[1]\nhigh_x = position[1] + 3\nlow_y = position[0]\nhigh_y = position[0] + 3\n</code></pre>\n<p>Since position is indexed into a few times, it makes sense to unpack it. I would also remove low_x and low_y since they already have (sensible) names; x and y.</p>\n<pre><code>x, y = position\ncurrent_position = x + 1, y + 1\nlow_x = x\nhigh_x = x + 3\nlow_y = y\nhigh_y = y + 3\nneighbourhood = regions[low_y:high_y, low_x:high_x].copy()\n</code></pre>\n<p>Then there is no point in keeping the variables low_x, low_y, high_x, or high_y. They don't add any clarity and are not used anywhere else.</p>\n<pre><code>x, y = position\ncurrent_position = x + 1, y + 1\nneighbourhood = regions[y:y+3, x:x+3].copy()\n</code></pre>\n<p>This code now has magic constants x+3 and y+3. I don't know where they come from, a comment explaining it would be nice.</p>\n<hr />\n<pre><code>adjacent_regions = sorted(...)\nadjacent_regions.pop(0)\n\nif len(adjacent_regions) == 0:\n ...\n ...\nelse:\n new_region_label = adjacent_regions.pop(0)\n regions[tuple(current_position)] = new_region_label\n for label in adjacent_regions:\n regions[regions == label] = new_region_label\n</code></pre>\n<p>I've removed anything that doesn't pertain to adjacent_regions. From this I noticed two things.</p>\n<p>The list structure is popped from the front once or twice. Usually lists have O(n) complexity when popped from the front, <a href=\"https://wiki.python.org/moin/TimeComplexity#list\" rel=\"nofollow noreferrer\">as it needs to make changes to everything in the list</a>. Even though it might not be a long list, it is still a complexity smell that we should try to avoid.</p>\n<p>A quick fix would be to sort the list in reverse, and pop from the end rather than the start. In this case, as I don't seen adjacent_region exposed outside of the function, we can avoid modifying the list instead. Not popping from the front, and accounting for the extra element, the code might look something like this:</p>\n<pre><code>adjacent_regions = sorted(...)\n# adjacent_regions.pop(0) # REMOVED\n\nif len(adjacent_regions) == 1: # Empty other than the '0' label\n ...\n ...\nelse:\n # Ignoring the first element, this becomes .pop(1)\n # Then changed .pop to a simple __getitem__\n new_region_label = adjacent_regions[1]\n regions[tuple(current_position)] = new_region_label\n for label in adjacent_regions:\n regions[regions == label] = new_region_label\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T03:44:54.807", "Id": "480640", "Score": "0", "body": "Thank you for the review! I agree with the (y,x) comments and have addressed it since; you do have a twist in the tuple decomp though, as it should be `y,x=position`. List complexity is a good point; I thought `O(k)` for `pop` and `k=1` means `O(1)` since it should just be finding the 2nd element and shifting a pointer ... I will try. I noticed that your suggestion assigns `new_region_label` to the 0-region as well, which is undesirable. I don't see a way around slicing or pop-ing; I will do some tests." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T18:38:06.480", "Id": "244807", "ParentId": "244771", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T07:49:15.210", "Id": "244771", "Score": "3", "Tags": [ "python", "game", "simulation" ], "Title": "Hex boardgame with fast random rollouts (OpenAI gym framework)" }
244771
<p>I'm learning to use HSpec and QuickCheck. As example I was implementing the Pseudocode from <a href="https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Pseudocode" rel="nofollow noreferrer">Wikipedia:Extended Euclidean Algorithm</a>. You can find the project at <a href="https://github.com/bdcaf/Euklid-haskell" rel="nofollow noreferrer">github</a> for the implementation of the tested code.</p> <p>In particular I wonder about two practices:</p> <ul> <li>selection of test cases - I took two trivial samples, examples from the wikipedia page and took three property tests.</li> <li>Generation of cases - the <code>a&gt;0 &amp;&amp; b&gt;0</code> seems inefficient to me.</li> </ul> <p>I'm most interested what would be a good practice to confirm two algorithms produce the same results.</p> <pre><code>module EuclidSpec ( spec ) where import Test.Hspec import Test.Hspec.Core.QuickCheck import Test.QuickCheck import Lib spec :: Spec spec = do describe &quot;Trivial&quot; $ do it &quot;trivial example 99 1&quot; $ let trivial = extendedEuclid 99 1 in trivial `shouldBe` (EuclidRes 1 (0) 1) it &quot;trivial example 99 99&quot; $ let trivial = extendedEuclid 99 99 in trivial `shouldBe` (EuclidRes 99 (0) 1) describe &quot;Examples&quot; $ do it &quot;explanation example 99 78&quot; $ let wikiExample = extendedEuclid 99 78 in wikiExample `shouldBe` (EuclidRes 3 (-11) 14) it &quot;explanation example flipped 78 99&quot; $ let wikiExample = extendedEuclid 78 99 in wikiExample `shouldBe` (EuclidRes 3 14 (-11) ) it &quot;explanation example 99 78&quot; $ let wikiExample = extendedEuclid 240 46 in wikiExample `shouldBe` (EuclidRes 2 (-9) 47) describe &quot;properties&quot; $ do it &quot;both numbers divisible a%gcd == 0, b%gcd ==0&quot; $ property $ prop_divisible it &quot;bezout a*s+b*t = gcd&quot; $ property $ prop_bezout it &quot;recursive and iterative algorithm have same result&quot; $ property $ prop_same_as_recursive prop_divisible a b = a&gt;0 &amp;&amp; b&gt;0 ==&gt; a `mod` d ==0 &amp;&amp; b `mod`d == 0 where EuclidRes d s t = extendedEuclid a b prop_bezout a b = a&gt;0 &amp;&amp; b&gt;0 ==&gt; a*s + b*t == d where EuclidRes d s t = extendedEuclid a b prop_same_as_recursive a b = a&gt;0 &amp;&amp; b&gt;0 ==&gt; extendedEuclid a b == extendedEuclid' a b </code></pre>
[]
[ { "body": "<p>Ah, a fine <code>Spec</code>. Has been a while since I've used <code>Hspec</code>, but your tests seem reasonable. So, first of all: <strong>well done!</strong></p>\n<p>There is one bit we should fix though, and you have identified it yourself: the property tests.</p>\n<h1>QuickCheck's newtypes</h1>\n<p>Creating any kind of number and then checking whether it's positive is a hassle, as half the numbers will get discarded per candidate. However, since <code>Hspec</code> uses <code>QuickCheck</code>, we can use <a href=\"https://hackage.haskell.org/package/QuickCheck-2.13.1/docs/Test-QuickCheck.html#t:Positive\" rel=\"nofollow noreferrer\"><code>Positive</code></a> to only generate positive numbers:</p>\n<pre><code>prop_divisible (Positive a) (Positive b) = a `mod` d == 0 &amp;&amp; b `mod`d == 0\n where EuclidRes d s t = extendedEuclid a b\n</code></pre>\n<p>Other than that there are no more objective improvements.</p>\n<p>However, there are some personal I would use in my own specs.</p>\n<h1>Reduce <code>let … in …</code> bindings in specs</h1>\n<p>Consider the following spec</p>\n<pre><code> describe &quot;Trivial&quot; $ do\n it &quot;trivial example 99 1&quot; $\n let trivial = extendedEuclid 99 1 \n in trivial `shouldBe` (EuclidRes 1 (0) 1)\n</code></pre>\n<p>If I want to understand the spec, I have to read the first line, remember the value of <code>trivial</code> (and that it hasn't been changed after calling <code>extendedEuclid</code>), and supply it in the next one.</p>\n<p>If I instead write</p>\n<pre><code> describe &quot;Trivial&quot; $ do\n it &quot;trivial example 99 1&quot; $\n extendedEuclid 99 1 `shouldBe` (EuclidRes 1 (0) 1)\n-- or\n it &quot;trivial example 99 99&quot; $\n extendedEuclid 99 99 \n `shouldBe` (EuclidRes 99 (0) 1)\n</code></pre>\n<p>I immediately see that <code>extendedEucild</code> is getting tested. This also <a href=\"https://hspec.github.io/\" rel=\"nofollow noreferrer\">fits the official style</a>, where <code>let … in …</code> bindings <a href=\"https://hspec.github.io/writing-specs.html\" rel=\"nofollow noreferrer\">aren't used at all</a>.</p>\n<h1>Other small pieces</h1>\n<p>You can use <code>prop</code> from <code>Test.Hspec.QuickCheck</code> instead of <code>it &quot;...&quot; $ property $ ...</code>:</p>\n<pre><code>import Test.Hspec.QuickCheck\n\n...\n\n describe &quot;properties&quot; $ do\n prop &quot;both numbers divisible a%gcd == 0, b%gcd ==0&quot; $ \n prop_divisible\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T12:15:43.017", "Id": "244783", "ParentId": "244774", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T10:11:13.643", "Id": "244774", "Score": "3", "Tags": [ "haskell", "unit-testing" ], "Title": "Haskell Hspec/Quickcheck test for numeric function" }
244774
<p>I wrote the following Forth code for sorting a string with the Bubble Sort method.</p> <p>It looks nice to my eyes, but I'd like your experienced opinion and any comments about the code you might have.</p> <ol> <li>In the <code>compare-and-swap-next</code> word, is using the return stack to save base address of string ok?</li> <li>the <code>bubblesort</code> word uses <code>2 pick</code> which is not so bad? A previous version had <code>5 pick</code> (!), anyway ... is <code>2 pick</code> <em>fine: don't overthink about that</em> or maybe try some more refactoring?</li> <li>How would I go about adding a check for any swaps in each round and terminate the sort early? A variable? A stack cell (on TOS)? Rethink all of the implementation?</li> </ol> <pre><code>: compare-and-swap-next ( string i -- ) 2dup + dup &gt;r c@ rot rot 1 + + c@ 2dup &gt; if r@ c! r&gt; 1 + c! else r&gt; drop 2drop then ; : bubblesort ( string len -- string len ) dup 1 - begin dup 0&gt; while dup 0 do 2 pick i compare-and-swap-next loop 1 - repeat drop ; \ s&quot; abracadabra&quot; bubblesort \ cr type \ s&quot; The quick brown fox&quot; bubblesort \ cr type \ s&quot; a quick brown fox jumps over the lazy dog.&quot; bubblesort \ cr type </code></pre> <p>Code available <a href="https://github.com/pm62eg/LearningForth/blob/900c773f8303a939b5172f0b35e9ba1a6cb08c37/sorts.fs" rel="nofollow noreferrer">on github</a></p> <p>Nitpicks welcome! Pedantism welcome!<br /> Thank you!</p>
[]
[ { "body": "<p>To address your immediate concerns,</p>\n<ol>\n<li><p>Using the return stack for storing your temporaries is a perfectly valid technique.</p>\n</li>\n<li><p><code>pick</code> is always frown upon (as well as <code>tuck</code>, <code>roll</code>, and friends). It <em>seems</em> that the <code>len</code> parameter to <code>bubblesort</code> does not participate in computation - except the very beginning - and mostly just stays in the way. Consider</p>\n<pre><code> : bubblesort\n dup &gt;r 1-\n ....\n</code></pre>\n</li>\n</ol>\n<p>and use <code>over</code> instead of <code>2 pick</code> (don't forget to <code>r&gt;</code> the length at the end).</p>\n<hr />\n<p>I prefer a slightly different formatting of conditional. Consider</p>\n<pre><code>2dup &gt; if \n r@ c! r&gt; 1 + c! else \n r&gt; drop 2drop then ;\n</code></pre>\n<p>Same for the loops. Consider</p>\n<pre><code>: bubblesort ( string len -- string len )\n dup 1 - begin \n dup 0&gt; while\n dup 0 do \n 2 pick i compare-and-swap-next \n loop\n 1 - \n repeat\ndrop ;\n</code></pre>\n<p>Keeping control words together with their respective conditions/actions looks more Forthy for me.</p>\n<hr />\n<p><code>r&gt; drop</code> is also known as <code>rdrop</code>.</p>\n<p><code>rot rot</code> is also known as <code>-rot</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T18:25:41.903", "Id": "244805", "ParentId": "244775", "Score": "2" } } ]
{ "AcceptedAnswerId": "244805", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T10:12:59.397", "Id": "244775", "Score": "4", "Tags": [ "beginner", "algorithm", "sorting", "forth" ], "Title": "Bubble Sort in Forth (for strings)" }
244775
<h3>Problem</h3> <p>When it comes to security I like to don a tin foil hat. As such I use the, off-line password manager, Keepass. Keepass allows you to to use multi-factor authentication via; a password, a keyfile and the Windows user account. I enabled only two of these, the password and the keyfile. Because I have two computers that need access to the keyfile I've stored it on a USB stick.</p> <p>On Windows everything is fine, I plug the USB in, I open the database, I eject the USB from the tray, remove USB and I can use the passwords I need. This in all takes two seconds.</p> <h3>Solution</h3> <p>However on Linux this feels like a whole song and dance. Consisting of something similar to the following:</p> <blockquote> <pre class="lang-bsh prettyprint-override"><code># Plug in USB lsblk sudo mount /dev/usb1 /path/to/folder keypass &amp; sudo umount /dev/usb1 udisksctl power-off -b /dev/usb lsblk # Remove USB </code></pre> </blockquote> <p>Whilst this in theory isn't much different than Windows, it's <em>just</em> an added mount and unmount. Having to check <code>lsblk</code> and type all of that just to get a password is inconvenient. And so I decided to script this away, it's just ~6 commands, how hard can it be?</p> <h3>Fishy Solution</h3> <p>I'm a beginner with <a href="https://fishshell.com/" rel="noreferrer">fish</a>, I've not used functions or lists before. And the only time I've set something was to update my path. I'm such a noob that I tried to <code>return (&quot;&quot; &quot;&quot;)</code> to return a list... However I have some experience in other, non-shell, languages and feel I've picked it up ok.</p> <ul> <li><p><code>pdev</code> - finds a partition's UUID, pkname, block path and mountpoint all from the UUID. If a device with a matching UUID is not found then it will continuously inform the user and attempt to reacquire the data.</p> </li> <li><p><code>pmount</code> - This takes four positional arguments for the partition; UUID, target mountpoint, block path, current mountpoint.</p> <ul> <li>If the partition has a current mountpoint it will fail if this is not the target mountpoint.</li> <li>Otherwise, if the block path is a value then it will mount the partition to the target path.</li> <li>Finally if neither of these are true it does nothing.</li> </ul> </li> <li><p><code>umount_all</code> - This is given a pkname and unmounts all partitions of the drive. Whilst it's unlikely that that the drive will have multiple partitions, and it's even more unlikely that they'll be mounted. I would prefer to err on the side of caution.</p> </li> <li><p><code>load_passwords</code> - This is effectively the 'main' function. It takes a UUID and a target path. From here it:</p> <ol> <li>Get the mount information from <code>pdev</code>.</li> <li>Get the drive's path. (This would be <code>/dev/usb</code> rather than <code>/dev/usb1</code>) This uses <code>lsblk</code> as simply cutting off the last number wouldn't work on some storage devices. (I.e. nvme0n1p1)</li> <li>Display the partition's information, the block path, highlighting the drive's path, and the current mountpoint.</li> <li>Attempt to mount the drive using <code>pmount</code>.</li> <li>Open keypass.</li> <li>Ask the user if they wish to eject the drive.</li> <li>Exit successfully if the user <em>does not</em> wish to eject the drive.</li> <li>Unmount all the partitions on the drive with <code>umount_all</code>.</li> <li>Power off the drive.</li> <li>Verify the device has been powered off successfully.</li> </ol> </li> <li><p><code>passwords</code> - A convenience function to pass the UUID and mountpoint that I use.</p> </li> </ul> <pre class="lang-fish prettyprint-override"><code>function pdev while true set mounts (lsblk -l -o UUID,PKNAME,PATH,MOUNTPOINT | grep &quot;^$argv[1] &quot; | grep -Po &quot;[^ ]+&quot;) if set -q mounts[1] break end read -P &quot;Insert key drive &quot; end for mount in $mounts echo $mount end end function pmount if set -q argv[4] if test $argv[4] != $argv[2] echo &quot;Mounted to wrong directory&quot; return 1 end else if set -q argv[3] sudo mount UUID=$argv[1] $argv[2] end end function umount_all set blocks (lsblk -l -o PKNAME,PATH,MOUNTPOINT | grep &quot;^$argv[1] &quot;) for block_ in $blocks set block (echo &quot;$block_&quot; | grep -Po &quot;/[^ ]+&quot;) if set -q block[2] sudo umount &quot;$block[1]&quot; end end end function load_passwords set mounts (pdev $argv[1]) if test $status != 0 return 1 end set drive (lsblk -o NAME,PATH | grep &quot;^$mounts[2] &quot; | grep -Po &quot;/[^ ]+&quot;) echo &quot;PATH : $mounts[3]&quot; | grep &quot;$drive&quot; echo &quot;MOUNT: $mounts[4]&quot; pmount $argv[1] $argv[2] $mounts[3] $mounts[4] if test $status != 0 return 1 end keepass &amp; read -P &quot;Eject drive? [Y/n] &quot; -l input echo &quot;$input&quot; | grep -Poi &quot;(^<span class="math-container">\$)|(^y)" &gt;&gt; /dev/null if test $status = 1 return end umount_all "$mounts[2]" udisksctl power-off -b $drive lsblk -o UUID | grep "^$argv[1]\$</span>&quot; &gt;&gt; /dev/null if test $status = 1 return end echo &quot;Failed to power off drive&quot; return 1 end function passwords load_passwords {redacted} /path/to/mountpoint end </code></pre> <h3>Concerns</h3> <ul> <li><p>If not a fan of using a for loop to echo each value in a list to 'return' a list. Is there a cleaner way to do this?</p> <blockquote> <pre class="lang-fish prettyprint-override"><code>for mount in $mounts echo $mount end </code></pre> </blockquote> </li> <li><p>I'm not a fan of names like <code>$argv[1]</code> rather than <code>$uuid</code> as they make the code harder to understand. Is there a clean way to specify these?</p> </li> <li><p>The code feels unreadable, it's why I've written such a thorough description here. I can see myself forgetting all this nuance and coming back to this in a year and go, which idiot wrote this?! </p> </li> <li><p>I'm not a fan of having all the functions be public, <code>pmount</code> should probably be private.</p> </li> <li><p>I'm not a fan of needing <code>sudo</code> when I have access to <code>/path/to/mountpoint</code>. There's a certain irony to needing to enter two passwords to get one...</p> </li> <li><p>I feel the code is just kinda messy and not great.</p> </li> </ul> <p>I am also happy for any other comments on my code.</p>
[]
[ { "body": "<blockquote>\n<p>If not a fan of using a for loop to echo each value in a list to 'return' a list. Is there a cleaner way to do this?</p>\n</blockquote>\n<p>The <code>printf</code> command will reuse the format string to consume all the input:</p>\n<pre><code>printf &quot;%s\\n&quot; $mounts\n</code></pre>\n<blockquote>\n<p>I'm not a fan of names like $argv[1] rather than $uuid as they make the code harder to understand. Is there a clean way to specify these?</p>\n</blockquote>\n<p>Use the <a href=\"https://fishshell.com/docs/current/cmds/function.html\" rel=\"nofollow noreferrer\"><code>-a</code> option to <code>function</code></a></p>\n<pre><code>function load_passwords -a uuid -a mountpath\n set mounts (pdev $uuid)\n ...\n</code></pre>\n<blockquote>\n<p>The code feels unreadable, it's why I've written such a thorough description here. I can see myself forgetting all this nuance and coming back to this in a year and go, which idiot wrote this?! </p>\n</blockquote>\n<p>Sorry, can't help with that. Looks reasonable to me. If you're worried about\nforgetting the nuance, add some comments including the URL for this\nquestion.</p>\n<blockquote>\n<p>I'm not a fan of having all the functions be public, pmount should probably be private.</p>\n</blockquote>\n<p>Why? There's no sensitive info in it.</p>\n<p>The only way you can achieve privacy is to chmod the source files so no\nother user can read them.</p>\n<blockquote>\n<p>I'm not a fan of needing sudo when I have access to /path/to/mountpoint. There's a certain irony to needing to enter two passwords to get one...</p>\n</blockquote>\n<p>Assuming you have the permission to do so, you could visudo so that your\nuser does not need to enter a password for <code>sudo mount</code> and <code>sudo umount</code></p>\n<blockquote>\n<p>I feel the code is just kinda messy and not great.</p>\n</blockquote>\n<p>That's pretty much the nature of the beast with shell scripting. At least\nfish has cleaner (if perhaps more verbose) syntax than bash.</p>\n<hr />\n<p>I'm a Lastpass user, and have made similar efforts to access passwords via the lpass command line tool.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T15:16:08.427", "Id": "480603", "Score": "0", "body": "Thank you, this is really helpful. `-a` has helped clean up a lot of the confusion, and I can probably use `-d` to add a description to make the rest of it more readable. It seems there's no tuple unpacking equivalent, so I have to deal with some `\"$mounts[2]\"` noise, but it's so much better. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T13:50:38.267", "Id": "244786", "ParentId": "244777", "Score": "3" } } ]
{ "AcceptedAnswerId": "244786", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T11:05:33.840", "Id": "244777", "Score": "5", "Tags": [ "console", "file-system", "linux", "shell", "fish-shell" ], "Title": "Fishy password management" }
244777
<p>See <a href="https://fishshell.com/" rel="nofollow noreferrer">https://fishshell.com/</a> for additional information</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T11:24:03.090", "Id": "244778", "Score": "0", "Tags": null, "Title": null }
244778
fish is a smart and user-friendly command line shell for Unix, Linux, macOS, and other Unix/Linux based operating systems.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T11:24:03.090", "Id": "244779", "Score": "0", "Tags": null, "Title": null }
244779
<p>Is there any approaches to reduce the below coding snippet in Angular 2+ with few lines of code by making use of ECMA Script or by some other ways</p> <pre><code>this.testCenterAccomodations.forEach((x: { utilityCode: string; isChecked: boolean; isSelected: boolean; }) =&gt; { if (x.utilityCode === 'PSDQRA') { if (this.voiceOverLanguageChecked) { x.isChecked = true; x.isSelected = true; } else { x.isChecked = false; x.isSelected = false; } } }); </code></pre> <p>Looping an Array of objects, we are trying to find the object with the column named <code>utilityCode</code> having <code>PSDQRA</code> value and setting those particular object's properties of <code>isChecked</code> &amp; <code>isSelected</code> to be true iff, <code>this.voiceOverLanguageChecked</code> boolean value is true, otherwise set those properties to false.</p> <p>The above snippets is simpler enough to read &amp; understand. But is it possible for someone to achieve the same piece of logic with few lines of code by making use of map, filter, reduce, lambda and rest..</p>
[]
[ { "body": "<p>Hmm i would in a first refactoring change it to this:</p>\n<pre><code>this.testCenterAccomodations.forEach((x: { utilityCode: string; isChecked: boolean; isSelected: boolean; }) =&gt; {\n if (x.utilityCode != 'PSDQRA') {\n return;\n };\n x.isChecked = this.voiceOverLanguageChecked;\n x.isSelected = this.voiceOverLanguageChecked;\n});\n</code></pre>\n<p>The next changes do not have the goal of &quot;shortening&quot; the code. But to make it more readable and easier to change. I would love to hear your feedback about my thoughts.</p>\n<p>I would create a small (perhaps local) interface, because <code>{ utilityCode: string; isChecked: boolean; isSelected: boolean; }</code> seems to be a recurring thing.</p>\n<pre><code>interface UtilityCodeSelection { \n utilityCode: string;\n isChecked: boolean; \n isSelected: boolean; \n}\n</code></pre>\n<p>Which will result in</p>\n<pre><code>this.testCenterAccomodations.forEach((x: UtilityCodeSelection ) =&gt; {\n if (x.utilityCode != 'PSDQRA') {\n return;\n };\n x.isChecked = this.voiceOverLanguageChecked;\n x.isSelected = this.voiceOverLanguageChecked;\n});\n</code></pre>\n<p>Then i would replace the magic variable &quot;PSDQRA&quot; by a constant (or by an enum if you have multiple utility codes we are coding against). Then we could use that constant at all necessary places and would be able to change it centraly. ALSO we can easily find out where our code is refering to this specific value.</p>\n<pre><code>interface UtilityCodeSelection { \n utilityCode: string;\n isChecked: boolean; \n isSelected: boolean; \n}\n\nexport enum UtilityCodes {\n PSDQRA = 'PSDQRA', // Or if PSDQRA has in reality a better name, use that for the enum\n ...\n}\n\nthis.testCenterAccomodations.forEach((x: UtilityCodeSelection ) =&gt; {\n if (x.utilityCode != UtilityCodes.PSDQRA) {\n return;\n };\n x.isChecked = this.voiceOverLanguageChecked;\n x.isSelected = this.voiceOverLanguageChecked;\n});\n</code></pre>\n<p>And in some cases i would even extract some parts into its own method</p>\n<pre><code>this.testCenterAccomodations.forEach((x: UtilityCodeSelection ) =&gt; this.setUtilityCodeSelection(x, UtilityCode.PSDQRA, this.voiceOverLanguageChecked));\n\n private setUtilityCodeSelection(code: UtilityCodeSelection, forCode: UtilityCode, setTo: boolean):void{\n if (code.utilityCode != forCode) {\n return;\n };\n code.isChecked = setTo;\n code.isSelected = setTo;\n}\n</code></pre>\n<p>This has some drawbacks. I personaly do not like implict changes (here we change the given <code>code</code>) and prefere to change explicitly (make a copy, change the copy and return the copy). Also the extra method is only useful if there are more similar checks. In general its a bad idea to try to generalize things, if there is (at least now) no need for it.</p>\n<p>Therefor the chance is high that in your example, i would not move the code in its own method..</p>\n<p>As always... Ask 3 developers about coding style and you will get 4 answers. :-)\nAnd they all will be right in some way.</p>\n<p>warm regards</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-14T12:47:26.870", "Id": "245472", "ParentId": "244780", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T11:50:59.043", "Id": "244780", "Score": "3", "Tags": [ "object-oriented", "array", "ecmascript-6", "angular-2+" ], "Title": "Iterating an Array Object & Assigning the Attributes Values to those that Match the Condition" }
244780
<p>I have written the following code to practice parallelizing a PyTorch code on GPUs:</p> <pre><code>import math import torch import pickle import time import numpy as np import torch.optim as optim from torch import nn print('device_count()', torch.cuda.device_count()) for i in range(torch.cuda.device_count()): print('get_device_name', torch.cuda.get_device_name(i)) def _data(dimension, num_examples): num_mislabeled_examples = 20 ground_truth_weights = np.random.normal(size=dimension) / math.sqrt(dimension) ground_truth_threshold = 0 features = np.random.normal(size=(num_examples, dimension)).astype( np.float32) / math.sqrt(dimension) labels = (np.matmul(features, ground_truth_weights) &gt; ground_truth_threshold).astype(np.float32) mislabeled_indices = np.random.choice( num_examples, num_mislabeled_examples, replace=False) labels[mislabeled_indices] = 1 - labels[mislabeled_indices] return torch.tensor(labels), torch.tensor(features) class tools: def __init__(self): self.name = 'x_2' def SomeFunc(self, model, input_): print(model.first_term(input_)[0]) # change to model.module.first_term when the flag is True class predictor(nn.Module): def __init__(self, dim): super(predictor, self).__init__() self.weights = torch.nn.Parameter(torch.zeros(dim, 1, requires_grad=True)) self.threshold = torch.nn.Parameter(torch.zeros(1, 1, requires_grad=True)) def first_term(self, features): return features @ self.weights def forward(self, features): return self.first_term(features) - self.threshold class HingeLoss(nn.Module): def __init__(self): super(HingeLoss, self).__init__() self.relu = nn.ReLU() def forward(self, output, target): all_ones = torch.ones_like(target) labels = 2 * target - all_ones losses = all_ones - torch.mul(output.squeeze(1), labels) return torch.norm(self.relu(losses)) class function(object): def __init__(self, epochs): dim = 10 N = 100 self.target, self.features = _data(dim, N) self.epochs = epochs self.model = predictor(dim).to('cuda') self.optimizer = optim.SGD(self.model.parameters(), lr=1e-3) self.target = self.target.to('cuda') self.features = self.features.to('cuda') self.loss_function = HingeLoss().to('cuda') self.tools = tools() def train(self): self.model.train() for epoch in range(self.epochs): self.optimizer.zero_grad() output = self.model(self.features) # self.tools.SomeFunc(self.model, self.features) print(output.is_cuda) loss = self.loss_function(output, self.target) loss.backward() print('For epoch {}, loss is: {}.'.format(epoch, loss.item())) self.optimizer.step() def main(): model = function(1000) print(torch.cuda.device_count()) if False: # This is Flag if torch.cuda.device_count() &gt; 1: model.model = nn.DataParallel(model.model) t = time.time() model.train() print('elapsed: {}'.format(time.time() - t)) if __name__ == '__main__': main() </code></pre> <p>As far as I understand setting <em>the flag</em> to <code>True</code> should fix the thing, but my run time increases from 1 sec to 15 sec's. I was wondering how to improve the performance.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T12:05:28.617", "Id": "244781", "Score": "2", "Tags": [ "pytorch" ], "Title": "Enhancing performance using DataParallel" }
244781
<p>This is a follow-up to my <a href="https://codereview.stackexchange.com/questions/244714/blackjack-with-card-representation-visuals">original post of Blackjack with card representation visuals</a></p> <p>I was given some very helpful advice by @Reinderien and @Linny which I greatly appreciate.</p> <p>I have done my best to implement the changes. However, I am unsure if I actually implemented these changes in the best way, and would love if anybody can take a look/ provide any feedback. I'm always looking to learn more and improve, so I greatly appreciate any feedback or additional comments.</p> <p>With regards to typing, is it common practice to include type annotations on every function? I can't help but feel it makes the file more cluttered?<br /> But if so, what is the best practice with class methods where the only parameter is the instance <code>self</code> ?</p> <p>Additionally, some of my methods don't actually return anything, but rather, they update the state of something. in these cases, did I handle them correctly, with the type hint of <code>-&gt; None</code></p> <p>I also added <code>from __future__ import annotations</code> in order to use type hints for classes I created. Is this the intended usage of the library/ correct way to handle these cases?</p> <p>To implement the various changes, I ended up needing to import a few more modules; but I'm curious if it's frowned upon to have too many imports? At a certain point, can it actually impact performance?</p> <p>Here is the link to Github <a href="https://github.com/zsonnen/blackjack" rel="nofollow noreferrer">Blackjack game</a> which also contains a <code>visuals.py</code> file.</p> <p>Thank you so much in advance:<br /> The updated code:</p> <pre><code>from __future__ import annotations import random import collections import time import os from typing import Sequence import subprocess as sp import visuals &quot;&quot;&quot; BLACKJACK GAME: visuals file imported: numerous pretty ways to display cards &quot;&quot;&quot; def clear(): sp.run(('cls' if os.name == 'nt' else 'clear'), shell=True) def validate_answer(question: str, choices: Sequence[str]) -&gt; bool: while answer := input(question).lower(): if answer in choices: return answer == choices[0] YES_NO = 'yn' Card = collections.namedtuple('Card', ['value', 'suit']) class Deck: values = [str(v) for v in range(2, 11)] + list('JQKA') suits = &quot;Spades Diamonds Hearts Clubs&quot;.split() suit_symbols = ['♠','♦','♥','♣'] def __init__(self, num_decks = 1): self.num_decks = num_decks self.cards = [Card(value, suit) for suit in self.suits for value in self.values] * self.num_decks self.length = len(self) def __repr__(self): deck_cards = &quot;Deck()\n&quot; for card in self.cards: deck_cards += f&quot;({card.value}-{card.suit})&quot; return deck_cards def __len__(self): return len(self.cards) def __getitem__(self, position): return self.cards[position] def draw_card(self): return self.cards.pop() def shuffle(self): random.shuffle(self.cards) #Shuffle when deck is &lt; 50% full length def is_shuffle_time(self): return len(self) &lt; (self.length / 2) def shuffle_time(self): clear() print(&quot;Reshuffling the Deck...\n&quot;) time.sleep(1) self.reset() self.shuffle() def reset(self): self.cards = [Card(value, suit) for suit in self.suits for value in self.values] * self.num_decks class Hand: def __init__(self): self.hand = [] def __repr__(self): hand_cards = &quot;Hand()\n&quot; for card in self.hand: hand_cards += f&quot;({card.value}-{card.suit})&quot; return hand_cards def add_card(self, *cards: tuple) -&gt; None: for card in cards: self.hand.append(card) def remove_card(self): return self.hand.pop() def hit(self, deck: Deck) -&gt; None: card = deck.draw_card() self.add_card(card) def hand_score(self): self.card_val = [10 if card.value in ['J','Q','K'] else 1 if card.value == 'A' else int(card.value) for card in self.hand] self.card_scores = dict(zip(self.hand, self.card_val)) score = 0 for card in self.hand: card_score = self.card_scores[card] score += card_score if any(card.value == 'A' for card in self.hand) and score &lt;= 11: score += 10 return score def card_visual(self): card_list = [] for card in self.hand: card_vis = visuals.reg_card_visual(card) card_list.append(card_vis) visuals.print_cards(card_list) print(f&quot;\nTotal of: {self.hand_score()}\n&quot;) def mini_card_visual(self): card_list = [] for card in self.hand: card_vis = visuals.mini_card_visual(card) card_list.append(card_vis) visuals.print_cards(card_list) print(f&quot;\nTotal of: {self.hand_score()}\n&quot;) class Player(Hand): def __init__(self, chips, bet=0, split_cards = False): super().__init__() self.chips = chips self.bet = bet self.profit = 0 self.alive = True self.split_cards = split_cards self.has_blackjack = False def deal_cards(self, deck: Deck) -&gt; None: self.hit(deck) self.hit(deck) print_line('Player Cards') self.card_visual() self.has_blackjack = self.check_for_blackjack() self.split_cards = self.check_for_split() self.apply_split(deck) def add_chips(self, chips: float) -&gt; None: self.chips += chips def remove_chips(self, chips: float) -&gt; None: self.chips -= chips def print_balance(self): print(f&quot;\nYour balance is currently: ${self.chips:,.2f}\n&quot;) def check_for_blackjack(self): return len(self.hand) == 2 and self.hand_score() == 21 def check_for_split(self): if self.hand[0].value == self.hand[1].value: return validate_answer(&quot;Do you want to split your cards?: [y / n]: &quot;, YES_NO) return False def wager(self): while True: self.print_balance() bet = input(f&quot;How much would you like to bet?: $&quot;) if not bet.isdecimal(): continue elif float(bet) &gt; self.chips: print(&quot;sorry, you don't have enough chips. Try again&quot;) else: self.bet = float(bet) self.remove_chips(float(bet)) break def added_wager(self): while True: self.print_balance() bet = input(f&quot;Enter additional wager. You may bet up to your original ${self.bet} or less: $&quot;) if not bet.isdecimal() or float(bet) &gt; self.bet: continue elif float(bet) &gt; self.chips: print(&quot;You don't have enough chips. Try again&quot;) else: self.bet_two = float(bet) self.remove_chips(float(bet)) break def confirm_double(self): return validate_answer(&quot;\nYou will only get 1 more card. Confirm you want to double down: [y / n]: &quot;, YES_NO) def double_down(self, deck: Deck) -&gt; None: self.added_wager() self.bet += self.bet_two self.visual_move(deck) if self.hand_score() &gt; 21: self.alive = False def apply_split(self, deck: Deck) -&gt; None: if self.split_cards: self.added_wager() self.hand_two = Player(0, split_cards=True, bet=self.bet_two) transfer_card = self.remove_card() self.hand_two.add_card(transfer_card) self.hit(deck) self.hand_two.hit(deck) print(&quot;\nFirst Hand: &quot;) self.mini_card_visual() time.sleep(1) self.player_move(deck) print(&quot;\nSecond Hand: &quot;) self.hand_two.mini_card_visual() time.sleep(1) self.hand_two.player_move(deck) time.sleep(1) def visual_move(self, deck: Deck) -&gt; None: self.hit(deck) if self.split_cards: self.mini_card_visual() else: self.card_visual() def player_move(self, deck: Deck) -&gt; None: while True: if self.hand_score() &gt; 21 or self.has_blackjack: self.alive = False break if self.hand_score() == 21: break if len(self.hand) == 2: action = input(&quot;Would you like to hit, stand, or double-down? Enter [h, s, or d]: &quot;) else: action = input(&quot;Would you like to hit or stand: Enter [h or s]: &quot;) if action == 'd': if len(self.hand) == 2: if self.confirm_double(): self.double_down(deck) break if action == &quot;h&quot;: self.visual_move(deck) if action == &quot;s&quot;: break def compute_results(self, dealer: Dealer) -&gt; None: if self.alive and dealer.alive: if self.hand_score() &gt; dealer.hand_score(): print(&quot;WINNER!\n&quot;) self.profit = 2 elif self.hand_score() == dealer.hand_score(): print(&quot;PUSH!\n&quot;) self.profit = 1 else: print(&quot;LOSER! Dealer Wins\n&quot;) elif not self.alive: if self.has_blackjack: print(&quot;YOU HAVE BLACKJACK!\n&quot;) self.profit = 2.5 else: print(&quot;BUST! LOSER!\n&quot;) else: print(&quot;DEALER BUSTS. YOU WIN!\n&quot;) self.profit = 2 self.settle() def settle(self): self.add_chips(self.profit*self.bet) def reset(self): self.hand = [] self.alive = True self.split_cards = False self.profit = 0 self.bet, self.bet_two = 0, 0 class Dealer(Hand): def __init__(self): super().__init__() self.alive = True def deal_cards(self, deck: Deck) -&gt; None: self.hit(deck) self.hit(deck) print_line('Dealer Cards') self.dealer_visual() time.sleep(1) def reset(self): self.hand = [] self.alive = True def card_reveal(self): print_line('Dealer Cards') time.sleep(1) self.card_visual() time.sleep(1) def dealer_move(self, deck: Deck) -&gt; None: self.card_reveal() while True: if self.hand_score() in range(17, 22): break if self.hand_score() &gt; 21: self.alive = False break if self.hand_score() &lt; 17: self.hit(deck) time.sleep(1) self.card_visual() def dealer_visual(self): card_list = [] hidden_card = visuals.reg_hidden_card card_list.append(hidden_card) for card in self.hand[1:]: card_vis = visuals.reg_card_visual(card) card_list.append(card_vis) visuals.print_cards(card_list) def play_again(): if validate_answer(&quot;Would you like to play another round? [y / n]: &quot;, YES_NO): clear() return True return False def print_line(word: str) -&gt; None: print(f&quot;\n______________________[{word}]______________________________\n&quot;) def game(): print_line('WELCOME TO BLACKJACK!!') num_decks = 6 player_chips = 1_000 player = Player(player_chips) dealer = Dealer() deck = Deck(num_decks) deck.shuffle() while True: if player.chips == 0: print(&quot;You're out of money. Game Over&quot;) break print(f&quot;Percentage of shoe not yet dealt: {len(deck)/(52*num_decks):.2%}&quot;) if deck.is_shuffle_time(): deck.shuffle_time() player.wager() dealer.deal_cards(deck) player.deal_cards(deck) if not player.split_cards: player.player_move(deck) if player.alive: dealer.dealer_move(deck) player.compute_results(dealer) # PLAYER SPLIT CARDS else: if player.alive or player.hand_two.alive: dealer.dealer_move(deck) print(&quot;HAND ONE:&quot;) player.compute_results(dealer) print(&quot;HAND TWO:&quot;) player.hand_two.compute_results(dealer) # Any chips won by second hand: Add it to total balance player.chips += player.hand_two.chips player.print_balance() if play_again(): player.reset() dealer.reset() continue else: break print(&quot;Thanks for playing. Goodbye.&quot;) if __name__ == &quot;__main__&quot;: game() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T14:22:51.667", "Id": "480596", "Score": "0", "body": "Are you using Python 3?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T14:36:03.040", "Id": "480597", "Score": "0", "body": "@Reinderien yes. python 3.8. is there anything I'm doing that suggests an older version?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T14:36:40.173", "Id": "480598", "Score": "0", "body": "`__future__`. You should just be using `typing`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T14:53:25.790", "Id": "480599", "Score": "0", "body": "I was trying to understand the usage of it. it seems to be a feature not introduced until 3.7 though I might be wrong. but if i don't include it, i get an error \"NameError: name 'Dealer' is not defined\" as an example, used in typing. as that is a class I created." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T14:54:40.737", "Id": "480600", "Score": "0", "body": "Read https://docs.python.org/3/library/typing.html . Right at the top, it says _New in version 3.5_. Your `NameError` is due to a different reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T14:57:41.650", "Id": "480601", "Score": "0", "body": "https://stackoverflow.com/a/33533514/13558944\nfor clarity: this seems to be the issue I am referring to" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T15:25:18.397", "Id": "480604", "Score": "1", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/110065/discussion-between-reinderien-and-zach-sonnenblick)." } ]
[ { "body": "<h1>Default Parameters</h1>\n<p>There should be no spaces before or after the <code>=</code>.</p>\n<pre><code>def __init__(self, chips, bet=0, split_cards=False):\n</code></pre>\n<h1><code>Hand.__repr__</code></h1>\n<p>You can utilize the <code>.join</code> function to append to strings.</p>\n<pre><code>def __repr__(self):\n return &quot;Hand()\\n&quot; + ''.join(f&quot;({card.value}-{card.suit)&quot; for card in self.hand)\n</code></pre>\n<h1><code>Hand.card_visual</code></h1>\n<p>You can use list comprehension to shorten this method.</p>\n<pre><code>def card_visual(self):\n card_list = [visuals.reg_card_visual(card) for card in self.hand]\n visuals.print_cards(card_list)\n print(f&quot;\\nTotal of: {self.hand_score()}\\n&quot;)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T15:59:47.917", "Id": "244792", "ParentId": "244785", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T13:27:02.023", "Id": "244785", "Score": "3", "Tags": [ "python", "object-oriented", "playing-cards", "classes" ], "Title": "follow up: Blackjack with card representation visuals" }
244785
<p>Out of the majority of my c++ projects, the most used thing is std::vector because it allows me to not have to my own memory management. However previously I had never really thought much about how std::vector works internally. Until recently and that's when I decided that to better understand std::vector I should attempt to reimplement it. Here is the code</p> <p>vector.hh</p> <pre><code>#ifndef VECTOR_H #define VECTOR_H #include &lt;memory&gt; #include &lt;new&gt; /*https://en.cppreference.com/w/cpp/container/vector is very helpful*/ namespace turtle { namespace helper { constexpr size_t upper_power_of_two(size_t v) { v--; v |= v &gt;&gt; 1; v |= v &gt;&gt; 2; v |= v &gt;&gt; 4; v |= v &gt;&gt; 8; v |= v &gt;&gt; 16; if constexpr (sizeof(size_t) == 8) { v |= v &gt;&gt; 32; } v++; return v; } template&lt;typename Pointer&gt; constexpr auto distance(Pointer first, Pointer last) -&gt; decltype(last - first) { return last - first; } } template&lt;typename T, typename Alloc = std::allocator&lt;T&gt;&gt; class vector { public: using value_type = T; using pointer = typename std::allocator_traits&lt;Alloc&gt;::pointer; using const_pointer = typename std::allocator_traits&lt;Alloc&gt;::const_pointer; using iterator = pointer; using const_iterator = const_pointer; using reverse_iterator = std::reverse_iterator&lt;iterator&gt;; using const_reverse_iterator = const std::reverse_iterator&lt;iterator&gt;; using size_type = typename std::allocator_traits&lt;Alloc&gt;::size_type; using allocator_type = Alloc; using difference_type = typename std::allocator_traits&lt;Alloc&gt;::difference_type; using reference = T &amp;; using const_reference = const T &amp;; constexpr vector() noexcept(noexcept(Alloc())) = default; constexpr explicit vector(const allocator_type &amp;alloc) noexcept: allocator_(alloc) {} constexpr vector(const size_type count, const T &amp;value, const allocator_type &amp;alloc = allocator_type()) : allocator_(alloc) { resize(count, value); } constexpr explicit vector(size_type count, const allocator_type &amp;alloc = allocator_type()) : allocator_( alloc) { resize(count); } template&lt;typename InputIt&gt; constexpr vector(InputIt first, InputIt last, const allocator_type &amp;alloc = allocator_type()) : allocator_( alloc) { insert(begin(), first, last); } constexpr vector(const vector &amp;other) { insert(cbegin(), other.cbegin(), other.cend()); } constexpr vector(const vector &amp;other, const allocator_type &amp;alloc) : allocator_(alloc) { insert(cbegin(), other.cbegin(), other.cend()); } constexpr vector(vector &amp;&amp;other) noexcept: data_(other.data_), size_(other.size_), capacity_(other.capacity_) { other.data_ = nullptr; other.capacity_ = 0; other.size_ = 0; } constexpr vector(vector &amp;&amp;other, const Alloc &amp;alloc) { *this = vector(other); allocator_ = alloc; } constexpr ~vector() { T_destroy(begin(), end()); std::allocator_traits&lt;allocator_type&gt;::deallocate(allocator_, data_, capacity_); } constexpr vector(const std::initializer_list&lt;T&gt; &amp;list, const Alloc &amp;alloc = Alloc()) : allocator_(alloc), size_(list.size()) { reallocate(list.size()); std::uninitialized_move(list.begin(), list.end(), begin()); } constexpr vector &amp;operator=(const vector &amp;other) { vector temp = other; swap(temp); return *this; } constexpr vector &amp;operator=(const std::initializer_list&lt;T&gt; &amp;other) { *this = vector(other); return *this; } constexpr void resize(const size_type &amp;size) { if (size &gt; capacity_) { reallocate(size); std::uninitialized_default_construct(begin() + size_, begin() + capacity_); } else if (size &lt; size_) { T_destroy(begin() + size, begin() + size_); } size_ = size; } constexpr void resize(const size_type &amp;size, const T &amp;x) { if (size &gt; capacity_) { reallocate(size); std::uninitialized_fill(begin() + size_, begin() + capacity_, x); } else if (size &lt; size_) { T_destroy(begin() + size, begin() + size_); } size_ = size; } constexpr void reserve(const size_type &amp;size) { if (size &lt; capacity_) return; reallocate(size); } constexpr void clear() noexcept { T_erase_at_true_end(cbegin() + (capacity_ - size_)); size_ = 0; } constexpr void shrink_to_fit() { reallocate(0); capacity_ = 0; } constexpr void push_back(const T &amp;item) { emplace_back(item); } constexpr void push_back(T &amp;&amp;item) { emplace_back(std::move(item)); } template&lt;typename... Args&gt; constexpr void push_back(Args &amp;&amp;... args) { (push_back(std::forward&lt;Args&gt;(args)), ...); } constexpr void push_back(std::initializer_list&lt;T&gt; list) { insert(end(), list); } constexpr void pop_back() { resize(size_ - 1); } constexpr iterator insert(const_iterator pos, const T &amp;item) { return T_insert(helper::distance(cbegin(), pos), item); } constexpr iterator insert(const_iterator pos, T &amp;&amp;item) { return T_insert(helper::distance(cbegin(), pos), std::move(item)); } constexpr iterator insert(const_iterator pos, size_type count, const T &amp;value) { return T_fill_insert(helper::distance(cbegin(), pos), count, value); } template&lt;typename InputIterator&gt; constexpr void insert(const_iterator pos, InputIterator first, InputIterator last) { T_fill_range(helper::distance(cbegin(), pos), first, last); } constexpr void insert(const_iterator pos, std::initializer_list&lt;T&gt; list) { T_fill_range(helper::distance(cbegin(), pos), list.begin(), list.end()); } constexpr iterator erase(iterator pos) { return T_erase_at(pos); } constexpr iterator erase(iterator first, iterator last) { return T_erase_range(first, last); } template&lt;typename... Args&gt; constexpr void emplace_back(Args &amp;&amp;... args) { emplace(end(), std::forward&lt;Args&gt;(args)...); } template&lt;typename... Args&gt; constexpr void emplace(iterator pos, Args &amp;&amp;... args) { difference_type offset = pos - begin(); T_grow(size_ + 1); size_++; /*shift array*/ std::uninitialized_move(begin() + offset, end() - 1, begin() + offset + 1); std::allocator_traits&lt;allocator_type&gt;::construct(allocator_, data_ + offset, std::forward&lt;Args&gt;(args)...); } constexpr void swap(vector &amp;other) { std::swap(other.data_, data_); std::swap(other.size_, size_); std::swap(other.capacity_, capacity_); } constexpr void assign(size_type count, const T &amp;value) { if (count &gt; size_) { resize(count); } //resize if necessary std::fill(begin(), end(), value); // fill array } constexpr void assign(iterator first, iterator last) { clear(); insert(begin(), first, last); } constexpr void assign(const std::initializer_list&lt;T&gt; &amp;list) { clear(); insert(begin(), list); //insert list } constexpr reference operator[](const size_type &amp;index) noexcept { return *std::launder(begin() + index); } constexpr const_reference operator[](const size_type &amp;index) const noexcept { return *std::launder(begin() + index); } constexpr reference at(const size_type &amp;index) { return (*this)[index]; } constexpr const_reference at(const size_type &amp;index) const { return (*this)[index]; } constexpr const T *data() const { return data_; } constexpr T *data() { return data_; } constexpr const_reference front() const { return *cbegin(); } constexpr const_reference back() const { return *cend(); } constexpr reference front() { return (*this)[0]; } constexpr reference back() { return (*this)[size_ - 1]; } constexpr const size_type &amp;size() const { return size_; } constexpr const size_type &amp;capacity() const { return capacity_; } constexpr bool empty() { return !size_; } constexpr size_type max_size() { return std::allocator_traits&lt;allocator_type&gt;::max_size(allocator_); } constexpr allocator_type get_allocator() const { return allocator_; } constexpr iterator begin() noexcept { return iterator(data_); } constexpr iterator end() noexcept { return iterator(data_) + size_; } constexpr const_iterator begin() const noexcept { return const_iterator(data_); } constexpr const_iterator end() const noexcept { return const_iterator(data_) + size_; } constexpr const_iterator cbegin() const noexcept { return const_iterator(data_); } constexpr const_iterator cend() const noexcept { return const_iterator(data_) + size_; } constexpr reverse_iterator rbegin() noexcept { return std::reverse_iterator(end()); } constexpr reverse_iterator rend() noexcept { return std::reverse_iterator(begin()); } constexpr const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(end()); } constexpr const_reverse_iterator crend() const noexcept { return const_reverse_iterator(begin()); } constexpr bool operator==(const vector &amp;rhs) const { if (size_ != rhs.size()) { return false; } // if the to vectors size's don't match return false for (size_type i = static_cast&lt;size_type&gt;(0); i &lt; size_; ++i) { if (rhs[i] != data_[i]) return false; } // compare each item in both vectors return true; } private: T *data_ = nullptr; size_type size_ = 0; size_type capacity_ = 0; allocator_type allocator_; constexpr iterator T_fill_insert(difference_type offset, size_type n, const T &amp;x) { T_grow(size_ + n); size_ += n; iterator pos = begin() + offset; std::uninitialized_move(pos, end() - n, pos + n); std::uninitialized_fill(pos, pos + n, x); // fill return pos; } constexpr iterator T_insert(difference_type offset, const T &amp;x) { T_grow(size_ + 1); size_++; iterator pos = begin() + offset; std::uninitialized_move(pos, end() - 1, pos + 1); std::allocator_traits&lt;Alloc&gt;::construct(allocator_, pos, x); return begin() + offset; } constexpr iterator T_insert(difference_type offset, T &amp;&amp;x) { T_grow(size_ + 1); size_++; iterator pos = begin() + offset; std::uninitialized_move(pos, end() - 1, pos + 1); std::allocator_traits&lt;Alloc&gt;::construct(allocator_, pos, std::move(x)); return begin() + offset; } template&lt;typename InputIterator&gt; constexpr void T_fill_range(difference_type offset, InputIterator first, InputIterator last) { difference_type n = helper::distance(first, last); iterator pos; T_grow(size_ + n); size_ += n; pos = begin() + offset; std::uninitialized_move(pos, end() - n, pos + n); std::uninitialized_copy(first, last, pos); } constexpr bool T_grow(size_type size) { if (size &gt; capacity_) { reallocate(helper::upper_power_of_two(size)); return true; } return false; } constexpr void T_erase_at_end(const_iterator pos) { difference_type offset = helper::distance(cbegin(), pos); T_destroy(begin() + offset, end()); } constexpr void T_erase_at_true_end(const_iterator pos) { difference_type offset = helper::distance(cbegin(), pos); T_destroy(begin() + offset, begin() + capacity_); } constexpr void reallocate(const size_type &amp;newSize) { if (!data_) { data_ = allocator_.allocate(newSize); capacity_ = newSize; } else { T *temp = allocator_.allocate(newSize &gt; capacity_ ? newSize : capacity_); std::uninitialized_move(data_, data_ + capacity_, temp); T_destroy(begin(), end()); allocator_.deallocate(data_, capacity_); data_ = temp; capacity_ = newSize &gt; capacity_ ? newSize : capacity_; } } constexpr iterator T_erase_range(iterator first, iterator last) { size_type offset = last - begin(); size_type rangeSize = helper::distance(first, last); std::copy(first + rangeSize, end(), first); if (rangeSize) T_erase_at_end(begin() + capacity_ - rangeSize); size_ -= rangeSize; return (begin() + offset) &gt;= end() ? end() : last == first ? begin() + offset : begin() + offset + 1; } constexpr iterator T_erase_at(iterator pos) { size_type offset = pos - begin(); std::copy(pos + 1, end(), pos); T_erase_at_end(end() - 1); --size_; return (begin() + offset) &gt;= end() ? end() : begin() + offset; } constexpr void T_destroy(iterator first, iterator last) { for (; first != last; first++) std::allocator_traits&lt;allocator_type&gt;::destroy(allocator_, first); } }; template&lt;typename T, typename Alloc, typename U&gt; constexpr auto erase(vector&lt;T, Alloc&gt; &amp;c, const U &amp;value) { auto it = std::remove(c.begin(), c.end(), value); auto r = helper::distance(it, c.end()); c.erase(it, c.end()); return r; } template&lt;typename T, typename Alloc, typename Pred&gt; constexpr auto erase_if(vector&lt;T, Alloc&gt; &amp;c, const Pred &amp;pred) { auto it = std::remove_if(c.begin(), c.end(), pred); auto r = helper::distance(it, c.end()); c.erase(it, c.end()); return r; } namespace pmr { template&lt;typename T&gt; using vector = turtle::vector&lt;T, std::pmr::polymorphic_allocator&lt;T&gt;&gt;; } } // namespace turtle #endif // VECTOR_H </code></pre>
[]
[ { "body": "<p>First of all, I have to commend you on even attempting this undertaking. As you probably discovered, <code>std::vector</code> is a <em>lot</em> more complicated than it first appears. I believe implementing <code>std::vector</code> is a <em>very</em> good learning exercise… <em>especially</em> if you’re going to go whole hog and make it allocator-aware (whenever I’ve had students reimplement <code>std::vector</code>, I don’t ask them to add allocator support, because it’s so complicated (and, historically, <em>woefully</em> underspecified)).</p>\n<p>And reimplmenting <code>std::vector</code> is not even really a waste of time, because there are ways you can actually <em>improve</em> on <code>std::vector</code>: for example, by implementing the “small string optimization” trick, which is illegal for <code>std::vector</code> due to iterator invalidation requirments, but could be a massive performance gain. I note you’ve actually added some extra functions.</p>\n<p>So kudos for even <em>attempting</em> this. And it’s a really good attempt, too!</p>\n<p>So, let’s dive into the review:</p>\n<pre><code>constexpr size_t upper_power_of_two(size_t v) {\n v--;\n v |= v &gt;&gt; 1;\n v |= v &gt;&gt; 2;\n v |= v &gt;&gt; 4;\n v |= v &gt;&gt; 8;\n v |= v &gt;&gt; 16;\n if constexpr (sizeof(size_t) == 8) { v |= v &gt;&gt; 32; }\n v++;\n return v;\n}\n</code></pre>\n<p>One of my biggest pet peeves when reviewing people’s code—and pretty much the first thing I look for—is bad comments… or worse, no comments. Now, in your case you can mostly get away without comments, because you’re simply reimplementing <code>std::vector</code>… it doesn’t really make a lot of sense to have a bunch of comments like <code>/* void push_back(T const&amp;): Does what std::vector::push_back(T const&amp;) does. */</code>. But for things like this function… you really do need comments to explain what you’re doing, and why.</p>\n<p>So, what I’m assuming is that you want your vector’s size when automatically growing—when the size isn’t <em>specifically</em> being set, such as in a call to <code>resize()</code> or <code>reserve()</code>—to always be a power of 2. That’s cool; there’s nothing wrong with that… but I can’t help but wonder if that’s not just based on a misunderstanding of growth factors. Most standard library vectors have a growth factor of 2 (I think Dinkumware’s is 1.5)… but that doesn’t mean the vector’s size is a power of 2. It just means they multiply the current size by 2. So your <code>T_grow()</code> function’s guts would look something like: <code>reallocate(max(capacity_ * 2, size));</code>.</p>\n<p>The thing with what you’re doing is that in the worst case scenario, the vector’s size will grow to almost double the <em>requested</em> size… as opposed to double the <em>current</em> size. For example, imagine the current capacity is 10,000, and I want to put 17,000 elements in it. If you do <code>max(10'000 * 2, 17'000)</code>, that will give you a new capacity of 20,000. But if you do <code>upper_power_of_two(17'000)</code>, that will give you 32,768… almost 13,000 more than with a growth factor of 2, and almost 16,000 more than we actually need. In fact, your vector will <em>never</em> allocate less than with a growth factor of 2 strategy. The benefit of that: much less frequent allocations. The downside: much more memory used. That may or may not be a trade-off that works for you.</p>\n<p>Anywho, as for the function itself, I should note that you’ve wisely checked to make sure that <code>std::size_t</code> is 64 bits before doing the last bit shift. Buuuuut….</p>\n<ol>\n<li>You assume that <code>sizeof(std::size_t) == 8</code> means 64 bits. No, that just means that 8 <em>bytes</em>… and a byte is not <em>necessarily</em> 8 bits. If you’re going to assume 8 bit bytes, you should confirm that by checking <code>CHAR_BIT</code>.</li>\n<li>You check that the size is <em>equal</em> to 8 bytes… but what if you’re on a system with 8 bit bytes and 128 bit std::size_t (it could happen!). Then <code>sizeof(std::size_t)</code> would be 16. I think what you meant was <code>sizeof(std::size_t) &gt;= 8</code>.</li>\n<li>You don’t take into account that <code>std::size_t</code> could be 16 bits. It could be!</li>\n</ol>\n<p>This functon could actually be greatly simplified by <em>not</em> unrolling the loop. For example:</p>\n<pre><code>constexpr auto upper_power_of_two(std::size_t v)\n{\n constexpr auto bit_size = std::size_t(CHAR_BIT * sizeof(std::size_t));\n \n --v;\n for (auto i = std::size_t{1}; i &lt; bit_size; ++i)\n v |= v &gt;&gt; i;\n return ++v;\n}\n</code></pre>\n<p>Now it will correctly handle <em>any</em> size of <code>std::size_t</code>… <em>any</em> size of byte… and you count on any half-decent compilier automatically unrolling the loop for you (or, if it’s <em>really</em> smart, maybe recognizing what you’re doing and using some intrinsics).</p>\n<pre><code>template&lt;typename Pointer&gt;\nconstexpr auto distance(Pointer first, Pointer last) -&gt; decltype(last - first) {\n return last - first;\n}\n</code></pre>\n<p>The trailing return type is a little redundant here. I assume the point of this function is so you don’t need to include <code>&lt;iterator&gt;</code>? But, thing is, you already need <code>&lt;iterator&gt;</code> anyway because you’re using <code>std::reverse_iterator</code> (and, in fact, your code is wrong for not including it, though I suppose it “works” because it’s picking the header up transitively somehow, probably via <code>&lt;memory&gt;</code>).</p>\n<p>So you might as well include <code>&lt;iterator&gt;</code>, and then use <code>std::distance()</code>.</p>\n<pre><code>template&lt;typename T, typename Alloc = std::allocator&lt;T&gt;&gt;\nclass vector\n{\n</code></pre>\n<p>Now, I would recommend that you always practice safe specialization with your templates, and check that the types the template is being instantiated with are types that make sense. That generally means that you should have a bunch of <code>static_assert</code> statements, verifying your template parameters.</p>\n<p>What things should you check for? Well, figuring that out is a large part of figuring out your type and its interface. But as an example, in this case, it might be wise to make sure that <code>T</code> isn’t a reference type with <code>static_assert(not std::is_reference_v&lt;T&gt;)</code>.</p>\n<pre><code>constexpr vector(const vector &amp;other) { insert(cbegin(), other.cbegin(), other.cend()); }\n</code></pre>\n<p>You copy the other vector’s contents here… but you don’t copy its <em>allocator</em>.</p>\n<p>And unfortunately, doing so isn’t as simple as <code>allocator_(other.allocator_)</code>. What you need to do is:</p>\n<pre><code>constexpr vector(const vector &amp;other) :\n allocator_(std::allocator_traits&lt;Alloc&gt;::select_on_container_copy_construction(other.allocator_))\n{ insert(cbegin(), other.cbegin(), other.cend()); }\n</code></pre>\n<p>You also forget to move the allocator when moving the vector:</p>\n<pre><code>constexpr vector(vector &amp;&amp;other) noexcept: data_(other.data_), size_(other.size_), capacity_(other.capacity_) {\n other.data_ = nullptr;\n other.capacity_ = 0;\n other.size_ = 0;\n}\n</code></pre>\n<p>Luckily this is an easy fix, because you can just do <code>allocator_(std::move(other.allocator_))</code> and everything else is cool.</p>\n<p>Unfortunately…</p>\n<pre><code>constexpr vector(vector &amp;&amp;other, const Alloc &amp;alloc) {\n *this = vector(other);\n allocator_ = alloc;\n}\n</code></pre>\n<p>… things are not going to be so simple here.</p>\n<p><em>If</em> <code>alloc</code> and <code>other._allocator</code> compare equal, then you can safely treat them as indistinct, meaning you can deallocate stuff using <code>alloc</code> even if it was originally allocated by <code>other._allocator</code>. That allows you to do a simple move of the pointer:</p>\n<pre><code>constexpr vector(vector &amp;&amp;other, const Alloc &amp;alloc) :\n _allocator(alloc)\n{\n if (_allocator == other._allocator)\n {\n using std::swap;\n \n swap(data_, other.data_);\n swap(size_, other.size_);\n swap(capacity_, other.capacity_);\n }\n else\n {\n // ...\n }\n}\n</code></pre>\n<p>But if the allocators <em>don’t</em> compare equal, then you <em>can’t</em> use <code>allocator_</code> to deallocate <code>data_</code> that was allocated by <code>other.allocator_</code>. In that case, your only recourse is to copy:</p>\n<pre><code>constexpr vector(vector &amp;&amp;other, const Alloc &amp;alloc) :\n _allocator(alloc)\n{\n if (_allocator == other._allocator)\n {\n using std::swap;\n \n swap(data_, other.data_);\n swap(size_, other.size_);\n swap(capacity_, other.capacity_);\n }\n else\n {\n insert(begin(), other.cbegin(), other.cend());\n }\n}\n</code></pre>\n<p>Now you’re probably guessing that if the copy and move constructors were that complicated, the <em>assignment</em> ops are going to be much, much worse. If so, you’d be right.</p>\n<p>But first, there’s one more major allocator complication I have to mention:</p>\n<pre><code>constexpr vector(const std::initializer_list&lt;T&gt; &amp;list, const Alloc &amp;alloc = Alloc()) : allocator_(alloc),\n size_(list.size()) {\n reallocate(list.size());\n std::uninitialized_move(list.begin(), list.end(), begin());\n}\n</code></pre>\n<p>Now, you use <code>std::uninitialized_move()</code> and its siblings quite a bit, and that’s good… <em>but</em>… the problem is that what you <em>should</em> be using is <code>std::allocator_traits&lt;Alloc&gt;::construct()</code>. And unfortunately, <code>std::uninitialized_move()</code> doesn’t use that.</p>\n<p>What that means is—and you’re going to hate me for telling you this—you need to <em>reimplment</em> all those uninitialized functions in terms of <code>std::allocator_traits&lt;Alloc&gt;::construct()</code>. Yeah. All of them. (Well, the ones you use anyway.)</p>\n<p>You may be think that’s madness, and why doesn’t the standard library have uninitialized functions for allocators?! I wholeheartedly agree. I’ve seen some proposals for them in the past, but I don’t think they’ve been championed yet. But yes, the standard library absolutely should support allocators with those uninitialized algorithms. It should also have a smart pointer for allocator-allocated memory (which you’re going to see come up later). Unfortunately, we have to work with what we’ve got.</p>\n<p>So you’ll need to reimplement all those uninitialized algorithms you use in terms of allocators, and use them instead of the ones you’re using now. I’m sorry to be the one to tell you this. Yeah, this is why I don’t push my students to work with allocators.</p>\n<p>Anywho, moving on….</p>\n<pre><code>constexpr vector &amp;operator=(const vector &amp;other) {\n vector temp = other;\n swap(temp);\n return *this;\n}\n</code></pre>\n<p>This is great; this would be the correct thing to do… if allocators weren’t a factor. Let’s put allocators aside for the moment, though. Although this creates an entire third vector, with a possibly redundant internal memory buffer, that’s what you need to do to account for exceptions.</p>\n<p>Except… not always though, eh?</p>\n<p>Because if <code>T</code> is <code>noexcept</code> copyable, then all you need to do is <em>possibly</em> grow the internal memory buffer (if and only if <code>other.size() &gt; this-&gt;capacity()</code>… then just copy over whatever’s there. In other words:</p>\n<pre><code>constexpr auto operator=(vector const&amp; other) -&gt; vector&amp;\n{\n if constexpr (std::is_nothrow_copy_constructible&lt;T&gt;)\n {\n if (capacity() &lt; other.size())\n // This might conceivably throw.\n reserve(other.size());\n \n // This shouldn't throw, because all it should do is destruct\n // all existing elements (and destructors shouldn't throw),\n // then copy construct all the new ones (and we've confirmed\n // that this can't throw).\n assign(other.cbegin(), other.cend());\n }\n else\n {\n auto temp = other;\n swap(temp);\n }\n \n return *this;\n}\n</code></pre>\n<p>If you don’t have to worry about allocators, this can be a <em>much</em> more efficient pattern if, for example, you’re copying a million <code>int</code>s over a vector that already held a million <code>int</code>s.</p>\n<p>Buuuut we do have to worry about allocators…</p>\n<p>… or do we?</p>\n<p>First let’s fix what we already have, assuming we <em>don’t</em> need to copy the allocator from <code>other</code>. The first branch of that <code>if</code> is fine. The <code>else</code> branch, however, has a problem, because when <code>temp</code> is constructed, it is constructed with a copy of <code>other.allocator_</code>. That’s not what we want; we want a copy of <code>this-&gt;allocator_</code>. So at the very least you’d need:</p>\n<pre><code> else\n {\n auto temp = vector(other, allocator_);\n swap(temp);\n }\n</code></pre>\n<p>But even that’s problematic, because allocator copying and swapping and so on… it’s a goddam mess that you’d be better off avoiding.</p>\n<p>A better strategy is simply to use <code>this-&gt;allocator_</code> to allocate the memory you directly, copy into it, and then just swap the <code>data_</code> pointer. Assuming you’ve got a <code>std::unique_ptr</code>-like-type for allocators called <code>allocator_ptr</code> type—which is trivial to make—you could do something like:</p>\n<pre><code> else\n {\n // Maintain the existing capacity.\n auto const new_capacity = std::max(capacity_, other.size());\n \n // Internally calls std::allocator_traits&lt;Alloc&gt;::allocate()\n // with the given args to allocate the memory.\n auto p = allocator_ptr&lt;Alloc&gt;{\n allocator_,\n new_capacity,\n data_ // try for locality if possible\n };\n \n // Do the copy.\n std::uninitialized_copy(other.cbegin(), other.cend(), p.get());\n \n // Swap the pointers.\n auto old_p = data_;\n data_ = p.release();\n p.reset(old_p);\n \n // Clean up old data.\n for (auto p = old_p; p &lt; (old_p + size_); ++p)\n std::allocator_traits&lt;Alloc&gt;::destroy(allocator_, p);\n \n // Make sure the other members are kosher.\n size_ = other.size();\n capacity_ = new_capacity;\n \n // And we're done. Old data will be automatically freed.\n }\n</code></pre>\n<p>But I note that all of the above is simply <code>assign(other.cbegin(), other.cend())</code>… assuming <code>assign()</code> is exception-safe (the current one isn’t).</p>\n<p>So if you <em>don’t</em> need to propagate the allocator, all you need is the code above (which is ultimately just <code>assign(other.cbegin(), other.cend())</code>). But what if you do? First, you should check to see if you do:</p>\n<pre><code>constexpr auto operator=(vector const&amp; other) -&gt; vector&amp;\n{\n if constexpr (std::allocator_traits&lt;Alloc&gt;::propagate_on_container_copy_assignment)\n {\n // ...\n }\n else // no need to propagate the allocator\n {\n assign(other.begin(), other.end());\n }\n \n return *this;\n}\n</code></pre>\n<p>Now you can just copy the allocator, use it to allocate new memory, and copy the contents of <code>other</code> into it, using exactly the same pattern that was used above (except the allocator has to be transferred as well):</p>\n<pre><code>constexpr auto operator=(vector const&amp; other) -&gt; vector&amp;\n{\n if constexpr (std::allocator_traits&lt;Alloc&gt;::propagate_on_container_copy_assignment)\n {\n auto alloc = other.allocator_;\n \n // Maintain the existing capacity.\n auto const new_capacity = std::max(capacity_, other.size());\n \n // Internally calls std::allocator_traits&lt;Alloc&gt;::allocate()\n // with the given args to allocate the memory.\n auto p = allocator_ptr&lt;Alloc&gt;{\n alloc,\n new_capacity,\n data_ // try for locality if possible\n };\n \n // Do the copy.\n std::uninitialized_copy(other.cbegin(), other.cend(), p.get());\n \n // Swap the pointers.\n auto old_p = data_;\n data_ = p.release();\n p.reset(old_p);\n \n // Clean up old data.\n for (auto p = old_p; p &lt; (old_p + size_); ++p)\n std::allocator_traits&lt;Alloc&gt;::destroy(allocator_, p);\n \n // Make sure the other members are kosher.\n size_ = other.size();\n capacity_ = new_capacity;\n \n // And of course, the allocator.\n allocator_ = std::move(alloc);\n \n // And we're done. Old memory will be automatically freed.\n }\n else // no need to propagate the allocator\n {\n assign(other.begin(), other.end());\n }\n \n return *this;\n}\n</code></pre>\n<p>And that’ll work just fine.</p>\n<p><em>BUT!</em> You can do even better! You can test if <code>alloc</code> and <code>this-&gt;allocator_</code> are equal <em>and</em> <code>T</code> objects are no-throw copyable <em>and</em> <code>other.size() &lt; capacity_</code>. If all those things are true, you don’t need to allocate new memory… you can simply overwrite what’s in <code>data_</code> (and of course, don’t forget to copy <code>alloc</code>). I’ll leave that for you to figure out.</p>\n<pre><code>constexpr void reserve(const size_type &amp;size) {\n if (size &lt; capacity_) return;\n reallocate(size);\n}\n</code></pre>\n<p>This function isn’t <em>wrong</em>, but its structure is a little bizarre. The <code>return</code> is hidden off to the right, so it’s easy to miss, leading one to misread the function logic. In fact, I think the logic might actually be wrong—do you really want to call <code>reallocate()</code> if <code>size == capacity_</code>?</p>\n<p>It just seems much more straightforward to do things the other way around:</p>\n<pre><code>constexpr void reserve(size_type size) {\n if (size &gt; capacity_)\n reallocate(size);\n}\n</code></pre>\n<p>(That also presumes you don’t want to reallocate if the requested size equals the existing capacity.)</p>\n<pre><code>constexpr void shrink_to_fit() {\n reallocate(0);\n capacity_ = 0;\n}\n</code></pre>\n<p>This… seems wrong.</p>\n<p>If I’m reading the code right, then <code>reallocate(0)</code> will simply reallocate the existing capacity. But that’s not the point of <code>shrink_to_fit()</code>. In fact, it seems completely pointless to just reallocate the existing buffer at the exact same size.</p>\n<p>What <code>shrink_to_fit()</code> <em>should</em> do is reallocate the buffer <em>if</em> the capacity doesn’t equal the size. And in that case, it should allocate a buffer where the capacity does equal the size. You can’t do that with your existing interface for <code>reallocate()</code>, because <code>reallocate()</code> will never allocate less than the current capacity.</p>\n<p>And setting <code>capacity_</code> to zero? Why? That just seems <em>completely</em> wrong.</p>\n<p>What you want seems something more like:</p>\n<pre><code>constexpr void shrink_to_fit() {\n if (size_ != capacity_)\n {\n auto p = allocator_ptr{allocator_, size_};\n // or allocator_ptr{allocator_, size_, data_}; for locality\n \n std::unitialized_copy_n(data_, size_, p.get());\n \n auto old_p = data_;\n data_ = p.release();\n p.reset(old_p);\n for (auto p = old_p; p &lt; (old_p + size_); ++p)\n std::allocator_traits&lt;Alloc&gt;::destroy(allocator_, p);\n \n capacity_ = size_;\n }\n}\n</code></pre>\n<p>And because <code>shrink_to_fit()</code> is non-binding, you could also use a more intelligent heuristic to decide whether or not to actually reallocate. Like, only reallocate if the current capacity is greater than 1.5 times the size; otherwise ignore the request. That’s up to you.</p>\n<pre><code>template&lt;typename... Args&gt;\nconstexpr void push_back(Args &amp;&amp;... args) { (push_back(std::forward&lt;Args&gt;(args)), ...); }\n</code></pre>\n<p>I’m not sure this is a wise interface choice, given the similarity between <code>push_back()</code> and <code>emplace_back()</code>. For example, suppose you have a type that is constructible from either a single <code>int</code> or a number of <code>int</code>s:</p>\n<pre><code>// These both do the same thing:\nv.push_back(0);\nv.emplace_back(0);\n\n// These do very different things:\nv.push_back(0, 1, 2);\nv.emplace_back(0, 1, 2);\n</code></pre>\n<p>But a careless code maintainer might be following the rule-of-thumb to replace <code>push_back()</code> with <code>emplace_back()</code>. The new code will compile without any warnings, but behave differently.</p>\n<p>I’d also take careful consideration of whether <code>push_back()</code> is allowed to take zero arguments. Does <code>vec.push_back();</code> makes sense? Bear in mind:</p>\n<pre><code>// These do very different things:\nv.push_back();\nv.emplace_back();\n</code></pre>\n<p>Now, a function that appends a number of items isn’t a bad idea. I just don’t think <code>push_back()</code> is a good name, given its symmetry with <code>emplace_back()</code>. Perhaps <code>push_back_n()</code>? In any case, if you’re going to do it, I suggest reserving <code>size_ + sizeof...(Args)</code>.</p>\n<pre><code>template&lt;typename... Args&gt;\nconstexpr void emplace_back(Args &amp;&amp;... args) {\n\n// ...\n\ntemplate&lt;typename... Args&gt;\nconstexpr void emplace(iterator pos, Args &amp;&amp;... args) {\n</code></pre>\n<p>Just FYI, <code>emplace()</code> and <code>emplace_back()</code> return references to the emplaced object, which is <em>really</em> handy for <code>emplace()</code> especially, because you can do <code>auto&amp;&amp; x = v.emplace(/* ... */);</code> and then play with the emplace-constructed <code>x</code>.</p>\n<pre><code>constexpr void swap(vector &amp;other) {\n std::swap(other.data_, data_);\n std::swap(other.size_, size_);\n std::swap(other.capacity_, capacity_);\n}\n</code></pre>\n<p>Ah, here we go again with allocators.</p>\n<p>So the code above is fine <em>if</em> you don’t need to propagate the allocator on swap <em>and</em> the two allocators are equal. If you need to propagate the allocator, well then, you need to propagate the allocator. If the two allocators aren’t equal, then you can’t use allocator 1 to deallocate the stuff allocated by allocator 2. And logically, if you’re not supposed to swap the allocators, then you can’t swap the pointers if the allocators are not equal. In fact, <a href=\"https://en.cppreference.com/w/cpp/container/vector/swap\" rel=\"nofollow noreferrer\">the standard vector says if the allocators are not equal, then swapping is UB</a>.</p>\n<p>So here’s what the standard actually asks of vector’s swap, as of C++17 (well, with <code>constexpr</code> from C++20 added):</p>\n<pre><code>constexpr void swap(vector&amp; other)\n noexcept(std::allocator_traits&lt;Alloc&gt;::propagate_on_container_swap::value\n || std::allocator_traits&lt;Alloc&gt;::is_always_equal::value)\n{\n using std::swap;\n \n if constexpr (std::allocator_traits&lt;Alloc&gt;::propagate_on_container_swap)\n {\n swap(allocator_, other._allocator);\n }\n else if constexpr (not std::allocator_traits&lt;Alloc&gt;::is_always_equal)\n {\n assert(allocator_ == other.allocator_);\n }\n \n swap(data_, other.data_);\n swap(size_, other.size_);\n swap(capacity_, other.capacity_);\n}\n</code></pre>\n<p>You don’t actually need the assert if you’re okay with just allowing UB. Or maybe you could just have it assert in debug mode or something.</p>\n<pre><code>constexpr void assign(size_type count, const T &amp;value) {\n if (count &gt; size_) { resize(count); } //resize if necessary\n std::fill(begin(), end(), value); // fill array\n}\n</code></pre>\n<p>This… seems a little dodgy. I’m all for code reuse, but what this function is actually doing is not what it advertises. First it resizes the internal buffer… except, no, that’s not <em>all</em> it does; it resizes the internal buffer and <em>possibly fills it out by default-constructing a bunch of <code>T</code>s</em>. That will “work” assuming two things:</p>\n<ol>\n<li><code>T</code>’s default constructor and copy constructor have no observable side effects; and</li>\n<li><code>T</code> actually has a default constructor.</li>\n</ol>\n<p>One of the reasons I use the <code>assign(n, t)</code> function in vectors is specifically for types that don’t have a default constructor. But that won’t work with this vector.</p>\n<p>The other issue here is exception safety. What happens if one of the copy constructors throws? Your vector will be in an unknown (though valid) state.</p>\n<p>I’m afraid you’re going to need to rethink this. It’s a lot more complicated at first glance:</p>\n<ol>\n<li>If the capacity is less than <code>count</code>, you need to allocate a new buffer. No problem: allocate, then <code>std::uninitialized_fill_n()</code>, then swap the newly allocated buffer with the old one and clean up the old stuff. This can all be done exception-safe. Job done.</li>\n<li>Otherwise, if capacity is greater than or equal to <code>count</code> <em>AND</em> copy construction and assignment are non-throwing, you can assign-in-place safely, but it’s potentially a multi-stage job.\na. First you can use <code>std::fill(begin(), end(), value)</code> to overwrite the existing elements, if any.\nb. Then you can use <code>std::uninitialized_fill(end(), begin() + count, value)</code> to initialize the remaining elements, if any.\nc. Then just set <code>size_</code> to <code>count</code> and you’re done.</li>\n</ol>\n<p>Though I’d recommend against using <code>std::fill()</code> specifically, because that would require including <code>&lt;algorithm&gt;</code>… and <code>&lt;algorithm&gt;</code> is a heavyweight header.</p>\n<pre><code>constexpr void assign(iterator first, iterator last) {\n clear();\n insert(begin(), first, last);\n}\n</code></pre>\n<p>This is a rather destructive <code>assign()</code>, that doesn’t offer the strong exception guarantee. I also think you’ve got the interface wrong.</p>\n<p>For starters, I think this should actually be a function template that takes two <code>Iterator</code> arguments… not a non-template that takes two <code>turtle::vector&lt;T&gt;::iterator</code> arguments. Right now, this function can only assign from another <code>turtle::vector&lt;T&gt;</code> (note: not even a <code>const</code> one, either, because it takes non-<code>const</code> iterators).</p>\n<p>So I think you want:</p>\n<pre><code>template &lt;typename InputIterator&gt;\nconstexpr void assign(InputIterator first, InputIterator last) {\n // ...\n</code></pre>\n<p>(or, using future-style iteration…)</p>\n<pre><code>template &lt;typename InputIterator, typename Sentinel&gt;\nconstexpr void assign(InputIterator first, Sentinel last) {\n // ...\n</code></pre>\n<p>(but let’s ignore future-style iteration for now)</p>\n<p>Now if the iterator category really is <code>InputIterator</code>… then yeah, all you can do is <code>clear()</code> and <code>insert()</code>.</p>\n<p><em>However!</em> If the iterator category is <code>ForwardIterator</code> or better… then you can be smarter. You can first determine the size, and if copy construction/assignment is non-throwing, and potentially assign right into the existing buffer. Even if you <em>can’t</em> assign into the existing buffer, knowing the size lets you allocate a properly-sized buffer and then you can <code>std::uninitialized_fill()</code> right into that.</p>\n<p>And for the next function, this is definitely the case…:</p>\n<pre><code>constexpr void assign(const std::initializer_list&lt;T&gt; &amp;list) {\n clear();\n insert(begin(), list); //insert list\n}\n</code></pre>\n<p>… because you know for a fact that <code>std::initializer_list</code>’s iterators are random access. (Plus, <code>std::initializer_list</code> has a <code>size()</code> function.) If the iterator version of <code>assign()</code> is done properly, then this could just be:</p>\n<pre><code>constexpr void assign(std::initializer_list&lt;T&gt; list) {\n assign(list.begin(), list.end());\n}\n</code></pre>\n<p>(Incidentally, you should never need to pass <code>std::initializer_list</code> around by <code>const&amp;</code>. It’s like <code>std::string_view</code> or <code>std::span</code> in that it’s designed to be passed around by-value.)</p>\n<pre><code>constexpr reference operator[](const size_type &amp;index) noexcept { return *std::launder(begin() + index); }\n\nconstexpr const_reference operator[](const size_type &amp;index) const noexcept {\n return *std::launder(begin() + index);\n}\n</code></pre>\n<p>Why are you using <code>std::launder()</code> here? You’re not doing any type-punning or other mischief so far as I can see.</p>\n<pre><code>constexpr reference at(const size_type &amp;index) { return (*this)[index]; }\n\nconstexpr const_reference at(const size_type &amp;index) const { return (*this)[index]; }\n</code></pre>\n<p>You’re kinda missing the whole point of <code>at()</code> here, which is to throw <code>std::out_of_range</code> if <code>index</code> is greater than or equal to <code>size()</code>.</p>\n<p>Also, there’s no point in taking <code>size_type</code> by <code>const&amp;</code> (or returning it by <code>const&amp;</code>, as you do in some other functions). By definition <code>size_type</code> <em>must</em> be an unsigned integer type. You gain nothing by working with references to it (and probably lose out because it’s harder to optimize).</p>\n<pre><code>constexpr const_reference back() const { return *cend(); }\n</code></pre>\n<p>You got a little bug here, because <code>cend()</code> points to one-past-the-last-element… not the last element.</p>\n<pre><code>constexpr iterator T_fill_insert(difference_type offset, size_type n, const T &amp;x) {\n T_grow(size_ + n);\n size_ += n;\n iterator pos = begin() + offset;\n std::uninitialized_move(pos, end() - n, pos + n);\n std::uninitialized_fill(pos, pos + n, x); // fill\n return pos;\n}\n</code></pre>\n<p>There are some problems here due to being sloppy about keeping track of when you can just move or fill, and when you need to do an <em>uninitialized</em> move or fill. There are multiple possibilities here:</p>\n<ol>\n<li>All new elements are overwriting existing elements; all moved elements are going into uninitialized space.</li>\n<li>All new elements are overwriting existing elements; some moved elements are overwriting existing elements, others are going into uninitialized space.</li>\n<li>Some new elements are overwriting existing elements, others are going into uninitialized space; all moved elements are going in uninitialized space.</li>\n<li>All new elements are going into uninitialized space (no moved elements; this would be a pure append).</li>\n</ol>\n<p>You also need to take exception safety into account.</p>\n<p>If you need to reallocate, then things are easy: just uninitialized copy the before and after elements, and uninitialized fill the space between. (But do keep exception safety in mind!)</p>\n<p>But if moves are non-throwing, and your capacity is enough, then you can move and fill in-place, even if copy assignment might throw. (If a copy does throw, then just “un-move” what you moved at the beginning.)</p>\n<pre><code>constexpr iterator T_insert(difference_type offset, const T &amp;x) {\n</code></pre>\n<p>To help you simplify things, note that this is just <code>T_fill_insert(offset, 1, x)</code>.</p>\n<pre><code>template&lt;typename InputIterator&gt;\nconstexpr void T_fill_range(difference_type offset, InputIterator first, InputIterator last) {\n difference_type n = helper::distance(first, last);\n iterator pos;\n T_grow(size_ + n);\n size_ += n;\n pos = begin() + offset;\n std::uninitialized_move(pos, end() - n, pos + n);\n std::uninitialized_copy(first, last, pos);\n}\n</code></pre>\n<p>If you tried this function with an <em>actual</em> <code>InputIterator</code>, you’d be in for a rude surprise.</p>\n<p>First of all, it won’t compile, because <code>helper::distance()</code> will only work with random access iterators or better. Only random access iterators or better support <code>operator-()</code>.</p>\n<p>But even if you fixed <code>helper::distance()</code> (or, better, used <code>std::distance()</code> instead), while this would now compile, it still won’t work. That’s because input iterators only allow a single pass. Once you’ve done <code>distance()</code>, you’ve burned up your single use. So the call to <code>std::uninitialized_copy()</code> at the end will copy nothing.</p>\n<p>What you need here is <em>two</em> functions—or a single function with two implementations via <code>if constexpr</code>.</p>\n<p>For input iterators… there’s simply no option other than doing a <code>for</code> loop inserting elements one at a time. This isn’t <em>so</em> bad because you’ll either have enough capacity to avoid a reallocation, or you’ll grow by your growth factor, so you won’t be reallocating on <em>every</em> iteration of the <em>for</em> loop.</p>\n<p>For forward iterators or better… well <em>now</em> you can use <code>distance()</code>, then pre-allocate if necessary, and so on. From that point, you just need to take the usual precautions regarding exception safety (that is, either using a whole new buffer, or—if moves are non-throwing—possibly trying to do the fill in-place).</p>\n<pre><code>constexpr void reallocate(const size_type &amp;newSize) {\n if (!data_) {\n data_ = allocator_.allocate(newSize);\n capacity_ = newSize;\n } else {\n T *temp = allocator_.allocate(newSize &gt; capacity_ ? newSize : capacity_);\n std::uninitialized_move(data_, data_ + capacity_, temp);\n T_destroy(begin(), end());\n allocator_.deallocate(data_, capacity_);\n data_ = temp;\n capacity_ = newSize &gt; capacity_ ? newSize : capacity_;\n }\n}\n</code></pre>\n<p>The first part of this function is fine.</p>\n<p>The second part is fine <em>if</em> moves are non-throwing. If moves can throw, you have to do copies instead. (Fun fact: there’s actually a function called <code>std::move_if_noexcept()</code> that was created specifically for this problem… that, hilariously, is actually useless in practice because you’re usually moving/copying into uninitialized memory, as you are here.)</p>\n<p>Luckily, the fix here is trivial:</p>\n<pre><code>constexpr void reallocate(size_type newSize)\n{\n if (!data_)\n {\n data_ = std::allocator_traits&lt;Alloc&gt;::allocate(allocator_, newSize);\n capacity_ = newSize;\n }\n else\n {\n auto const newCapacity = newSize &gt; capacity_ ? newSize : capacity_; // DRY\n \n auto temp = std::allocator_traits&lt;Alloc&gt;::allocate(allocator_, newCapacity); // possibly with _data as hint for locality\n if constexpr (std::is_nothrow_move_constructible_v&lt;T&gt;)\n {\n std::uninitialized_move_n(std::to_address(data_), size_, std::to_address(temp));\n }\n else\n {\n try\n {\n std::uninitialized_copy_n(std::to_address(data_), size_, std::to_address(temp));\n }\n catch (...)\n {\n std::allocator_traits&lt;Alloc&gt;::deallocate(allocator_, temp, newCapacity);\n throw;\n }\n }\n \n T_destroy(begin(), end());\n std::allocator_traits&lt;Alloc&gt;::deallocate(allocator_, data_, capacity_);\n \n data_ = temp;\n capacity_ = newCapacity;\n }\n}\n</code></pre>\n<p>Finally, your data members:</p>\n<pre><code>T *data_ = nullptr;\nsize_type size_ = 0;\nsize_type capacity_ = 0;\nallocator_type allocator_;\n</code></pre>\n<p><code>data_</code> should really be <code>pointer</code>, not <code>T*</code>.</p>\n<p>As for <code>allocator_</code>… the thing is that allocators quite often are empty. However, if you include an allocator data member like this, then it takes up space in your class even though it doesn’t need to. In C++20, you can use <code>[[no_unique_address]]</code>. Prior to that, you’d use <a href=\"https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Empty_Base_Optimization\" rel=\"nofollow noreferrer\">the empty base optimization trick</a>. Frankly, I’d suggest not bothering with EBO; it’s going to be obsolete in a few months.</p>\n<p>I think that’s it!</p>\n<h1>Summary</h1>\n<p>There are only a very small number of critical bugs in the code:</p>\n<ul>\n<li>Your custom <code>helper::distance()</code> function only supports random access iterators, though you use it for other iterator categories.</li>\n<li>In a couple places, you copy/move pointers without copying the allocators as well. This could cause a situation where you’re deallocating memory with the wrong allocator.</li>\n<li>In <code>shrink_to_fit()</code> you set the capacity to zero… which is almost sure to lead to crashes and/or leaks.</li>\n<li>In the <code>const</code> version of <code>back()</code>, you dereference past-the-end.</li>\n</ul>\n<p>There are a few potential problems that aren’t <em>necessarily</em> bugs (though could become bugs depending on your intended usage):</p>\n<ul>\n<li>There are a few places where exception safety doesn’t even meet the minimal weak guarantee (where an exception will not only leave the object in an unknown state, it will almost certanly lead to UB).</li>\n<li>There are a few places where you don’t keep track of which parts of your memory are initialized and which are not, and possibly use the wrong type of algorithm.</li>\n<li>There are a few places where you seem to intend to use iterator categories your code doesn’t actually support (for example, making multiple passes through what are supposed to be input iterators).</li>\n<li>There are a few functions that don’t offer the same guarantees as the <code>std::vector</code> versions, like where <code>std::vector</code> promises they will work even with non-default constructible types, but your versions do default constructions.</li>\n</ul>\n<p>Other than that, the only issues worth mentioning are:</p>\n<ul>\n<li>some efficiency gains that could be achieved, for example, by taking advantage cases where you can reuse existing capacity; and</li>\n<li>some correctness issues regarding the use of allocators (mostly revolving around using uninitialized memory algorithms that don’t use the allocator’s <code>construct()</code> or <code>destroy()</code> functions.</li>\n</ul>\n<p>And for style issues:</p>\n<ul>\n<li>lack of comments; and</li>\n<li>unnecessary use of <code>const&amp;</code> for simple types.</li>\n</ul>\n<p>Almost all of the issues are <em>really</em> complex, low-level-detail stuff. Overall, if I were grading this, I’d give it an “A”.</p>\n<h1>Extended answer</h1>\n<pre><code>constexpr iterator T_fill_insert(difference_type offset, size_type n, const T &amp;x) {\n const auto old_size = size_;\n /* check if reallocation is needed */\n T_grow(size_ + n);\n size_ += n;\n /* get the iterator at offset */\n iterator pos = begin() + offset;\n /* we can move already initialized parts of memory\n * that we can move */\n std::move(pos,begin()+old_size-n,pos+n);\n std::uninitialized_move(pos+old_size-n, end(), end()-n);\n std::uninitialized_fill(pos, pos + n, x);\n return pos;\n}\n</code></pre>\n<p>Alright, let’s logic through this together to see if it works. (I honestly don’t know if it does yet! I’m working through it as I write.)</p>\n<p>Let’s skip over the reallocation part, on the assumption that it works fine, and start our reasoning on the line where <code>pos</code> is initialized. Let’s assume the size is 10, containing the digits ‘0’, ‘1’, ‘2’, …. The capacity is 16. We want to insert 3 ‘X’s starting at position 5.</p>\n<p>So at the start, the vector’s contents are:</p>\n<pre><code>0 1 2 3 4 5 6 7 8 9 _ _ _ _ _ _\n ^\n | insert position\n</code></pre>\n<p>Where the underscores represent uninitialized memory.</p>\n<p>So <code>offset</code> is 5, and <code>pos</code> points to the position shown.</p>\n<p>This is the before and after states we want:</p>\n<pre><code>start:\n0 1 2 3 4 5 6 7 8 9 _ _ _ _ _ _\n\nfinal:\n0 1 2 3 4 X X X 5 6 7 8 9 _ _ _\n ~ ~ + + +\n</code></pre>\n<p>Note that two of the elements (5 and 6) are moved onto already initialized memory, while three (7, 8, and 9) are moved onto uninitialized memory. In this case, all three new elements are copied over already initialized elements (but that won’t always be true!).</p>\n<p>The first operation moves everything from <code>pos</code> to the end over to <code>pos+n</code>:</p>\n<pre><code>start:\n0 1 2 3 4 5 6 7 8 9 _ _ _ _ _ _\n\nstd::move(pos,begin()+old_size-n,pos+n):\n0 1 2 3 4 ? ? 7 5 6 _ _ _ _ _ _\n\nfinal:\n0 1 2 3 4 X X X 5 6 7 8 9 _ _ _\n</code></pre>\n<p>(The question mark means a valid but moved-from value.)</p>\n<p>Already you can see a problem. You’ve completely lost 8 and 9. Your steps are out of order. You should have done the following uninitialized move first.</p>\n<p>Let’s try that—let’s swap those two lines (and fix the last argument to <code>std::uninitialized_move()</code>, because it’s exactly the same as the first one, meaning the function ultimately does nothing—it moves from <code>pos+size-n</code> to <code>pos+size-n</code>) and keep going:</p>\n<pre><code>start:\n0 1 2 3 4 5 6 7 8 9 _ _ _ _ _ _\n\nstd::uninitialized_move(pos+old_size-n, end(), end()):\n0 1 2 3 4 5 6 ? ? ? 7 8 9 _ _ _\n\nstd::move(pos,begin()+old_size-n,pos+n):\n0 1 2 3 4 ? ? ? 5 6 7 8 9 _ _ _\n\nfinal:\n0 1 2 3 4 X X X 5 6 7 8 9 _ _ _\n</code></pre>\n<p>So far, so good. Ah, but the next step should be a fill… not an <em>uninitialized</em> fill.</p>\n<p>Okay, let’s try replacing it with a normal fill:</p>\n<pre><code>start:\n0 1 2 3 4 5 6 7 8 9 _ _ _ _ _ _\n\nstd::uninitialized_move(pos+old_size-n, end(), end()):\n0 1 2 3 4 5 6 ? ? ? 7 8 9 _ _ _\n\nstd::move(pos,begin()+old_size-n,pos+n):\n0 1 2 3 4 ? ? ? 5 6 7 8 9 _ _ _\n\nstd::fill(pos, pos + n, x):\n0 1 2 3 4 X X X 5 6 7 8 9 _ _ _\n\nfinal:\n0 1 2 3 4 X X X 5 6 7 8 9 _ _ _\n</code></pre>\n<p>Perfect.</p>\n<p>But… does it always work? Let’s try adding 6 elements instead of 3:</p>\n<pre><code>start:\n0 1 2 3 4 5 6 7 8 9 _ _ _ _ _ _\n\nstd::uninitialized_move(pos+old_size-n, end(), end()):\n0 1 2 3 ? ? ? ? ? ? 4 5 6 7 8 9\n\n// nope (note the 4 was moved) ...\n\nfinal:\n0 1 2 3 4 X X X X X X 5 6 7 8 9\n</code></pre>\n<p>Looks like it’s back to the drawing board. Like I said, this is really a <em>lot</em> more complicated than it looks at first.</p>\n<p>I always tell people I teach programming to that 95% of programming is done before you hit the first keystroke. You can always tell a good programmer from a bad programmer by, ironically, noting who <em>doesn’t</em> start programming right away. It’s all about understanding the problem, the algorithm, and the tools you’re using to implement it. If you start coding before you’ve <em>completely</em> worked through those things, then your code is already broken. If it even works at all, that’s just a fluke.</p>\n<p>My advice is to sit down and work through pictorial representations like the ones above, and try to suss out all the possible cases—What if <code>n</code> is greater than <code>size</code>, for example? Then what would <code>pos+old_size-n</code> do? Crash!</p>\n<p>Then try to determine a set of general rules that work for all cases. That might not even be possible! You might need to use <code>if</code> branches to handle different cases. I honestly don’t know what the solution is; I’d have to do exactly what I’m recommending to you, and sit down and work it through.</p>\n<p>Or, alternately, rather than that method, you may prefer to try to think conceptually about the required steps first, and <em>then</em> try the pictorial representations to test your ideas. Either way is fine; it just boils down to your style.</p>\n<p>But the bottom line is that you shouldn’t even <em>try</em> writing a single line of code until you understand the problem, and the solution, however you choose to do that. Seat-of-your-pants coding can be fun sometimes, but it’s not a serious way to write real code.</p>\n<p>And write tests! I even recommend writing the tests <em>before you write the code</em>! You could make a simple test type that can detect when it hasn’t been initialized (for example, in the constructor, record its address in a static list, and if you’re trying to move-assign over an object whose address isn’t in the list, you’ve detected a bug), and use that in your vector. You could test inserts at the beginning, middle, and end of a 10 element vector, with insert sizes from 1 to 12. Test! Test! Test! Code without tests is just garbage—just throwaway crap you might have fun playing with for a while, but can’t use in serious projects. Pick a test library—I like <a href=\"https://www.boost.org/doc/libs/release/libs/test/doc/html/index.html\" rel=\"nofollow noreferrer\">Boost.Test</a>, but something simpler like <a href=\"https://github.com/catchorg/Catch2\" rel=\"nofollow noreferrer\">Catch2</a> is also great; you can even use <a href=\"https://github.com/google/googletest\" rel=\"nofollow noreferrer\">Google Test</a> if you’re masochistic, I suppose. (Actually, Catch2’s tutorial even shows some basic testing of <code>std::vector</code>.) I’d even argue that being able to write good tests is a more important skill than being able to just code from the hip.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T19:39:54.443", "Id": "480984", "Score": "0", "body": "Thanks for the feedback, but I have a question how much better would this be than the current T_fill_insert function https://pastebin.com/Bj6jptDv." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-07T12:01:56.250", "Id": "481340", "Score": "0", "body": "I'll have to extend the answer a bit for that, because it's a bit too much work out in a comment, so check above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-07T11:18:27.643", "Id": "484742", "Score": "0", "body": "I read only half of this answer and I'm already scared >_>" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T17:27:47.380", "Id": "244961", "ParentId": "244787", "Score": "8" } } ]
{ "AcceptedAnswerId": "244961", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T13:58:03.017", "Id": "244787", "Score": "5", "Tags": [ "c++", "reinventing-the-wheel" ], "Title": "std::vector remake" }
244787
<p>File <code>fibonacci.aec</code>:</p> <pre><code>syntax GAS ;We are, of course, targeting GNU Assembler here, rather than FlatAssembler, to be compatible with GCC. verboseMode on ;Tells ArithmeticExpressionCompiler to output more comments into the assembly code it produces (fibonacci.s). AsmStart .global fibonacci #We need to tell the linker that &quot;fibonacci&quot; is the name of a function, and not some random label. fibonacci: AsmEnd If not(mod(n,1)=0) ;If 'n' is not a integer, round it to the nearest integer. n := n + ( mod(n,1) &gt; 1/2 ? 1-mod(n,1) : (-mod(n,1))) EndIf If n&lt;2 ;The 1st Fibonacci number is 1, and the 0th one is 0. returnValue := n &gt; -1 ? n : 0/0 ;0/0 is NaN (indicating error), because negative Fibonacci numbers don't exist AsmStart .intel_syntax noprefix ret #Far return (to the other section, that is, to the C++ program). The way to do a same-section return depends on whether we are in a 32-bit Assembler or a 64-bit Assembler, while the far return is the same (at least in the &quot;intel_syntax mode&quot;). .att_syntax AsmEnd ElseIf not(memoisation[n]=0) ;Has that Fibonacci number already been calculated? returnValue:=memoisation[n] AsmStart .intel_syntax noprefix ret .att_syntax AsmEnd EndIf ;And now comes the part where we are tricking ArithmeticExpressionCompiler into supporting recursion... topOfTheStackWithLocalVariables := topOfTheStackWithLocalVariables + 2 ;Allocate space on the stack for 2 local variables ('n', the argument passed to the function, and the temporary result). temporaryResult := 0 ;The sum of fib(n-1) and fib(n-2) will be stored here, first 0 then fib(n-1) then fib(n-1)+fib(n-2). stackWithLocalVariables[topOfTheStackWithLocalVariables - 1] := temporaryResult ;Save the local variables onto the stack, for the recursive calls will corrupt them (as they are actually global variables, because ArithmeticExpressionCompiler doesn't support local ones). stackWithLocalVariables[topOfTheStackWithLocalVariables] := n n:=n-1 AsmStart .intel_syntax noprefix call fibonacci .att_syntax AsmEnd temporaryResult := stackWithLocalVariables[topOfTheStackWithLocalVariables - 1] temporaryResult := temporaryResult + returnValue ;&quot;returnValue&quot; is supposed to contain fib(n-1). ;And we repeat what we did the last time, now with n-2 instead of n-1... stackWithLocalVariables[topOfTheStackWithLocalVariables - 1] := temporaryResult n := stackWithLocalVariables[topOfTheStackWithLocalVariables] n := n - 2 AsmStart .intel_syntax noprefix call fibonacci .att_syntax AsmEnd temporaryResult := stackWithLocalVariables[topOfTheStackWithLocalVariables - 1] temporaryResult := temporaryResult + returnValue stackWithLocalVariables[topOfTheStackWithLocalVariables - 1] := temporaryResult n := stackWithLocalVariables [topOfTheStackWithLocalVariables] returnValue := temporaryResult memoisation[n] := returnValue topOfTheStackWithLocalVariables := topOfTheStackWithLocalVariables - 2 AsmStart .intel_syntax noprefix ret .att_syntax AsmEnd </code></pre> <p>File <code>let_gcc_setup_gas.cpp</code>:</p> <pre><code>/*The C++ wrapper around &quot;fibonacci.aec&quot;. Compile this as: node aec fibonacci.aec #Assuming you've downloaded aec.js from the releases. g++ -o fibonacci let_gcc_setup_gas.cpp fibonacci.s */ #include &lt;algorithm&gt; //The &quot;fill&quot; function. #include &lt;cmath&gt; //The &quot;isnan&quot; function. #include &lt;iostream&gt; #ifdef _WIN32 #include &lt;cstdlib&gt; //system(&quot;PAUSE&quot;); #endif extern &quot;C&quot; { // To the GNU Linker (which comes with Linux and is used by GCC), // AEC language is a dialect of C, and AEC is a C compiler. float n, stackWithLocalVariables[1024], memoisation[1024], topOfTheStackWithLocalVariables, temporaryResult, returnValue, result; // When using GCC, there is no need to declare variables in the same // file as you will be using them, or even in the same language. So, // no need to look up the hard-to-find information about how to // declare variables in GNU Assembler while targeting 64-bit Linux. // GCC and GNU Linker will take care of that. void fibonacci(); // The &quot;.global fibonacci&quot; from inline assembly in // &quot;fibonacci.aec&quot; (you need to declare it, so that the C++ // compiler doesn't complain: C++ isn't like JavaScript or AEC // in that regard, C++ tries to catch errors such as a // mistyped function or variable name in compile-time). } int main() { std::cout &lt;&lt; &quot;Enter n:&quot; &lt;&lt; std::endl; std::cin &gt;&gt; n; topOfTheStackWithLocalVariables = -1; if (n &gt;= 2) std::fill(&amp;memoisation[0], &amp;memoisation[int(n)], 0); // This is way more easily done in C++ than in AEC here, // because the AEC subprogram doesn't know if it's being // called by C++ or recursively by itself. fibonacci(); if (std::isnan(returnValue)) { std::cerr &lt;&lt; &quot;The AEC program returned an invalid decimal number.&quot; &lt;&lt; std::endl; return 1; } std::cout &lt;&lt; &quot;The &quot; &lt;&lt; n &lt;&lt; ((int(n) % 10 == 3) ? (&quot;rd&quot;) : (int(n) % 10 == 2) ? (&quot;nd&quot;) : (int(n) % 10 == 1) ? (&quot;st&quot;) : &quot;th&quot;) &lt;&lt; &quot; Fibonacci number is &quot; &lt;&lt; returnValue &lt;&lt; &quot;.&quot; &lt;&lt; std::endl; #ifdef _WIN32 std::system(&quot;PAUSE&quot;); #endif return 0; } </code></pre> <p>The executable files for Windows and Linux are available <a href="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/blob/master/recursive_Fibonacci/executablesOfRecursiveFibonacci.zip?raw=true" rel="nofollow noreferrer">here</a>, and the assembly code that my compiler for AEC generates is available <a href="https://raw.githubusercontent.com/FlatAssembler/ArithmeticExpressionCompiler/master/recursive_Fibonacci/fibonacci.s" rel="nofollow noreferrer">here</a>.<br/> So, what do you think about it?</p>
[]
[ { "body": "<h1>Why would you do such a thing?</h1>\n<p>I understand that you wrote the Arithmetic Expression Compiler, and perhaps want to show it off. But who would ever want to write a function as simple as a Fibonacci sequence generater using three programming languages (AEC, Intel assembly, and C++) mixed together, and type way more code than it would take in either C++ or even pure Intel assembly itself to implement it?</p>\n<p>AEC doesn't provide any benefits here. Looking at the generated assembly, AEC does not perform any kind of optimization.</p>\n<h1><code>fibonacci.aec</code> syntax</h1>\n<p>The syntax in <code>fibonacci.aec</code> looks quite bad. There's assembly code mixed with AEC's own language. It seems AEC generates ATT syntax, and your inline assembly uses Intel syntax, and you have to manually switch between the two. Also, the instructions you do have to add manually seem very trivial: <code>call</code> and <code>ret</code>. It would be much nicer if the AEC language allowed you to express these operations, so you wouldn't need to add assembly.</p>\n<h1>Comments about your C++ code</h1>\n<h2>Use of global variables</h2>\n<p>I suppose it is a limitation of AEC that you have to use global variables to communicate between the generated assembly code and the C++ code. However, now you have the problem that you cannot call <code>fibonacci()</code> from different threads simultaneously. There's also a compile-time limit on how many elements of the Fibonacci sequence you can generate, due to the size of <code>stackWithLocalVariables[]</code> and <code>memoisation[]</code>.</p>\n<h2>Floats vs. ints</h2>\n<p>Your AEC only deals with 32-bit floating point values, but the C++ program deals with integers, and now has to convert to and from floating point variables to satisfy the assembly code. But a lot of conversions are there only because you are reusing <code>float n</code> to store the user's input, even if you clearly expect an integer. Far better would be to declare an <code>int</code> variable in <code>main()</code>, and copy it to <code>n</code> to satisfy <code>fibonacci()</code>, but avoid all the <code>int(n)</code> casts.</p>\n<h2>Elevenst, twelfnd, thirteenrd</h2>\n<p>The suffix you add to print out &quot;The n-th Fibonacci number is&quot; is calculated using an expression that doesn't catch all the edge cases. I suggest you just do not try to add such a suffix at all, and instead write something like:</p>\n<pre><code>std::cout &lt;&lt; &quot;Element &quot; &lt;&lt; n &lt;&lt; &quot; in the Fibonacci sequence is equal to &quot; &lt;&lt; returnValue &lt;&lt; &quot;.\\n&quot;;\n</code></pre>\n<h2>Use <code>&quot;\\n&quot;</code> instead of <code>std::endl</code></h2>\n<p>I strongly suggest you use <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\"><code>&quot;\\n&quot;</code> instead of <code>std::endl</code></a>; the latter is equivalent to <code>&quot;\\n&quot;</code>, but it also forces a flush of the output stream. That is usually unnecessary and can be detrimental to performance.</p>\n<h2>Avoid using <code>std::system()</code> for trivial things</h2>\n<p><a href=\"https://stackoverflow.com/questions/1107705/systempause-why-is-it-wrong\">Using <code>std::system()</code> is usually wrong</a>. has a huge overhead: it has to create a new shell process, that process has to parse the command you gave, and if that command is not a built-in function of the shell, then it has to start yet another process. As you already have noticed, it also is not portable between different operating systems. And something trivial as <code>std::system(&quot;PAUSE&quot;)</code> can be replaced by a simple C++ statement like:</p>\n<pre><code>std::cin.get();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T18:14:52.207", "Id": "244802", "ParentId": "244789", "Score": "5" } } ]
{ "AcceptedAnswerId": "244802", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T14:35:23.317", "Id": "244789", "Score": "3", "Tags": [ "c++", "recursion", "assembly", "fibonacci-sequence", "memoization" ], "Title": "Fibonacci Sequence using Recursion with Memoisation" }
244789
<p>In the interview you are asked to build a tower in a variable input e.g. n=3 . The output should be as show below.</p> <pre><code>[ ' * ', ' *** ', '*****' ] </code></pre> <p><strong>My solution</strong> is the following. Is this a good enough answer for the problem because I know people can solve it using <strong>Linq</strong> with less lines of code.</p> <pre><code> public string[] PrintStairs(int n) { if (n == 1) { return new []{ &quot; * &quot; }; } var result = new string[n]; for (int row =0; row &lt; n; row++) { var level = new StringBuilder(); var midpoint = ((2 * n - 1) / 2); for (int col =0; col &lt; 2 * n - 1; col++) { if((midpoint-row &lt;= col) &amp;&amp; (midpoint + row &gt;= col)) { level.Append(&quot;*&quot;); } else { level.Append(&quot; &quot;); } } result[row] = string.Concat(new string(level.ToString())); } return result; } </code></pre> <p>Linq Solution:</p> <pre><code> public static string[] TowerBuilder(int nFloors) { return Enumerable.Range(1, nFloors).Select(i =&gt; string.Format(&quot;{0}{1}{0}&quot;, i == nFloors ? &quot;&quot; : new string(' ', nFloors - i), new string('*', 2 * i - 1))).ToArray(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T23:40:20.867", "Id": "480638", "Score": "3", "body": "Personal opinion: If I were code reviewing this, I would ask for consistency in spacing (e.g. `midpoint-row` vs `midpoint + row`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T06:04:46.700", "Id": "480646", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly. Leave the concerns for the question body." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T11:51:55.043", "Id": "480659", "Score": "0", "body": "(1) _\"Is this a good enough answer\"_ isn't meaningfully answerable without understanding both your skill level and the expected skill level you're interviewing for, and any possible modifiers/priorities you've been given to solve this exercise. (2) _\"because I know people can solve it using Linq with less lines of code\"_ Lines of code is not the main measure of quality. If anything, the LINQ example \"cheats\" by inlining a lot of different steps and ends up with compromised readability because of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T12:21:29.473", "Id": "480664", "Score": "0", "body": "Jeff E has a very excellent answer but I would add that you are using var in a very lazy manner, one should only use var when the type can be easily inferred from the name of the variable or when dealing with Linq." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T09:46:16.537", "Id": "480902", "Score": "0", "body": "I always use var is all my coding instead of the declaring the actually property type and its a coding standard within the company i work" } ]
[ { "body": "<p>How did you determine the output <code>' # '</code> for the case <code>n==1</code>? I'd have expected it to just be <code>'*'</code>. If you're unclear about the specification for code you're writing in an interview, it's best to either ask for clarification or document your assumptions -- it's possible they deliberately handed you an unclear spec and are testing how you handle that.</p>\n<p>If we take the interviewer request literally, you're still missing the <code>[ ... ]</code> formatting.</p>\n<h2>Naming</h2>\n<p><code>public string[] PrintStairs(int n)</code></p>\n<p>This method is named as a verb indicating it's useful for its side effect, but it returns a value indicating it's useful for its return value. You should design APIs for one or the other but not both. Since your method is useful for its return value, a more appropriate name might be <code>GenerateStairs</code> or <code>GetStairs</code>.</p>\n<p>Use more descriptive parameter names. <code>numberOfStairs</code> instead of <code>n</code> for example.</p>\n<p>You use two different names, <code>row</code> and <code>level</code>, for different manifestations of the same concept: a step in your staircase. I'd unify these and call them <code>rowIndex</code> and <code>rowBuilder</code> respectively, or maybe <code>stepIndex</code> and <code>stepBuilder</code>.</p>\n<h2>Input validation</h2>\n<p>Your method crashes for negative values of <code>n</code>. If negative numbers are not valid inputs to the method, that fact should be documented by a method header and by throwing an <code>ArgumentOutOfRangeException</code>.</p>\n<h2>String APIs</h2>\n<p><code>result[row] = string.Concat(new string(level.ToString()));</code></p>\n<p>This is a very complicated way of saying <code>result[row] = level.ToString()</code>! <code>string.Concat</code> is an API for concatenating strings, but you are only giving it one string which does nothing but give you the same string out again.</p>\n<p>Explicit <code>string</code> constructors are intended to be used for creating strings from individual characters or from unmanaged code; here you're just giving it another <code>string</code>, which also does nothing but give you the same string out again.</p>\n<h2>General behaviour</h2>\n<p><code>var midpoint = ((2 * n - 1) / 2);</code></p>\n<p>You are doing integer division here. Double-check your math because this expression simplifies to <code>n - 1</code> for positive <code>n</code> -- were you intending for something more elaborate to happen with this calculation? A reader might wonder if there's a bug here.</p>\n<p><code>n</code> doesn't change inside the loop, so this whole line can be moved outside of it.</p>\n<h2>General formatting</h2>\n<p>Your spacing is inconsistent:</p>\n<p><code>for (int row =0; row &lt; n; row++)</code></p>\n<p><code>if((midpoint-row &lt;= col) &amp;&amp; (midpoint + row &gt;= col))</code></p>\n<p><code>for (int col =0; col &lt; 2 * n - 1; col++)</code></p>\n<h2>LINQ</h2>\n<p>Having everything on one line isn't necessarily a <em>good</em> thing. The LINQ solution is impenetrable when written like that. It deserves to be on multiple lines anyway for the sake of being able to read it properly:</p>\n<pre><code>return Enumerable.Range(1, nFloors)\n .Select(i =&gt; string.Format(&quot;{0}{1}{0}&quot;,\n i == nFloors\n ? &quot;&quot;\n : new string(' ', nFloors - i),\n new string('*', 2 * i - 1)))\n .ToArray();\n</code></pre>\n<p>Yes, it's technically LINQ, but the guts of that <code>Select</code> is what's doing all the heavy lifting.</p>\n<p>The LINQ solution doesn't give the same output for <code>n==1</code>, which again begs the question where you got the idea that it should output <code>' # '</code> in the previous solution.</p>\n<p>A more LINQ-y solution would have you build up the building blocks needed to write code that really is shorter. LINQ is all about operations on sequences; the thing that throws a wrench in any LINQ solution here is the fact that the output depends on how many things are in the sequence (the amount of space you use to pad the stairs depends on how many stairs there are), so you're probably going to have to enumerate sequences more than once.</p>\n<p>Here's my LINQ-y take: start with a simple enumerator that gives you unformatted steps, from which you can take any arbitrary number of them:</p>\n<pre><code>private string GenerateStep(int stepIndex)\n{\n if (stepIndex &lt; 1)\n throw new ArgumentOutOfRangeException(nameof(stepIndex));\n return new string('*', stepIndex * 2 - 1);\n}\n\nprivate IEnumerable&lt;string&gt; EnumerateSteps()\n{\n for (int stepIndex = 0; stepIndex &lt; int.MaxValue; stepIndex++)\n {\n yield return GenerateStep(stepIndex);\n }\n}\n</code></pre>\n<p>Now I can say <code>EnumerateSteps().Take(3)</code> to get:</p>\n<pre><code>[\n '*',\n '***',\n '*****'\n]\n</code></pre>\n<p>Then define a method that takes a sequence of strings and centers them:</p>\n<pre><code>static class StringExtensions\n{\n private static string CenterFormatted(string original, int totalWidth)\n {\n if (original == null)\n throw new ArgumentNullException(nameof(original));\n if (totalWidth &lt; original.Length)\n throw new ArgumentOutOfRangeException(nameof(totalWidth));\n\n int paddingNeededOnLeft = (totalWidth - original.Length) / 2;\n int paddingNeededOnRight = totalWidth - original.Length - paddingNeededOnLeft;\n\n return String.Concat(\n new string(' ', paddingNeededOnLeft),\n original,\n new string(' ', paddingNeededOnRight));\n }\n\n public static IEnumerable&lt;string&gt; CenterFormatted(this IEnumerable&lt;string&gt; sequence)\n {\n // Exercise: how will you check for a null input sequence here? If you check it here and throw ArgumentNullException, will it actually throw when you call CenterFormatted?\n int largestStringLength = sequence.Max(s =&gt; s.Length);\n foreach (string original in sequence)\n {\n yield return CenterFormatted(original, largestStringLength);\n }\n }\n}\n</code></pre>\n<p>Now you have two orthogonal and reusable things: a thing that generates steps and a thing that centers sequences of strings. You can compose these quite concisely in a LINQ statement to solve the original problem:</p>\n<p><code>EnumerateSteps().Take(3).CenterFormatted().ToArray()</code></p>\n<p>which gives me</p>\n<pre><code>[\n ' * ', \n ' *** ', \n '*****'\n]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T09:53:36.420", "Id": "480903", "Score": "0", "body": "I made a mistake with \"# ' for the case n==1\". Thanks for the reply." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T16:08:27.897", "Id": "244794", "ParentId": "244790", "Score": "20" } }, { "body": "<blockquote>\n<p>Is this a good enough answer?</p>\n</blockquote>\n<p>This isn't meaningfully answerable without understanding both your skill level and the expected skill level you're interviewing for, and any possible modifiers/priorities you've been given to solve this exercise.</p>\n<blockquote>\n<p>Because I know people can solve it using Linq with less lines of code</p>\n</blockquote>\n<p>Line count is not the main measure of quality. If anything, the LINQ example &quot;cheats&quot; by inlining a lot of different steps and ends up with compromised readability because of it.</p>\n<hr />\n<p>That being said, there are certain improvements to be made here. You've made things much more complex than they need to be. I'm going to make an educated guess here and say that you were <a href=\"https://dev.to/dstarner/dont-be-a-shotgun-coder-2hfp\" rel=\"noreferrer\">shotgun coding</a> and then did not clean up/refactor afterwards.</p>\n<p>You would've been better off taking a step back and figuring out if you could calculate some things instead of iteratively needing to exploring them. If you had done so, you would've been able to break things down into three easy steps.</p>\n<p>The main example of this is that you're adding every whitespace individually, which is not performant. It could've been calculated once, instead of iteratively adding them. A basic formula would be:</p>\n<pre><code>amount_of_blanks_on_one_side = tower_height - current_step_index - 1\n</code></pre>\n<p>Or if your steps are counted using 1-indexing (which I will actually use in this case:</p>\n<pre><code>amount_of_blanks_on_one_side = tower_height - current_step\n</code></pre>\n<p>Pick any tower size, and you'll see that this formula is correct for every step of every possible tower.</p>\n<p>I'm not going to get into the specific code for this yet, but this already suggests that you have a clearly abstractable method here:</p>\n<pre><code>string stepString = GenerateStep(towerHeight, currentStep);\n</code></pre>\n<hr />\n<p>We've now split our logic into two separate steps:</p>\n<ul>\n<li>How we generate a single step (<code>GenerateStep</code>)</li>\n<li>How we combine these single steps into a tower</li>\n</ul>\n<p>Let's focus on the second one now. It is assume that we already know the tower height, so let's work with a basic variable for now:</p>\n<pre><code>int towerHeight = 3;\n</code></pre>\n<p>Then, we're going to need a list of the steps (i.e. the number denoting each step. That is always going to be a list of numbers starting at <code>1</code> and ending at <code>towerHeight</code>, which can be easily generated using:</p>\n<pre><code>var steps = Enumerable.Range(1, towerHeight);\n\n// steps: [ 1, 2, 3 ]\n</code></pre>\n<p>And now, we want to convert each step into the string we need it to be. Luckily, we already defined this as the <code>GenerateStep</code> method:</p>\n<pre><code>var tower = steps.Select(step =&gt; GenerateStep(towerHeight, step));\n\n// tower: [ &quot; * &quot;, &quot; *** &quot;, &quot;*****&quot; ]\n</code></pre>\n<p>And that's all you need to do to get the tower you're looking for. Of course, we still need to look at how you generate the step string, but I want you to see how simple the rest of the logic really is.</p>\n<hr />\n<p>Now, all we need to do is figure out how to generate a given step, based on the tower height and current step number. We don't need to worry about loops or towers anymore, we can focus solely on generating a single step. This will be wrapped in the method we already defined:</p>\n<pre><code>public string GenerateStep(int towerHeight, int currentStep)\n{\n // ...\n}\n</code></pre>\n<p>A step is always of the form:</p>\n<pre><code>[X amount of blanks][Y amount of asterisks][X amount of blanks]\n</code></pre>\n<p>So we really just need to figure out what X (which I'll call the padding) and Y (which I'll call the width of the tower) are.</p>\n<p>We actually already established how to find the padding (X):</p>\n<pre><code>amount_of_blanks_on_one_side = tower_height - current_step\n</code></pre>\n<p>Or, in code:</p>\n<pre><code>int paddingSize = towerHeight - currentStep;\n</code></pre>\n<p>The width of the tower is slightly more complex. Let's look at some numbers to see if we spot the formula</p>\n<pre><code>STEP | WIDTH\n------------\n 1 | 1\n 2 | 3\n 3 | 5\n 4 | 7\n 5 | 9\n</code></pre>\n<p>Depending on how you look at it, you should quickly figure out that the width is always one less than the double of the step number, i.e.:</p>\n<pre><code>int towerWidth = 2 * currentStep - 1;\n</code></pre>\n<p>So now we know our width and padding. The only thing that's left is how to generate a string of a given length with a repeating character. There is actually a <code>string</code> constructor for that:</p>\n<pre><code>var myString = new string(myCharacter, amountOfCharacters);\n</code></pre>\n<p>Therefore, we can generate the appropriate strings:</p>\n<pre><code>string padding = new string(' ', paddingSize);\nstring towerPart = new string('*', towerWidth);\n</code></pre>\n<p>And then we put these string together:</p>\n<pre><code>string result = $&quot;{padding}{towerPart}{padding}&quot;;\n</code></pre>\n<p>And that's it.</p>\n<hr />\n<p>Putting it all together:</p>\n<pre><code>public IEnumerable&lt;string&gt; GenerateTower(int towerHeight)\n{\n var steps = Enumerable.Range(1, towerHeight);\n\n var tower = steps.Select(step =&gt; GenerateStep(towerHeight, step));\n\n return tower;\n}\n\npublic string GenerateStep(int towerHeight, int currentStep)\n{\n int paddingSize = towerHeight - currentStep;\n int towerWidth = 2 * currentStep - 1;\n\n string padding = new string(' ', paddingSize);\n string towerPart = new string('*', towerWidth);\n\n return $&quot;{padding}{towerPart}{padding}&quot;;\n}\n</code></pre>\n<p>If you examine the steps closely, this actually mirrors the LINQ example you provided. But the LINQ example is horribly unreadable, which is why I opted for a bit more verbosity to ensure that the code remains clean and readable.</p>\n<p>Could you optimize this further? Yes, and I'm sure this has already been golfed. But further condensing the code is only going to detract from the readability, which is why you're better off not optimizing any further (unless you are dealing with very specific performance constraints).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T10:17:30.760", "Id": "480907", "Score": "0", "body": "When you do the calculation for int paddingSize = towerHeight - currentStep. If(n =3) for first loop with have a padding size of 2. So how does that work? I know the answer is correct" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T11:35:28.450", "Id": "480913", "Score": "0", "body": "@GreatKhan2016: It helps to count from the ground up (= the end of the array). The last element should have 0 padding. The one above it should have 1 padding. The one above it should have 2 padding. And so on... You'll notice that for any tower with `n` steps, the paddings start at `n-1` and decreases all the way down to `0`. For for `n=3` that's padding sizes `[2,1,0]`, for `n=5` that's padding sizes `[4,3,2,1,0]` and for `n=100` that would be padding sizes `[99, 98, 97, ..., 2, 1, 0]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T11:43:27.910", "Id": "480914", "Score": "0", "body": "@GreatKhan2016: If you're unsure how to find a formula for calculating a number, it helps to write down a bunch of examples and see if you can spot a pattern. If you can guess the next number in the sequence, that means there is a pattern to the sequence and therefore an underlying formula that expresses that pattern. You can see in the answer that I did this when we were trying to figure out how to calculate the width of the tower. You can use the exact same approach when you want to calculate the padding size." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T13:16:54.317", "Id": "244831", "ParentId": "244790", "Score": "5" } }, { "body": "<p>The first things that strike me:</p>\n<ul>\n<li>Where is the documentation?</li>\n<li>How do I know what the code is <em>intended</em> to do (which may be different from what it does)?</li>\n<li>Why are there no comments at all in/near the code?</li>\n</ul>\n<p>As such, the code is not maintainable, neither by you in 6 months or some poor maintenance programmer who gets to fix/update the program. (Always program assuming the maintenance programmer who will have to keep your code alive is a homicidal maniac with a chainsaw and knows where you live.)</p>\n<p><em>Given a number i, this will return an array of i elements. The elements are strings that, when printed/displayed with a monospaced font, will show a triangle. With an input of 3, an array containing these 3 elements is returned:</em></p>\n<pre><code>' * '\n' *** '\n'*****' \n</code></pre>\n<p>There are also no tests, but that may be justified if it is just an example. (Input validation etc. etc. etc. have been mentioned by others.)</p>\n<p>Unless there is a really, really good reason, you need your code to be (in this order):</p>\n<ol>\n<li>correct: getting the wrong answers makes the code utterly useless.</li>\n<li>maintainable: a new programmer (or you in 6 months) must understand this.</li>\n<li>sufficiently fast while not being an undue burden on memory, I/O, storage space etc.</li>\n</ol>\n<p>Why is speed/memory/... not placed higher? Because usually these limitations can be solved by throwing money at it, whereas a non-maintainable program is a millstone round the neck.</p>\n<p>LoC is a <em>terrible</em> measurement.<br />\nPerformance<br />\ncalculated<br />\nby<br />\nLines<br />\nof<br />\nCode<br />\njust<br />\ncauses<br />\nmore<br />\nline-<br />\nbreaks.<br />\n(See how productive I have been?)</p>\n<p>Elegant code is maintainable: succinct, minimum boilerplate code, idiomatic use of the language.</p>\n<p>There are code formatters for C# out there: use them! Tweak then to fit the style guide used --- if necessary create a style guide.</p>\n<p>Consistency is especially important when there are/will be more than one single programmer.</p>\n<p>Your choice of name is ... <em>interesting</em>. Nothing is actually printed. Even when the result is printed, you will get no stairs. It'll be a triangle, a pyramid, maybe even a &quot;tower&quot;. Good names provide a very useful abstractions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T09:57:04.567", "Id": "480904", "Score": "0", "body": "Sorry it is a coding challenge and i want to know if i spend 20 mins writing the code if it was good enough" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T20:08:27.537", "Id": "244901", "ParentId": "244790", "Score": "1" } } ]
{ "AcceptedAnswerId": "244831", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T15:05:20.930", "Id": "244790", "Score": "3", "Tags": [ "c#" ], "Title": "Coding Challenge : Build Tower refactoring code is it necessary" }
244790
<p>I have a pandas dataframe, <code>df1</code>:</p> <pre><code>a b c d e f 1 1 1 x 1 5 1 1 1 x 1 6 1 1 1 y 1 5 1 1 1 y 1 7 </code></pre> <p>and another dataframe, <code>df2</code>:</p> <pre><code>a b c d e f 1 1 1 x 1 5 </code></pre> <p>Now I want to filter <code>df1</code> on columns <code>a, b, c, d</code> if it is present in respective columns of <code>df2</code>. This is what I tried:</p> <pre><code>mask = df1['a'].isin(df2['a']) &amp; df1['b'].isin(df2['b']) &amp; df1['c'].isin(df2['c']) &amp; df1['d'].isin(df2['d']) df_new = df1[mask] </code></pre> <p>so <code>df_new</code> finally contains:</p> <pre><code>a b c d e f 1 1 1 x 1 5 1 1 1 x 1 6 </code></pre> <p>I am looking for a better approach as there are a lot of columns to compare and a lot of rows, both in <code>df1</code> and <code>df2</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T20:04:06.417", "Id": "480627", "Score": "0", "body": "http://www.datasciencemadesimple.com/intersection-two-dataframe-pandas-python-2/ and https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html is what you need." } ]
[ { "body": "<p>You need to merge dataframes like done here in <a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html\" rel=\"nofollow noreferrer\">Pandas Merge</a>. You also need to read on <code>dataframe joins</code> which is a common topic in learning databases.Here I have not done any tweaking with indices i.e, whether to keep left ones or right ones but you can check the docs for better information on here <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html#pandas.DataFrame.merge\" rel=\"nofollow noreferrer\">Merge Docs Pydata</a></p>\n<pre><code>import pandas as pd\n\ncolumns = &quot;a b c d e f&quot;.split()\ndata = '''1 1 1 x 1 5\n1 1 1 x 1 6\n1 1 1 y 1 5\n1 1 1 y 1 7'''.split(&quot;\\n&quot;)\n\ndata = list(map(lambda x:x.split(), data ))\n</code></pre>\n<hr />\n<pre><code>left = pd.DataFrame(columns = columns, data=data)\n\n\n\n a b c d e f\n0 1 1 1 x 1 5\n1 1 1 1 x 1 6\n2 1 1 1 y 1 5\n3 1 1 1 y 1 7\n</code></pre>\n<hr />\n<pre><code>right = pd.DataFrame(data = [&quot;1 1 1 x 1 5&quot;.split()], columns=columns)\n\n\n a b c d e f\n0 1 1 1 x 1 5\n</code></pre>\n<hr />\n<pre><code>pd.merge(left, right, how=&quot;right&quot;, on=[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;])\n\n a b c d e_x f_x e_y f_y\n0 1 1 1 x 1 5 1 5\n1 1 1 1 x 1 6 1 5\n</code></pre>\n<hr />\n<pre><code>pd.merge(left, right, how=&quot;right&quot;, on=[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;], suffixes=[&quot;&quot;, &quot;_&quot;] ).drop([&quot;e_&quot;, &quot;f_&quot;], axis=1)\n\n\n a b c d e f\n0 1 1 1 x 1 5\n1 1 1 1 x 1 6\n</code></pre>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T08:26:43.497", "Id": "480764", "Score": "0", "body": "Those screenshots don't make the answer clearer. You can use to_clipboard to get a decent text representation" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T20:22:29.027", "Id": "244810", "ParentId": "244793", "Score": "1" } } ]
{ "AcceptedAnswerId": "244810", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T16:06:58.007", "Id": "244793", "Score": "2", "Tags": [ "python", "pandas" ], "Title": "Pandas filter dataframe on multiple columns wrt corresponding column values from another dataframe" }
244793
<p>I am trying to figure out whether the below is better than just having a raw script or just a script with functions.</p> <pre><code>class WebsiteImages(object): def __init__(self,photographer,Website_url): self.photographer = photographer self.Website_url = Website_url def GetNumberOfResultPages(self): #Get the exact number of pages in the results from selenium import webdriver browser = webdriver.Firefox() browser.get(self.Website_url) last_number_page = browser.find_elements_by_xpath(&quot;//span[@class='search-pagination__last-page']&quot;) for i in last_number_page: number_of_pages = i.text return number_of_pages def GetImageIds(self): number_of_pages = self.GetNumberOfResultPages() Website_ids = [] self.number_of_pages = number_of_pages #For each page get the image IDs import urllib from bs4 import BeautifulSoup import sys from time import sleep for page in range(1,int(number_of_pages)+1): #Extract the image id only and save it in file url = urllib.request.urlopen(self.Website_url+'&amp;page='+str(page)+'&amp;sort=best') sleep(1) content = url.read() soup = BeautifulSoup(content, 'lxml') #search on page for div class and extract the id between the gi-asset attribute images_found = soup.find_all('gi-asset') #gi-asset is the HTML object that contains the image and the id in the search results for i in range(len(images_found)): #range(len(images_found)) Website_id = images_found[i].get('data-asset-id') #data-asset-id' is the HTML object that contains the ID if Website_id not in 'placeholder': Website_ids.append(Website_id) return Website_ids # Define some photographers john_smith = WebsiteImages('John%20Smith', 'https://www.WebsiteImages.co.uk/search/photographer?assettype=image&amp;photographer=John%20smith') # Now we can get to the image IDs easily #print(john_smith.GetNumberOfResultPages()) print(john_smith.GetImageIds()) </code></pre> <p>The idea of using the class was to make the script more organised and the outputs accessible for different search results. Example below:</p> <pre><code>one_guy = WebsiteImages('One%20Guy', 'https://www.WebsiteImages.co.uk/search/photographer?photographer=John%20smith') two_guy = WebsiteImages('Two%20Guy', 'https://www.WebsiteImages.co.uk/search/photographer?photographer=John%20smith') </code></pre>
[]
[ { "body": "<h1>Class inheritance</h1>\n<p>Classes no longer have to be subclasses from object</p>\n<pre><code>class WebsiteImages:\n</code></pre>\n<h1>Naming Conventions</h1>\n<p>Methods and variable names should be <code>snake_case</code>. Classes should be <code>PascalCase</code>, so you got that correct :-).</p>\n<h1>Imports</h1>\n<p>Any and all imports should go at the top of the file.</p>\n<h1><code>f&quot;&quot;</code> strings</h1>\n<p>You should use <code>f&quot;&quot;</code> strings to directly implement variables into your strings.</p>\n<pre><code>url = urllib.request.urlopen(f&quot;{self.website_url}&amp;page={page}&amp;sort=best&quot;)\n</code></pre>\n<h1>User Interaction</h1>\n<p>The way a user has to interact with this program is pretty challenging to understand. If I was a normal user, I would do something like this:</p>\n<pre><code>person = WebsiteImages(&quot;John Smith&quot;, &quot;https://www.WebsiteImages.co.uk&quot;)\n</code></pre>\n<p>But I would get an error, or no images returned because I didn't know the name had to be encoded with <code>%20</code> and I didn't know I needed to specify a very particular url. I would blame it on the program and look for something else that's more user friendly.</p>\n<hr>\n<p>I would solve this by only requiring a name. Since you're going to one website, you can save the url as an instance variable and sort things out there, instead of relying on a user to provide perfect input. <em>Never trust user input</em>.</p>\n<pre><code>john = WebsiteImages(&quot;John Smith&quot;)\nprint(john.get_image_ids())\n</code></pre>\n<p>And within the constructor you can do something like this:</p>\n<pre><code>def __init__(self, photographer: str):\n self.photographer = '%20'.join(photographer.split())\n self.website_url = f&quot;https://www.WebsiteImages.co.uk/search/photographer?photographer={self.photographer}&quot;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T18:33:47.860", "Id": "480620", "Score": "1", "body": "Just one comment. No need to join the '%20' bit as it is an HTML unicode and it is automatically generated in the link if it is blank :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T17:04:42.180", "Id": "244797", "ParentId": "244796", "Score": "4" } } ]
{ "AcceptedAnswerId": "244797", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T16:44:25.547", "Id": "244796", "Score": "3", "Tags": [ "python", "python-3.x", "classes", "beautifulsoup" ], "Title": "Class or not in Page Scraper (Python BeautifulSoup)" }
244796
<p>Another graph algorithm, this time to create a priority or build order. Provided with a starting <code>List&lt;Project&gt;</code> and <code>List&lt;ProjectWithPrerequisite&gt;</code> the algorithm will return the order to build them in. For a list of projects <code>a, b, c, d, e, f</code> and their corresponding prerequisites where <code>a, d</code> means that a is a prerequisite for d or <code>a--&gt;d</code>.</p> <p>To find the build order, projects are sorted in descending prerequisite order so that projects with the most prerequisites come first. Each project has a path created for every prerequisite up until the starting node is found, which has no prerequisites. Projects with multiple prerequisites, and subsequent multiple paths, have these paths merged into a single path for the build order of that project. Once the linear path has been created for the project it is added to a completed order list.</p> <p>To avoid repeatedly searching the same path I check if a <code>Project</code> already belongs to the completed order and if so stop checking since it will already have its itself and precedents as members.</p> <p>I have not considered the scenarios where:</p> <ul> <li>All projects have prerequisites which forms a loop with itself. A--&gt;B--&gt;C--&gt;A</li> <li>There are two or more non-connected paths (islands) for the same project.</li> </ul> <p>Included at the end are the unit tests I used.</p> <p>How can I improve my logic? Does anything stand out as excessively complex or not straightforward enough?</p> <pre><code>public class Project { public List&lt;Project&gt; Prerequisites { get; } = new List&lt;Project&gt;(); public char Name { get; } public Project(char name) { Name = name; } } public class ProjectWithPrerequisite { public Project Project { get; } public Project Prerequisite { get; } public ProjectWithPrerequisite(Project prerequisite, Project project) { Prerequisite = prerequisite; Project = project; } } public class ProjectBuildOrder { private Dictionary&lt;char, Project&gt; _projects { get; } private List&lt;ProjectWithPrerequisite&gt; _singlePrerequisites { get; } private List&lt;Project&gt; _completedOrder = new List&lt;Project&gt;(); public ProjectBuildOrder(List&lt;Project&gt; projects, List&lt;ProjectWithPrerequisite&gt; singlePrerequisites) { _projects = new Dictionary&lt;char, Project&gt;(projects.Count); foreach (var item in projects) { _projects.Add(item.Name, item); } _singlePrerequisites = singlePrerequisites; } /// &lt;summary&gt; /// Creates the build order to accomplish the given list of projects. /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public List&lt;Project&gt; GenerateBuildOrder() { AddPrerequisitesToProjects(); return BuildOrder(); } /// &lt;summary&gt; /// Adds the provided prerequisites to the projects. /// &lt;/summary&gt; private void AddPrerequisitesToProjects() { foreach (var pair in _singlePrerequisites) { var projectWithPrerequisite = _projects[pair.Project.Name]; projectWithPrerequisite.Prerequisites.Add(pair.Prerequisite); } } /// &lt;summary&gt; /// Creates the build order for the list of &lt;see cref=&quot;Project&quot;/&gt;s. /// &lt;/summary&gt; /// &lt;returns&gt;&lt;see cref=&quot;List{T}&quot;/&gt; containing the build order for the provided list of &lt;see cref=&quot;Project&quot;/&gt;s and their prerequisites.&lt;/returns&gt; private List&lt;Project&gt; BuildOrder() { var checkOrder = _projects .OrderByDescending(kvp =&gt; kvp.Value.Prerequisites.Count).Select(kvp =&gt; kvp.Value); _completedOrder = new List&lt;Project&gt;(); var path = new LinkedList&lt;Project&gt;(); foreach (var project in checkOrder.Where(p =&gt; !_completedOrder.Contains(p))) { if (project.Prerequisites.Count &gt; 1) { var branchPaths = GetBranchPrecedents(project); path = MergePaths(branchPaths); } else { path = NonBranchingPath(project); } _completedOrder.AddRange(path.Where(p =&gt; !_completedOrder.Contains(p))); } return _completedOrder; } /// &lt;summary&gt; /// For a node which has only a single prerequisite. This will follow the path back to the end, branching if necessary by claling &lt;see cref=&quot;GetBranchPrecedents(Project)&quot;/&gt;. /// &lt;/summary&gt; /// &lt;param name=&quot;project&quot;&gt;The node whose precedents will be listed.&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private LinkedList&lt;Project&gt; NonBranchingPath(Project project) { if (project.Prerequisites.Count == 0) { var ll = new LinkedList&lt;Project&gt;(); ll.AddLast(project); return ll; } if (project.Prerequisites.Count == 1) { var ll = new LinkedList&lt;Project&gt;(); ll.AddLast(project); var parent = project.Prerequisites[0]; if (_completedOrder.Contains(parent)) { return ll; } while (parent.Prerequisites.Count == 1) { ll.AddFirst(parent); parent = parent.Prerequisites[0]; if (_completedOrder.Contains(parent)) { break; } } if (parent.Prerequisites.Count == 0) { if (!_completedOrder.Contains(parent)) { ll.AddFirst(parent); } return ll; } var parentPath = MergePaths(GetBranchPrecedents(parent)); var first = ll.First.Value; ll.RemoveFirst(); parentPath.AddLast(first); return parentPath; } return MergePaths(GetBranchPrecedents(project)); } /// &lt;summary&gt; /// When a node contains multiple prerequisites it will follow each path. If a prerequisite path branches it will recursively /// call itself to find those branching paths, and merging them. /// &lt;/summary&gt; /// &lt;param name=&quot;projectForPrerequisite&quot;&gt;Node containini more than one prerequisite.&lt;/param&gt; /// &lt;returns&gt;&lt;see cref=&quot;List{T}&quot;/&gt; containing the distinct path branches.&lt;/returns&gt; private List&lt;LinkedList&lt;Project&gt;&gt; GetBranchPrecedents(Project projectForPrerequisite) { var list = new List&lt;LinkedList&lt;Project&gt;&gt;(); foreach (var parent in projectForPrerequisite.Prerequisites.Where(project =&gt; !_completedOrder.Contains(project))) { switch (parent.Prerequisites.Count) { case 0: var endOfPrecedenceChain = new LinkedList&lt;Project&gt;(); endOfPrecedenceChain.AddFirst(parent); endOfPrecedenceChain.AddLast(projectForPrerequisite); list.Add(endOfPrecedenceChain); break; case 1: var nonBranch = NonBranchingPath(parent); nonBranch.AddLast(projectForPrerequisite); list.Add(nonBranch); break; default: var branchPrecedents = GetBranchPrecedents(parent); var mergedPrecedents = MergePaths(branchPrecedents); mergedPrecedents.AddLast(parent); mergedPrecedents.AddLast(projectForPrerequisite); list.Add(mergedPrecedents); break; } } return list; } /// &lt;summary&gt; /// Merge each of the branching paths in the &lt;see cref=&quot;LinkedList{T}&quot;/&gt; into one. Merging based on precedence they were added. /// &lt;/summary&gt; /// &lt;param name=&quot;paths&quot;&gt;A &lt;see cref=&quot;List{T}&quot;/&gt; containing the branching paths.&lt;/param&gt; /// &lt;returns&gt;&lt;see cref=&quot;LinkedList{T}&quot;/&gt; of path back to a starting node which has no prerequisites.&lt;/returns&gt; LinkedList&lt;Project&gt; MergePaths(List&lt;LinkedList&lt;Project&gt;&gt; paths) { if (paths.Count == 1) { return paths[0]; } var last = paths[0].Last.Value; var merged = paths[0]; merged.RemoveLast(); LinkedList&lt;Project&gt; ll; for (int path = 1; path &lt; paths.Count; path++) { ll = paths[path]; ll.RemoveLast(); while (ll.Any()) { if (!merged.Contains(ll.First.Value)) { merged.AddLast(ll.First.Value); } ll.RemoveFirst(); } } merged.AddLast(last); return merged; } } </code></pre> <p>Unit tests to check results against.</p> <pre><code>[Fact] public void Single_branch_list_follows_build_order() { #region All_projects var a = new Project('a'); var b = new Project('b'); var c = new Project('c'); var d = new Project('d'); var e = new Project('e'); var f = new Project('f'); #endregion var expected = new List&lt;Project&gt;() { f, a, b, d, c, e }; var projects = new List&lt;Project&gt;() { a, b, c, d, e, f }; var projectsAndPrerequisite = new List&lt;ProjectWithPrerequisite&gt;() { new ProjectWithPrerequisite(a, d), new ProjectWithPrerequisite(f, b), new ProjectWithPrerequisite(b, d), new ProjectWithPrerequisite(f, a), new ProjectWithPrerequisite(d, c) }; var sut = new ProjectBuildOrder(projects, projectsAndPrerequisite); var actual = sut.GenerateBuildOrder(); Assert.Equal(expected, actual); } [Fact] public void Multi_branch_list_follows_build_order() { #region All_projects var a = new Project('a'); var b = new Project('b'); var c = new Project('c'); var d = new Project('d'); var e = new Project('e'); var f = new Project('f'); var g = new Project('g'); #endregion var expected = new List&lt;Project&gt;() { g, f, a, b, d, c, e }; var projects = new List&lt;Project&gt;() { a, b, c, d, e, f, g }; var projectsAndPrerequisite = new List&lt;ProjectWithPrerequisite&gt;() { new ProjectWithPrerequisite(g, c), new ProjectWithPrerequisite(a, d), new ProjectWithPrerequisite(f, b), new ProjectWithPrerequisite(b, d), new ProjectWithPrerequisite(f, a), new ProjectWithPrerequisite(d, c) }; var sut = new ProjectBuildOrder(projects, projectsAndPrerequisite); var actual = sut.GenerateBuildOrder(); Assert.Equal(expected, actual); } [Fact] public void Multi_branch_list_has_prerequisites_sorted_in_alphabetical_order() { #region All_projects var a = new Project('a'); var b = new Project('b'); var c = new Project('c'); var d = new Project('d'); var e = new Project('e'); var f = new Project('f'); var g = new Project('g'); #endregion var expected = new List&lt;Project&gt;() { f, g, b, a, d, c, e }; var projects = new List&lt;Project&gt;() { a, b, c, d, e, f, g }; var projectsAndPrerequisite = new List&lt;ProjectWithPrerequisite&gt;() { new ProjectWithPrerequisite(g, b), new ProjectWithPrerequisite(g, c), new ProjectWithPrerequisite(a, d), new ProjectWithPrerequisite(f, b), new ProjectWithPrerequisite(b, d), new ProjectWithPrerequisite(f, a), new ProjectWithPrerequisite(d, c), new ProjectWithPrerequisite(f, g), }; var sut = new ProjectBuildOrder(projects, projectsAndPrerequisite); var actual = sut.GenerateBuildOrder(); Assert.Equal(expected, actual); } </code></pre>
[]
[ { "body": "<h2>Algorithm</h2>\n<h3>Correctness</h3>\n<p>Due to a small problem in <code>GetBranchPrecedents</code> this algorithm does not actually work. The case that all parents might already be present in the complete order. E.g. take the graph with the edges (C,A), (D,A), (E,A), (D,B), (E,B). In this case, A has the most prerequisites and will be treated first. This puts all nodes but B into the order. Since B has more than one prerequisite, the branch using <code>GetBranchPrecedents</code> is used, where no parent will be evaluated because they are all already in the complete order.</p>\n<p>This can easily be fixed by treating this special case inside <code>GetBranchPrecedents</code> or by making the function better honor its name and adding the final node for the project in question outside of it.</p>\n<h3>Design and Documentation</h3>\n<p>The design of the algorithm seems to be a bit convoluted. This seems to partly originate in a lack of documentation of <code>NonBranchingPath</code>'s purpose. As far as I can see, it is simply a performance optimization to avoid merging single element lists of ancestor paths. This would also explain the switch from a recursive approach to the inclusion of iterative parts. The algorithm itself could have been written entirely without special-casing single parents.</p>\n<h3>Performance</h3>\n<p>The asymptotic complexity of this algorithm is rather bad. It is at least never better than <code>O(V^2)</code> but might as well only be <code>O(V^3)</code>, where <code>V</code> is the number of projects (vertices); I have not performed a thorough analysis.</p>\n<p>The first problem is that the check whether a project already exists in the final order is performed by a <code>Contains</code> on the list containing the final order. Each of these checks is an <code>O(V)</code> operation. By maintaining a <code>HashSet</code> of the already sorted projects, this could be essentially reduced to <code>O(1)</code>.</p>\n<p>The second problem is that <code>MergePaths</code> may have to revisit the same nodes a lot and that the <code>Contains</code> check here is on a linked list. The check could be optimized by maintaining a <code>HashSet</code> again. However, there is no easy solution for the other problem. E.g. take a chain of <code>n</code> nodes one depending on the next; let the last one depend on <code>n</code> other nodes, which all depend on one final node. All descendant paths for the final node will contain the first <code>n</code> nodes. Thus, this step is at least quadratic in the number of nodes, even when the number of edges is linear in the number of nodes.</p>\n<p>Finally, sorting the elements at the start is not really necessary and leads to a minimum complexity of <code>O(V*log(V))</code>, no matter how few edges there are.</p>\n<h3>Alternatives</h3>\n<p>There is an alternative approach to this problem, which is also known as topological sorting, that is a bit easier to follow and at the same time achieves an asymptotic complexity of <code>O(V+E)</code>, where <code>V</code> is the number of projects and <code>E</code> the number of prerequisites. I do not want to spoil the answer to how it works here, though. (You can just search for topological sort, if you do not want to figure it out yourself.) I will just give the hint that you should think about which nodes you can add at the start or the build order and what you have to maintain to let the problem look the same, just for a smaller list of projects, after you have added the first element.</p>\n<h2>API</h2>\n<p>To me, the API is a bit confusing, i.e. the publicly accessible features to not follow a clear line and impose some restrictions, which are not really needed.</p>\n<p>The first thing that confused me a bit was that you have a separate class for the dependency edges, while the projects already contains that information. In addition, your functionality takes in both projects and dependencies at the same time. This is confusing because it is not clear which of the dependency information will be taken into account.</p>\n<p>I see two ways to make this clearer: either remove the dependency input entirely or remove the dependencies from the projects. In both cases, only one source of dependencies remains ant the API is clearer. In the latter case, you could maintain the dependencies of project information in a dictionary.</p>\n<p>You <code>Project</code> classes expose a bit much functionality to the public. All they really need to expose regarding the dependencies is an <code>IReadOnlyCollecion&lt;Project&gt;</code> and a method <code>AddDependency</code> or an <code>ICollection&lt;Project&gt;</code>, if you want to allow deleted as well. There is really no value in the order of the dependencies here. Should that be important for some other external reason, at least consider using the interface <code>IList</code> instead of fixing the concrete implementation.</p>\n<p>On a similar note, the constructor for <code>ProjectBuildOrder</code> could just take <code>IEnumerable&lt;T&gt;</code> instances since you just iterate over them once.</p>\n<p>In addition, the whole class <code>ProjectBuildOrder</code> would probably be better off as a function or as a strategy class with a single function taking in the current constructor parameters as its parameters. There is no real benefit here in maintaining any information on the class level, except maybe convenience. If information was passed around in a more functional way, it would be possible to use this algorithm on multiple threads in parallel.</p>\n<p>Finally, the return type of <code>GenerateBuildOrder</code> could be an <code>IList&lt;Project&gt;</code> and should probably be better names <code>BuildOrder</code>. In general, when naming methods, procedures should be verbs describing what they do and functions and properties should be nouns describing the result.</p>\n<h2>General</h2>\n<p>I will not write too much in this category, since the review is already long enough. However, I would like to point out that the naming of variables could be improved a bit. In general, it tries to state what the things are, but then slips a bit, which can become confusing. One example of this is the loop variable <code>path</code> in <code>MergePaths</code>, which really should be <code>pathIndex</code> because <code>ll</code> is the actual path. Moreover, using <code>ll</code> for the linked lists everywhere wastes the opportunity to state what the linked list represents. In general, name things after what they represent, not after what they technically are.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T23:21:55.147", "Id": "244815", "ParentId": "244798", "Score": "10" } } ]
{ "AcceptedAnswerId": "244815", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T17:49:57.067", "Id": "244798", "Score": "11", "Tags": [ "c#", "algorithm", "graph" ], "Title": "Create a build order from a list of projects and their respective prerequisites" }
244798
<p>I'm posting my code for a LeetCode problem copied here. If you have time and would like to review, please do so. Thank you!</p> <h3>Problem</h3> <blockquote> <p>Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.</p> <p>Two trees are duplicate if they have the same structure with same node values.</p> <p>Example 1:</p> <pre><code> 1 / \ 2 3 / / \ 4 2 4 / 4 </code></pre> <p>The following are two duplicate subtrees:</p> <pre><code> 2 / 4 </code></pre> <p>and</p> <pre><code> 4 </code></pre> <p>Therefore, you need to return above trees' root in the form of a list.</p> </blockquote> <h3>Code</h3> <pre><code>#include &lt;vector&gt; #include &lt;unordered_map&gt; #include &lt;string&gt; class Solution { public: std::vector&lt;TreeNode *&gt; findDuplicateSubtrees(TreeNode *root) { std::unordered_map&lt;string, std::vector&lt;TreeNode *&gt;&gt; nodes_map; std::vector&lt;TreeNode *&gt; duplicates; this-&gt;serialize(root, nodes_map); for (auto iter = nodes_map.begin(); iter != nodes_map.end(); iter++) { if (iter-&gt;second.size() &gt; 1) { duplicates.push_back(iter-&gt;second[0]); } } return duplicates; } private: std::string serialize(TreeNode *node, std::unordered_map&lt;std::string, std::vector&lt;TreeNode *&gt;&gt; &amp;nodes_map) { if (!node) { return &quot;&quot;; } std::string serialized = &quot;[&quot; + serialize(node-&gt;left, nodes_map) + std::to_string(node-&gt;val) + serialize(node-&gt;right, nodes_map) + &quot;]&quot;; nodes_map[serialized].push_back(node); return serialized; } }; </code></pre> <h3>Reference</h3> <p>LeetCode has a template for answering questions. There is usually a class named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename. For this question, the template is:</p> <pre><code>/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector&lt;TreeNode*&gt; findDuplicateSubtrees(TreeNode* root) { } }; </code></pre> <ul> <li><p><a href="https://leetcode.com/problems/find-duplicate-subtrees/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/find-duplicate-subtrees/solution/" rel="nofollow noreferrer">Solution</a></p> </li> <li><p><a href="https://leetcode.com/problems/find-duplicate-subtrees/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> <li><p><a href="https://en.wikipedia.org/wiki/Tree_(data_structure)" rel="nofollow noreferrer">Tree Data Structure</a></p> </li> </ul>
[]
[ { "body": "<h1>You forgot a <code>std::</code></h1>\n<p>There's a <code>string</code> without <code>std::</code> in front of it. I guess you secretly used <code>using namespace std</code> and/or <code>#include &lt;bits/stdc++.h&gt;</code> before submitting the result. The rest looks fine though.</p>\n<h1>Consider using <code>const TreeNode *</code> everywhere</h1>\n<p>I know the public API of the LeetCode problem explicitly takes non-const pointers to <code>TreeNode</code>, so you shouldn't change this. But consider that your functions, quite rightly so, don't modify the <code>TreeNode</code>s themselves. So you could write <code>const TreeNode *</code> everywhere you now have <code>TreeNode *</code>, and it would still compile correctly. So in real production code, that is what you should do.</p>\n<h1>Don't use <code>this-&gt;</code> unnecessarily</h1>\n<p>In C++, there is rarely a need to write <code>this-&gt;</code>. So in <code>findDuplicateSubtrees()</code>, you can just write <code>serialize(root, nodes_map)</code>.</p>\n<h1>Use range-for and structured bindings where appropriate</h1>\n<p>You can replace the <code>for</code>-loop in <code>findDuplicateSubtrees()</code> using range-<code>for</code> and structured bindings:</p>\n<pre><code>for (auto &amp;[serialization, nodes]: nodes_map) {\n if (nodes.size() &gt; 1) {\n duplicates.push_back(nodes[0]);\n }\n}\n</code></pre>\n<h1>Consider using a binary serialization format</h1>\n<p>There are many ways you could serialize trees. Making human-readable strings has some advantages: it is easy to reason about, and it is nice when having to put them in textual formats like XML or JSON files. But it can be inefficient to convert values to strings. In your case, you are only using the serialization internally, so a binary format might be more efficient.</p>\n<p>In the case of trees of integers, an obvious representation is just a vector of <code>int</code>s. However, a node might have only one child, and you somehow have to encode that as well. You could use a <code>std::optional&lt;int&gt;</code>, and use <code>std::nullopt</code> to represent an unpopulated leaf node. The serialization format would then be:</p>\n<pre><code>std::vector&lt;std::optional&lt;int&gt;&gt; serialization;\n</code></pre>\n<p>The serialization function would then look like:</p>\n<pre><code>std::vector&lt;std::optional&lt;int&gt;&gt; serialize(TreeNode *node, std::unordered_map&lt;std::string, std::vector&lt;TreeNode *&gt;&gt; &amp;nodes_map) {\n if (!node) {\n return {std::nullopt};\n }\n\n auto left = serialize(node-&gt;left, nodes_map);\n auto right = serialize(nodes-&gt;right, nodes_map);\n left.append(node-&gt;val);\n left.insert(left.end(), right.begin(), right.end()); // append right\n return left;\n}\n</code></pre>\n<p>For the LeetCode problem, it's not worth doing this though; the algorithmic complexity is the same, and the string representation is smaller for trees with small values. Also, you can not use a <code>std::unordered_map</code> anymore for <code>nodes_map</code>, unless you write a custom hash function. You could use a <code>std::map</code> though, since optionals and vectors have well-defined ordering.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T20:47:58.297", "Id": "244811", "ParentId": "244799", "Score": "2" } } ]
{ "AcceptedAnswerId": "244811", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T18:06:11.023", "Id": "244799", "Score": "0", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 652: Find Duplicate Subtrees" }
244799
<p>I made a program in Java that asks for the student's name, course, and grades. After the required text inputs are filled, the program will then show the result. If the student passed, the program will show &quot;PASSED&quot;; if the student is failing, the program will show &quot;ACADEMIC WARNING&quot;; if the student failed, the program will show &quot;FAILED&quot;.</p> <p>So this is the code:</p> <pre><code>/* * Java Grades by fosionef */ import javax.swing.JOptionPane; import java.util.Scanner; public class JavaGrades { public static void main(String[] args) { getStudentName(); getStudentCourse(); getGrades(); } // get student name public static void getStudentName() { Scanner input = new Scanner(System.in); String name = JOptionPane.showInputDialog(null,&quot;Input Name: &quot;); //String name = input.nextLine(); JOptionPane.showMessageDialog(null,&quot;Name: &quot; + name.toUpperCase()); } // get student course public static void getStudentCourse() { Scanner input = new Scanner(System.in); String course = JOptionPane.showInputDialog(null,&quot;Input Course: &quot;); //String course = input.nextLine(); JOptionPane.showMessageDialog(null,&quot;Course: &quot; + course.toUpperCase()); } // get student grades public static void getGrades() { Scanner input = new Scanner(System.in); double grades = Double.parseDouble(JOptionPane.showInputDialog(null,&quot;Input grades: &quot;)); //double grades = input.nextDouble(); if(grades == 90 || grades &gt;= 80) { JOptionPane.showMessageDialog(null,grades + &quot;: PASSED!&quot;); }else if(grades == 79 || grades &gt;= 75) { JOptionPane.showMessageDialog(null, grades + &quot;: ACADEMIC WARNING!&quot;); }else if(grades &lt;= 74) { JOptionPane.showMessageDialog(null,grades + &quot;: FAILED!&quot;); }else{ JOptionPane.showMessageDialog(null, &quot;Please input the required&quot;); } } } </code></pre> <p>How was the code? I am looking forward to corrections and suggestions. That way I can improve my coding skills. Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T19:28:09.620", "Id": "480622", "Score": "0", "body": "Please do not change the code after the code has been review, once the code has been received everyone needs to look at the same code, here are the [site guidelines on this](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<h1>Reduce code repetition / redundant checks</h1>\n<p>Your <code>if</code> statements are redundant. If <code>grade = 90</code>, it already satisfies the <code>grade &gt;= 80</code>, so just use that. No need to check if it equals <code>90</code> exactly because that's already covered.</p>\n<p>Instead of having four different lines where you show a message dialog, have a string that you assign the message to and print that at the end? Something like this:</p>\n<pre><code>String message;\nif (grades &gt;= 80) {\n message = grades + &quot;: Passed!&quot;;\n} else if (grades &gt;= 75) {\n message = grades + &quot;: Academic Warning!&quot;;\n} else {\n message = grades + &quot;: Failed!&quot;;\n}\nJOptionPage.showMessageDialog(null, message);\n</code></pre>\n<h1>Reduce unused code</h1>\n<p>You created a <code>Scanner</code> in all of your functions, but never use them. I'd remove them for code clarity.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T19:40:19.480", "Id": "480623", "Score": "0", "body": "@RolandIllig Wrote this while working so it was more of a rough draft than anything. And yeah working with python for so long then reviewing a java project caused a few mistakes lol." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T06:55:50.653", "Id": "480649", "Score": "0", "body": "The last \"else if\" should not have the \"if\". The fact that `(grades < 75)` is clear from the former two ifs failing, and the reader does not have to ask himself whether there's a case that has not been covered." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T18:20:34.760", "Id": "244804", "ParentId": "244800", "Score": "5" } }, { "body": "<p>In addition to @Linny's answer, I can comment on the following topics:</p>\n<ol>\n<li><p>Use correct method names. <code>getGrades</code> method gets grade input and displays student's status. You should name it accordingly. Actually, your <code>getGrades</code> method does <strong>two</strong> different things which is a violation of <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>. Dividing it into two methods such as <code>getGrades</code> and <code>displayResult</code> could be a better solution.</p>\n</li>\n<li><p>Try to handle exceptions. While getting grade input, you tried to cast it to double. However, user input might not be converted to double (For example: supply 'a' as input) after which <code>NumberFormatException</code> is thrown. You should not ignore such errors/exceptions.</p>\n</li>\n<li><p>Avoid writing duplicate code. <code>getStudentName</code> and <code>getStudentCourse</code> methods are doing almost the same thing. Defining a common method for this purpose can reduce code repetition.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T22:54:27.480", "Id": "480635", "Score": "2", "body": "A \"magic\" number that can be readily understood from the context is in no way magic, it is just a number. And there is no rule against using numbers in code. If anything, the source of these numbers should be mentioned in the code. Using constants only does harm in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T06:12:12.370", "Id": "480648", "Score": "0", "body": "I agree with you that using constants might be overkill in this case. The answer is edited accordingly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T21:01:59.983", "Id": "244812", "ParentId": "244800", "Score": "2" } } ]
{ "AcceptedAnswerId": "244804", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T18:09:55.350", "Id": "244800", "Score": "2", "Tags": [ "java" ], "Title": "Determine if the student has passing grades" }
244800
<p>I'm using Telegram API and I've different methods which returns different type of information like this:</p> <pre><code>public SendMessage getTextMessage(Long chatId, String text) { return new SendMessage() .enableMarkdown(false) .setChatId(chatId) .setText(text); } public AnswerCallbackQuery getPopUpAnswer(String callbackId, String text) { return new AnswerCallbackQuery() .setCallbackQueryId(callbackId) .setText(text) .setShowAlert(true); } public EditMessageText getEditedMessage(Long chatId, Integer messageId, String text){ return new EditMessageText() .setChatId(chatId) .setMessageId(messageId) .setText(text); } public SendPhoto getPhotoMessage(Long chatId, GooglePlayGame game) { return new SendPhoto().setChatId(chatId) .setPhoto(game.getPictureURL()) .setCaption(game.toString()); } </code></pre> <p>They have one parent <code>PartialBotApiMethod</code>. In main method I handle and execute (send) them:</p> <pre><code>PartialBotApiMethod&lt;?&gt; responseToUser = updateReceiver.handleUpdate(update); try { execute(responseToUser); //error } catch (TelegramApiException e){ e.printStackTrace(); } </code></pre> <p>But I can't execute PartialBotApiMethod object, only BotApiMethod and their subs. <code>SendPhoto</code> is not in one hierarchy with others, that's why I can't put SendPhoto result to BotApiMethod type variable. And I can't cast like this:</p> <pre><code>try { execute((BotApiMethod)responseToUser); } catch (TelegramApiException e){ e.printStackTrace(); } </code></pre> <p>Because SendPhoto doesn't extends BotApiMethod and I'll give a ClassCastEx.</p> <p>So I gonna use instanceof and cast &quot;personally&quot;:</p> <pre><code>PartialBotApiMethod&lt;?&gt; responseToUser = updateReceiver.handleUpdate(update); if (responseToUser instanceof SendMessage) { try { execute((SendMessage)responseToUser); } catch (TelegramApiException e) { e.printStackTrace(); } } else if (responseToUser instanceof SendPhoto) { try { execute((SendPhoto) responseToUser); } catch (TelegramApiException e) { e.printStackTrace(); } } else if (responseToUser instanceof AnswerCallbackQuery) { try { execute((AnswerCallbackQuery)responseToUser); } catch (TelegramApiException e) { e.printStackTrace(); } } else if (responseToUser instanceof EditMessageText) { try { execute((EditMessageText)responseToUser); } catch (TelegramApiException e) { e.printStackTrace(); } } </code></pre> <p>Do I've better options or just stay with instanceof?</p> <p>Can I replace instanceof if I cannot use a common interface (third pary API)?</p> <p><strong>UPDATE</strong></p> <p><code>updateReceiver.handleUpdate()</code></p> <pre><code>public PartialBotApiMethod handleUpdate(Update update) { if (updateHasTextMessage(update)){ try { return processInputMessage(update.getMessage()); } catch (NotSupportedChatCommandException e) { return replyMessageService.getTextMessage(update.getMessage().getChatId(), &quot;Not available&quot;); } } else if (updateHasCallbackQuery(update)) { return callbackQueryHandler.handleCallbackQuery(update.getCallbackQuery()); } else { return replyMessageService.getTextMessage(update.getMessage().getChatId(), &quot;Can't handle&quot;); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T22:38:44.570", "Id": "480634", "Score": "1", "body": "Please show `updateReceiver.handleUpdate`. Is it an API method or one you wrote?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T09:36:06.687", "Id": "480655", "Score": "0", "body": "It's my own method." } ]
[ { "body": "<p>I'm not sure if there is enough context for me to fully understand the restrictions you are wporking with but I will try anyway... 25 years ago an elder university student half-jokingly taught me that the solution to any problem is always to &quot;add another layer of indirection.&quot; In this case, split <code>handleUpdate</code> so that each message type has their own handler object and place the type specific request handling into those classes. Furthermore, separate each type specific response handler into their own class (to maintain <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>) and <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">inject that dependency</a> to each update handler.</p>\n<p>I.e. move type specific handling to the module where the type is still known. The function of the instanceof-block you want to get rid of will now effectively be moved to the if-block in the <code>handleUpdate</code> method and you don't need to repeat it again in the response handling code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-29T06:43:09.730", "Id": "260150", "ParentId": "244801", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T18:12:29.287", "Id": "244801", "Score": "1", "Tags": [ "java", "object-oriented", "telegram" ], "Title": "Casting calls with the same parent class" }
244801
<p>Update:</p> <p>This is an older version of the question/script. The new version can be found here: <a href="https://codereview.stackexchange.com/questions/245073/part-2-create-or-update-record-via-http-request?noredirect=1#comment481239_245073">Part 2: Create or update record via HTTP request</a></p> <hr /> <p>I have an <a href="https://codereview.stackexchange.com/questions/244736/part-2-send-http-request-for-each-row-in-excel-table/244756">external system</a> that sends an HTTP request to a Jython script (in IBM's <a href="https://www.ibm.com/ca-en/marketplace/maximo" rel="nofollow noreferrer">Maximo Asset Management</a> platform).</p> <p>The Jython 2.7.0 script does this:</p> <ol> <li>Accepts an HTTP request: <code>http://server:port/maximo/oslc/script/CREATEWO?_lid=wilson&amp;_lpwd=wilson&amp;f_wonum=LWO0382&amp;f_description=LEGACY WO&amp;f_classstructureid=1666&amp;f_status=APPR&amp;f_wopriority=1&amp;f_assetnum=LA1234&amp;f_worktype=CM</code></li> <li>Loops through parameters: <ul> <li>Searches for parameters that are prefixed with <code>f_</code> (<em>'f'</em> is for field-value)</li> <li>Puts the parameters in a list</li> <li>Removes the prefix from the list values (so that the parameter names match the database field names).</li> </ul> </li> <li>Updates or creates records via the parameters in the list: <ul> <li>If there is an existing record in the system with the same work order number, then the script updates the exiting record with the parameter values from the list.</li> <li>If there isn't an existing record, then a new record is created (again, from the parameter values from the list).</li> </ul> </li> <li>Finishes by returning a message to the external system (message: updated, created, or other (aka an error)).</li> </ol> <p>Can the script be improved?</p> <hr /> <pre><code>from psdi.mbo import SqlFormat from psdi.server import MXServer from psdi.mbo import MboSet params = list( param for param in request.getQueryParams() if param.startswith('f_') ) paramdict={} resp='' for p in params: paramdict[p[2:]]=request.getQueryParam(p) woset = MXServer.getMXServer().getMboSet(&quot;workorder&quot;,request.getUserInfo()) #Prevents SQL injection sqf = SqlFormat(&quot;wonum=:1&quot;) sqf.setObject(1,&quot;WORKORDER&quot;,&quot;WONUM&quot;,request.getQueryParam(&quot;f_wonum&quot;)) woset.setWhere(sqf.format()) woset.reset() woMbo = woset.moveFirst() if woMbo is not None: for k,v in paramdict.items(): woMbo.setValue(k,v,2L) resp = 'Updated workorder ' + request.getQueryParam(&quot;f_wonum&quot;) woset.save() woset.clear() woset.close() else: woMbo=woset.add() for k,v in paramdict.items(): woMbo.setValue(k,v,2L) resp = 'Created workorder ' + request.getQueryParam(&quot;f_wonum&quot;) woset.save() woset.clear() woset.close() responseBody = resp </code></pre> <hr /> <p><sup><em>Note 1: Previously, there was an SQL injection vulnerability in the code. This issue has been resolved via the <a href="https://developer.ibm.com/static/site-id/155/maximodev/7609/maximocore/businessobjects/psdi/mbo/SqlFormat.html" rel="nofollow noreferrer">SQLFormat java class</a>. The code has been updated.</em></sup></p> <p><sup><em>Note 2: Unfortunately, I'm <strong>not</strong> able to import Python 2.7.0 libraries into my Jython implementation. In fact, I don't even have access to all of the standard python libraries.</em></sup></p> <p><sup><em>Note 3: The acronym 'MBO' stands for 'Master Business Object' (it's an IBM thing). For the purpose of this question, a Master Business Object can be thought of as a work order <strong>record</strong>. Additionally, the <a href="https://stackoverflow.com/questions/59446491/maximo-what-is-the-purpose-of-maxvars">constant</a> <em><strong>2L</strong></em> tells the system to override any MBO rules/constraints.</em> </sup></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T11:30:32.197", "Id": "480781", "Score": "1", "body": "You should read: [Preventing SQL Injection Attacks With Python](https://realpython.com/prevent-python-sql-injection/). If you cannot use the sql library from the article then I would Google: \"Regex to Prevent SQL Injection\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T11:32:07.427", "Id": "480783", "Score": "0", "body": "Ensuring that `f_wonum` `isNumeric()` will prevent the SQL attacks for this script, assuming that `f_wonum` is a number." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T15:14:09.883", "Id": "480809", "Score": "0", "body": "@TinMan Thanks. Actually, `f_wonum` is not a number. What I've done is utilized the [SQLFormat Java class](https://developer.ibm.com/static/site-id/155/maximodev/7609/maximocore/businessobjects/psdi/mbo/SqlFormat.html) for this. I've updated *Note 1* in the question. Cheers!" } ]
[ { "body": "<blockquote>\n<p>Can the script be improved?</p>\n</blockquote>\n<p>Jython is somewhat of a horror show, so improvements are limited but still possible.</p>\n<h2>List comprehensions</h2>\n<pre><code>params = list( param for param in request.getQueryParams() if param.startswith('f_') )\n</code></pre>\n<p>can be</p>\n<pre><code>params = [\n param for param in request.getQueryParams()\n if param.startswith('f_')\n]\n</code></pre>\n<h2>Dict comprehensions</h2>\n<p>This just <a href=\"https://www.python.org/dev/peps/pep-0274/#implementation\" rel=\"nofollow noreferrer\">squeaked into Python 2.7</a>:</p>\n<pre><code>paramdict = {\n p[2:]: request.getQueryParam(p)\n for p in params\n}\n</code></pre>\n<h2>Factor out common code</h2>\n<p>Factor out common code from these blocks:</p>\n<pre><code>if woMbo is not None:\n for k,v in paramdict.items():\n woMbo.setValue(k,v,2L)\n resp = 'Updated workorder ' + request.getQueryParam(&quot;f_wonum&quot;)\n woset.save()\n woset.clear()\n woset.close()\nelse:\n woMbo=woset.add()\n for k,v in paramdict.items():\n woMbo.setValue(k,v,2L)\n resp = 'Created workorder ' + request.getQueryParam(&quot;f_wonum&quot;)\n woset.save()\n woset.clear()\n woset.close()\n</code></pre>\n<p>For example,</p>\n<pre><code>if woMbo is None:\n woMbo=woset.add()\n verb = 'Created'\nelse:\n verb = 'Updated'\n\nfor k,v in paramdict.items():\n woMbo.setValue(k,v,2L)\nresp = verb + ' workorder ' + request.getQueryParam(&quot;f_wonum&quot;)\nwoset.save()\nwoset.clear()\nwoset.close()\n</code></pre>\n<h2>Guaranteed closure</h2>\n<p>Wrap your code in a <code>try</code>/<code>finally</code>:</p>\n<pre><code>woset = MXServer.getMXServer().getMboSet(&quot;workorder&quot;,request.getUserInfo())\ntry:\n # ...\nfinally:\n woset.close()\n</code></pre>\n<h2>Named constants</h2>\n<blockquote>\n<p>the constant <code>2L</code> tells the system to override any MBO rules/constraints</p>\n</blockquote>\n<p>Fine; so it should get first-class treatment:</p>\n<pre><code>IGNORE_RULES = 2L\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T16:27:11.470", "Id": "244889", "ParentId": "244803", "Score": "5" } } ]
{ "AcceptedAnswerId": "244889", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T18:17:03.110", "Id": "244803", "Score": "5", "Tags": [ "python", "python-2.x", "http", "jython" ], "Title": "Part 1: Create or update record via HTTP request" }
244803
<p>I am currently working on a project and very recently came across Vuejs. I used it to create a dynamic form on my frontend, however, the approach I took does not seem right to me. Could someone take a look and provide some feedback?</p> <pre><code>var app = new Vue({ el: '.directionsContainer', data: { directions: [ { direction: '' } ] }, methods: { addDirectionForm: function(){ this.directions.push({ direction: '' }) }, deleteDirectionForm: function(directionIndex){ if(index != 0) this.directions.splice(directionIndex, 1) } } }) var app = new Vue({ el: '.ingredientsContainer', data: { ingredients: [ { ingredient: '' } ] }, methods: { addIngredientForm: function(){ this.ingredients.push({ ingredient: '' }) }, deleteIngredientForm: function(ingredientIndex){ if(index != 0) this.ingredients.splice(ingredientIndex, 1) } } }) </code></pre> <p>Thanks for any help.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T06:07:21.427", "Id": "480647", "Score": "1", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>I'm not familiar with vue.js, but perhaps you could expand upon what &amp; why this doesn't seem right to you. These look to be two discrete components with functions that <em>look</em> similar but because of the simplicity of them I can't say it's <em>actual</em> code duplication.</p>\n<p>I have only a couple significant comments about each deleteX functions</p>\n<pre><code>deleteDirectionForm: function(directionIndex){\n if(index != 0)\n this.directions.splice(directionIndex, 1)\n}\n...\ndeleteIngredientForm: function(ingredientIndex){\n if(index != 0)\n this.ingredients.splice(ingredientIndex, 1)\n}\n</code></pre>\n<ol>\n<li><code>index</code> looks to be undefined. Perhaps this is a case where you defined one function, copy/pasted it to the second component, then updated names and just missed it. Maybe it <em>is</em> defined somewhere higher up in scope. I will assume you intended this to be one of the function index arguments.</li>\n<li>Uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness\" rel=\"nofollow noreferrer\">&quot;==&quot; versus &quot;===&quot;</a> The double equals (<code>==</code>) will perform a type conversion when comparing two things, i.e. <code>&quot;5&quot; == 5 // true</code> whereas triple equals (<code>===</code>) won't do the type conversion, so <code>&quot;5&quot; === 5 // false</code>. The index is almost certainly going to be a number so you should use <code>===</code>. In fact, you should very nearly <em><strong>always</strong></em> use <code>===</code> when doing comparisons unless you have a compelling reason not to.</li>\n</ol>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log('5' == 5); // true\nconsole.log('5' === 5); // false</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ol start=\"3\">\n<li>Javascript variables have a sense of &quot;<a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Truthy\" rel=\"nofollow noreferrer\">truthy</a>&quot; &amp; &quot;<a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Falsy\" rel=\"nofollow noreferrer\">falsey</a>&quot;, and all values are considered truthy unless they are one of the following: <code>0</code>, <code>-0</code>, <code>&quot;&quot;</code>, <code>null</code>, <code>undefined</code> and <code>NaN</code>. All non-zero integer values are truthy, so when using as condition tests you can simplify the expression.</li>\n</ol>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const directionIndex = 0;\nconst ingredientIndex = 5;\n\nif (directionIndex) {\n console.log('do direction stuff');\n}\n\nif (ingredientIndex) {\n console.log('do ingredient stuff');\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Suggested updated functions:</p>\n<pre><code>deleteDirectionForm: function(directionIndex) {\n if (directionIndex)\n this.directions.splice(directionIndex, 1)\n}\n...\ndeleteIngredientForm: function(ingredientIndex) {\n if (ingredientIndex)\n this.ingredients.splice(ingredientIndex, 1)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T00:03:12.937", "Id": "480744", "Score": "0", "body": "All your comments were quite helpful and clarified a lot! The reason I felt the code was \"duplicated' because of the similarities between both chunks of code. It is my first time using Vuejs so I am unsure if there is a way to combine both those chunks of code into one segment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T02:51:08.483", "Id": "480748", "Score": "0", "body": "@HossamAlsheikh Yeah, I had considered the same. To combine them into a single function you'd need to change the signature to take the array, in addition to the index, to operate on as well, something like `function(arr, index) { if (index) arr.splice(index, 1); }`. As I said though, I'm completely unfamiliar with vue.js and have no idea if this would match what the `Vue` constructor would accept as an option object for each component." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T02:07:59.760", "Id": "480872", "Score": "0", "body": "I see ok. Thank you very much." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T04:30:25.650", "Id": "244819", "ParentId": "244808", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T20:17:26.693", "Id": "244808", "Score": "-3", "Tags": [ "javascript", "vue.js" ], "Title": "Is there a means to combine the similar chunks of Vuejs code shown below?" }
244808
<p>Follow up to my question here: <a href="https://codereview.stackexchange.com/questions/244089/constexpr-circular-queue">Constexpr circular queue</a> . I've taken the time to fix the many problems pointed out there and am asking for any tips/corrections for the new version below.</p> <p>The queue will work with non-trivial types in non-constexpr contexts. For types that are trivially copy assignable and destructible, it works with constexpr contexts.</p> <p>Code is by me and posted here: <a href="https://github.com/SteveZhang1999-SZ/CircularQueue/blob/master/circularQueue.hpp" rel="nofollow noreferrer">https://github.com/SteveZhang1999-SZ/CircularQueue/blob/master/circularQueue.hpp</a></p> <p><strong>Changes:</strong></p> <p>Idxtype must be an integral type so unlike before with enable_if, the new code enforces this with a static_assert.</p> <p>forConstexprCtor is now an empty class instead of a bool since the former has a no-op construction.</p> <p>The union Cell will change the active member by either constructing a Cell with the desired active member and assigning it or through placement new.</p> <p>In the assignment methods, the old active elements are destroyed if either std::is_trivially_copy_assignable::value and std::is_trivially_destructible::value are false, and the only elements in the other queue that are copied are the ones with value as the Cell's active member.</p> <p>The (Args&amp;&amp;... theList) constructor is no longer preferred over the default empty constructor should a circular queue be constructed with zero arguments.</p> <p>When inserting elements, users may use the full() method to check if the queue is full.</p> <p><strong>Changes not made</strong></p> <p>The Idxtypes are still declared on one line. Personally, I think putting them all in one line is neater and this shouldn't introduce errors since Idxtype will be something simple like shorts or longs.</p> <p>Direct construction for the member named value remains. This is necessary so I can construct a union with value as the active member initially, then assign it to another union so that the end result is that the assigned-to union has value as the active member now (Which is doable in constexpr contexts).</p> <pre><code>#ifndef CIRCULARQUEUEHPP #define CIRCULARQUEUEHPP #include &lt;cstddef&gt; #include &lt;new&gt; //For placement new #include &lt;type_traits&gt; template&lt;class T, bool B&gt; union Cell;//bool B == std::is_trivially_destructible&lt;T&gt;::value template&lt;class T&gt; union Cell&lt;T, true&gt;{ class emptyClass{} forConstexprCtor; T value; //Initializes forConstexprCtor because constexpr union constructors must initialize a member constexpr Cell() : forConstexprCtor{} {} //Initializes value with the provided parameter arguments template&lt;typename... Args&gt; constexpr Cell(Args&amp;&amp;... args) : value((args)...) {} }; template&lt;class T&gt; union Cell&lt;T, false&gt;{ class emptyClass{} forConstexprCtor; T value; constexpr Cell() : forConstexprCtor{} {} template&lt;typename... Args&gt; constexpr Cell(Args&amp;&amp;... args) : value((args)...) {} ~Cell(){} //Included because Cell&lt;T, false&gt;'s destructor is deleted }; template&lt;class T, std::size_t N, typename Idxtype&gt; struct commonQueueFunctions{ static_assert(std::is_integral&lt;Idxtype&gt;::value, &quot;Idxtype must be an integral type\n&quot;); constexpr bool full() const noexcept {return theSize == N;} //Check if queue is full constexpr bool empty() const noexcept {return !theSize;} //Check if queue is empty constexpr Idxtype size() const noexcept {return theSize;} //Returns the queue's current size //Returns the max number of elements the queue may hold constexpr std::size_t capacity() const noexcept {return N;} //Returns the element next to be popped. Undefined behavior if queue is empty constexpr const T&amp; front() const {return theArray[head].value;} constexpr T&amp; front() {return theArray[head].value;} //Returns the element last to be popped. Undefined behavior if queue is empty constexpr const T&amp; back() const {return theArray[tail - 1].value;} constexpr T&amp; back() {return theArray[tail - 1].value;} protected: Idxtype head{0}, tail{0}, theSize{0}; Cell&lt;T, std::is_trivially_destructible&lt;T&gt;::value&gt; theArray[N]; constexpr void clear(){ //Destroys value in the queue when value is the active member if(this-&gt;head &gt; this-&gt;tail|| (this-&gt;head == this-&gt;tail &amp;&amp; this-&gt;theSize == N)){ for(; this-&gt;head &lt; N; ++this-&gt;head){ this-&gt;theArray[this-&gt;head].value.~T(); } this-&gt;head = 0; } for(; this-&gt;head &lt; this-&gt;tail; ++this-&gt;head){ this-&gt;theArray[this-&gt;head].value.~T(); } } constexpr commonQueueFunctions() = default; constexpr commonQueueFunctions(const commonQueueFunctions&amp; other) : head{other.head}, tail{other.tail}, theSize(other.theSize){ //Copy constructor std::size_t originalHead(other.head); //If other is full, there's a chance that other.head == other.tail if(other.head &gt; other.tail || (other.head == other.tail &amp;&amp; other.theSize == N)){ for(; originalHead &lt; N; ++originalHead){ if constexpr(std::is_trivially_copy_assignable&lt;T&gt;::value &amp;&amp; std::is_trivially_destructible&lt;T&gt;::value){ theArray[originalHead] = other.theArray[originalHead]; } else { new(&amp;theArray[originalHead].value)T(other.theArray[originalHead].value); } } originalHead = 0; } for(; originalHead &lt; other.tail; ++originalHead){ if constexpr(std::is_trivially_copy_assignable&lt;T&gt;::value &amp;&amp; std::is_trivially_destructible&lt;T&gt;::value){ theArray[originalHead] = other.theArray[originalHead]; } else { new(&amp;theArray[originalHead].value)T(other.theArray[originalHead].value); } } } constexpr commonQueueFunctions(commonQueueFunctions&amp;&amp; other) : head{other.head}, tail{std::move(other.tail)}, theSize(std::move(other.theSize)){ //Move constructor std::size_t originalHead(std::move(other.head)); if(other.head &gt; other.tail || (other.head == other.tail &amp;&amp; other.theSize == N)){ for(; originalHead &lt; N; ++originalHead){ if constexpr(std::is_trivially_copy_assignable&lt;T&gt;::value &amp;&amp; std::is_trivially_destructible&lt;T&gt;::value){ theArray[originalHead] = std::move(other.theArray[originalHead]); } else { new(&amp;theArray[originalHead].value)T(std::move(other.theArray[originalHead].value)); } } originalHead = 0; } for(; originalHead &lt; other.tail; ++originalHead){ if constexpr(std::is_trivially_copy_assignable&lt;T&gt;::value &amp;&amp; std::is_trivially_destructible&lt;T&gt;::value){ theArray[originalHead] = std::move(other.theArray[originalHead]); } else { new(&amp;theArray[originalHead].value)T(std::move(other.theArray[originalHead].value)); } } } constexpr commonQueueFunctions&amp; operator=(const commonQueueFunctions&amp; other){//Copy assignment std::size_t originalHead(head = other.head); if constexpr((std::is_trivially_copy_assignable&lt;T&gt;::value &amp;&amp; std::is_trivially_destructible&lt;T&gt;::value) == false){ clear(); } if(other.head &gt; other.tail || (other.head == other.tail &amp;&amp; other.theSize == N)){ for(; originalHead &lt; N; ++originalHead){ if constexpr(std::is_trivially_copy_assignable&lt;T&gt;::value &amp;&amp; std::is_trivially_destructible&lt;T&gt;::value){ theArray[originalHead] = other.theArray[originalHead]; } else { new(&amp;theArray[originalHead].value)T(other.theArray[originalHead].value); } } originalHead = 0; } for(; originalHead &lt; other.tail; ++originalHead){ if constexpr(std::is_trivially_copy_assignable&lt;T&gt;::value &amp;&amp; std::is_trivially_destructible&lt;T&gt;::value){ theArray[originalHead] = other.theArray[originalHead]; } else { new(&amp;theArray[originalHead].value)T(other.theArray[originalHead].value); } } tail = other.tail; theSize = other.theSize; return *this; } constexpr commonQueueFunctions&amp; operator=(commonQueueFunctions&amp;&amp; other){ //Move assignment std::size_t originalHead(head = other.head); if constexpr((std::is_trivially_copy_assignable&lt;T&gt;::value &amp;&amp; std::is_trivially_destructible&lt;T&gt;::value) == false){ clear(); } if(other.head &gt; other.tail || (other.head == other.tail &amp;&amp; other.theSize == N)){ for(; originalHead &lt; N; ++originalHead){ if constexpr(std::is_trivially_copy_assignable&lt;T&gt;::value &amp;&amp; std::is_trivially_destructible&lt;T&gt;::value){ theArray[originalHead] = std::move(other.theArray[originalHead]); } else { new(&amp;theArray[originalHead].value)T(std::move(other.theArray[originalHead].value)); } } originalHead = 0; } for(; originalHead &lt; other.tail; ++originalHead){ if constexpr(std::is_trivially_copy_assignable&lt;T&gt;::value &amp;&amp; std::is_trivially_destructible&lt;T&gt;::value){ theArray[originalHead] = std::move(other.theArray[originalHead]); } else { new(&amp;theArray[originalHead].value)T(std::move(other.theArray[originalHead].value)); } } tail = std::move(other.tail); theSize = std::move(other.theSize); return *this; } template&lt;typename... Args&gt; //Constructor which accepts arguments to construct theArray constexpr commonQueueFunctions(std::size_t theHead, std::size_t theTail, std::size_t paramSize, Args&amp;&amp;... theList) : head(theHead), tail(theTail), theSize(paramSize),theArray{(theList)...}{} }; template&lt;class T, std::size_t N, bool B, typename Idxtype&gt; struct theQueue; template&lt;class T, std::size_t N, typename Idxtype&gt; struct theQueue&lt;T,N, true, Idxtype&gt; : public commonQueueFunctions&lt;T, N, Idxtype&gt;{ constexpr theQueue() = default; //Default constructor //Constructor which accepts arguments to construct theArray template&lt;typename... Args, typename = typename std::enable_if&lt;(... &amp;&amp; std::is_constructible_v&lt;T,Args&gt;)&gt;::type &gt; explicit constexpr theQueue(Args&amp;&amp;... theList) : commonQueueFunctions&lt;T, N, Idxtype&gt;(0, sizeof...(theList), sizeof...(theList),std::forward&lt;Args&gt;(theList)...){} constexpr bool push(T theObj){//Pushes the given element value to the end of the queue if(this-&gt;theSize == N){ return false;//queue is full } this-&gt;theArray[(this-&gt;tail == N ? (this-&gt;tail = 0)++ : this-&gt;tail++)] = Cell&lt;T,true&gt;(std::move(theObj)); return ++this-&gt;theSize; //++theSize always &gt; 0. Return true } template&lt;typename ...Args&gt; constexpr bool emplace(Args&amp;&amp;... args){ //Same as push, but the element is constructed in-place if(this-&gt;theSize == N){ return false;//queue is full } this-&gt;theArray[(this-&gt;tail == N ? (this-&gt;tail = 0)++ : this-&gt;tail++)] = Cell&lt;T,true&gt;((args)...); return ++this-&gt;theSize; } constexpr bool pop() noexcept{ //Removes the element at the queue's front if(!this-&gt;theSize) return false; //If it's empty, pop fails (this-&gt;head == N ? this-&gt;head = 0 : ++this-&gt;head); return this-&gt;theSize--;//Even if theSize == 1, theSize-- will &gt; 0 so this returns true. } }; template&lt;class T, std::size_t N, typename Idxtype&gt; struct theQueue&lt;T,N, false, Idxtype&gt; : public commonQueueFunctions&lt;T, N, Idxtype&gt;{ constexpr theQueue() = default; template&lt;typename... Args, typename = typename std::enable_if&lt;(... &amp;&amp; std::is_constructible_v&lt;T,Args&gt;) &gt;::type &gt; explicit constexpr theQueue(Args&amp;&amp;... theList) : commonQueueFunctions&lt;T, N, Idxtype&gt;(0, sizeof...(theList), sizeof...(theList),std::forward&lt;Args&gt;(theList)...) {} constexpr bool push(T theObj){ if(this-&gt;theSize == N){ return false;//queue is full } new(&amp;this-&gt;theArray[(this-&gt;tail == N ? (this-&gt;tail = 0)++ : this-&gt;tail++)].value)T(std::move(theObj)); return ++this-&gt;theSize; //++theSize always &gt; 0. Return true } template&lt;typename ...Args&gt; constexpr bool emplace(Args&amp;&amp;... args){ if(this-&gt;theSize == N){ return false;//queue is full } new(&amp;this-&gt;theArray[(this-&gt;tail == N ? (this-&gt;tail = 0)++ : this-&gt;tail++)].value)T((args)...); return ++this-&gt;theSize; } constexpr bool pop(){ if(!this-&gt;theSize) return false; //If it's empty, pop fails this-&gt;theArray[(this-&gt;head == N ? this-&gt;head = 0 : this-&gt;head++)].value.~T(); return this-&gt;theSize--; } ~theQueue(){ //Destroys every Cell's value where value is the active member this-&gt;clear(); } }; template&lt;class T, std::size_t N, typename Idxtype = std::size_t&gt; using circularQueue = theQueue&lt;T,N,std::is_trivially_destructible&lt;T&gt;::value &amp;&amp; std::is_trivially_copy_assignable&lt;T&gt;::value, Idxtype&gt;; #endif //CIRCULARQUEUEHPP <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h1>Add empty lines and whitespace</h1>\n<p>You hardly use empty lines and sometimes omit spaces around operators, leading to very dense code. This makes it very hard to see the structure in your code. I recommended these rules of thumb:</p>\n<ul>\n<li>Add empty lines between functions and classes.</li>\n<li>Add an empty line before and after every <code>if-then-else</code>-block.</li>\n<li>Add whitespace around binary operators, except:</li>\n<li>Add whitespace after a comma, but not before.</li>\n<li>Add whitespace after a semicolon if another statement or a comment follows.</li>\n</ul>\n<p>Also just avoid having multiple statements on one line. That includes things like:</p>\n<pre><code>if(!this-&gt;theSize) return false;\n</code></pre>\n<p>That should become:</p>\n<pre><code>if(!this-&gt;theSize) {\n return false;\n}\n</code></pre>\n<h1>Don't write <code>this-&gt;</code> unnecessarily</h1>\n<p>In C++ it is usually not necessary to explicitly write <code>this-&gt;</code> inside member functions. However, there are a few cases where it is necessary, such as:</p>\n<ol>\n<li>When you have a local variable in a member function that shadows a member variable. To be able to access the member variable you need to specify <code>this-&gt;</code>.</li>\n<li>When you to pass a pointer or reference to the current object.</li>\n<li>When you are referring to a member function or variable of a templated base class.</li>\n</ol>\n<p>The reason for the latter is <a href=\"https://stackoverflow.com/questions/4643074/why-do-i-have-to-access-template-base-class-members-through-the-this-pointer\">explained in this question</a>.</p>\n<p>It might be tempting to write <code>this-&gt;</code> everywhere, but it does hurt readability. So try to only do it where necessary.</p>\n<h1>Split up complex expressions</h1>\n<p>Similar to the whitespace issue, very complex one-line expressions can be hard to follow. Take for example:</p>\n<pre><code>this-&gt;theArray[(this-&gt;tail == N ? (this-&gt;tail = 0)++ : this-&gt;tail++)] = Cell&lt;T,true&gt;(std::move(theObj));\n</code></pre>\n<p>Part of the complexity is from all the <code>this</code>es, but also because of the ternary expression and the combined assignment and post-increment of <code>tail</code>.\nYou cannot get rid of <code>this-&gt;</code> inside <code>theQueue</code> when referring to members of the base class <code>commonQueueFunctions</code>, however you can minimize it by creating a helper function in the base class to update the tail pointer and return a reference to the next free element in the array for you:</p>\n<pre><code>template&lt;class T, std::size_t N, typename Idxtype&gt;\nstruct commonQueueFunctions {\n ...\n constexpr auto &amp;nextFreeElement() {\n if (tail == N)\n tail == 0;\n return theArray[tail++];\n }\n};\n</code></pre>\n<p>Then inside <code>push()</code> for trivial types, you can write:</p>\n<pre><code>this-&gt;nextFreeElement() = Cell&lt;T, true&gt;(std::move(theObj));\n</code></pre>\n<p>Inside the variant for non-trivial types, you can write:</p>\n<pre><code>new(&amp;this-&gt;nextFreeElement().value) T(std::move(theObj));\n</code></pre>\n<p>You can do something similar for <code>pop()</code>. You can also consider moving the updating of <code>this-&gt;theSize</code> into the base class itself. Basically, move as much as possible into the base class, and only handle the actual differences in the derived class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T22:23:21.320", "Id": "480740", "Score": "0", "body": "Regarding the this->, I noticed that the clear() method didn't need the this-> to refer the variables since it's part of commonQueueFunctions, so I cleaned that up. For the variables in the theQueue<class T, std::size_t N, bool B, typename Idxtype> methods, I think the this-> is mandatory since those variables are inherited from commonQueueFunctions.\nIn my previous submission, everything was in one class, so I knew I didn't need to refer to the variables with this->." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T04:45:55.357", "Id": "480751", "Score": "0", "body": "You don't need `this->` to refer to inherited variables or functions either." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T15:31:10.110", "Id": "480811", "Score": "1", "body": "In a push() method, I replaced one of the this>theSize with theSize, but I got an error saying \"use of undeclared identifier 'theSize'\". In case it's important, this is on Visual Studio Code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:57:09.890", "Id": "480840", "Score": "0", "body": "You're correct, it is actually necessary in the derived class, but not in the base class. I've updated the answer with a short explaination, and a link to another question which has a much more detailed answer about why `this->` is necessary in the derived class." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T19:46:18.617", "Id": "244848", "ParentId": "244813", "Score": "1" } } ]
{ "AcceptedAnswerId": "244848", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T21:44:04.737", "Id": "244813", "Score": "3", "Tags": [ "c++", "performance", "c++17", "queue" ], "Title": "Constexpr circular queue - follow-up #1" }
244813
<p>I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <blockquote> <p>Given a 2D board and a list of words from the dictionary, find all words in the board.</p> <p>Each word must be constructed from letters of sequentially adjacent cell, where &quot;adjacent&quot; cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.</p> <h3>Example:</h3> <pre><code>Input: board = [ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ] words = [&quot;oath&quot;,&quot;pea&quot;,&quot;eat&quot;,&quot;rain&quot;] Output: [&quot;eat&quot;,&quot;oath&quot;] </code></pre> <p>Note:</p> <ul> <li>All inputs are consist of lowercase letters a-z.</li> <li>The values of words are distinct.</li> </ul> </blockquote> <h3>Code</h3> <pre><code>#include &lt;vector&gt; #include &lt;string&gt; #include &lt;set&gt; class Solution { static constexpr unsigned int A_LOWERCASE = 'a'; static constexpr unsigned int ALPHABET_SIZE = 26; private: class TrieNode { public: std::vector&lt;TrieNode *&gt; children; bool is_word; TrieNode() { is_word = false; children = std::vector&lt;TrieNode *&gt;(ALPHABET_SIZE, NULL); } }; class Trie { public: TrieNode *get_parent() { return parent; } Trie(const std::vector&lt;std::string&gt; &amp;words) { parent = new TrieNode(); for (unsigned int index = 0; index &lt; words.size(); index++) { set_word(words[index]); } } void set_word(const std::string &amp;word) { TrieNode *curr = parent; for (unsigned int length = 0; length &lt; word.size(); length++) { unsigned int index = word[length] - A_LOWERCASE; if (curr-&gt;children[index] == NULL) { curr-&gt;children[index] = new TrieNode(); } curr = curr-&gt;children[index]; } curr-&gt;is_word = true; } private: TrieNode *parent; }; public: std::vector&lt;std::string&gt; findWords(std::vector&lt;std::vector&lt;char&gt;&gt; &amp;board, std::vector&lt;std::string&gt; &amp;words) { Trie *trie = new Trie(words); TrieNode *parent = trie-&gt;get_parent(); std::set&lt;std::string&gt; found_words; for (unsigned int row = 0; row &lt; board.size(); row++) { for (unsigned int col = 0; col &lt; board[0].size(); col++) { depth_first_search(board, row, col, parent, &quot;&quot;, found_words); } } std::vector&lt;std::string&gt; structured_found_words; for (const auto found_word : found_words) { structured_found_words.push_back(found_word); } return structured_found_words; } private: static void depth_first_search(std::vector&lt;std::vector&lt;char&gt;&gt; &amp;board, const unsigned int row, const unsigned int col, const TrieNode *parent, std::string word, std::set&lt;std::string&gt; &amp;structured_found_words) { if (row &lt; 0 || row &gt;= board.size() || col &lt; 0 || col &gt;= board[0].size() || board[row][col] == ' ') { return; } if (parent-&gt;children[board[row][col] - A_LOWERCASE] != NULL) { word = word + board[row][col]; parent = parent-&gt;children[board[row][col] - A_LOWERCASE]; if (parent-&gt;is_word) { structured_found_words.insert(word); } char alphabet = board[row][col]; board[row][col] = ' '; depth_first_search(board, row + 1, col, parent, word, structured_found_words); depth_first_search(board, row - 1, col, parent, word, structured_found_words); depth_first_search(board, row, col + 1, parent, word, structured_found_words); depth_first_search(board, row, col - 1, parent, word, structured_found_words); board[row][col] = alphabet; } }; }; </code></pre> <h3>Reference</h3> <p>LeetCode has a template for answering questions. There is usually a class named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename. For this question, the template is:</p> <pre><code>class Solution { public: vector&lt;string&gt; findWords(vector&lt;vector&lt;char&gt;&gt;&amp; board, vector&lt;string&gt;&amp; words) { } }; </code></pre> <ul> <li><p><a href="https://leetcode.com/problems/word-search-ii/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/word-search-ii/solution/" rel="nofollow noreferrer">Solution</a></p> </li> <li><p><a href="https://leetcode.com/problems/word-search-ii/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> <li><p><a href="https://en.wikipedia.org/wiki/Trie" rel="nofollow noreferrer">Trie</a></p> </li> </ul>
[]
[ { "body": "<h1>Avoid defining trivial constants</h1>\n<p>While it is good practice to give some constants that are used throughout the code a nice descriptive name, <code>A_LOWERCASE</code> is a case of a trivial constant where it is actually detrimental to define it. The reason is that <code>A_LOWERCASE</code> describes exactly its value, instead of what the value stands for. If you would call it <code>FIRST_LETTER_OF_THE_ALPHABET</code>, it would be a better name (although obviously a bit too long for comfort). But, everyone already knows that <code>'a'</code> is the first letter. It's as trivial as the numbers 0 and 1, and you wouldn't write:</p>\n<pre><code>static constexpr int ZERO = 0;\nstatic constexpr int ONE = 1;\n\nfor (int i = ZERO; i &lt; ...; i += ONE) {\n ...\n}\n</code></pre>\n<p>Another issue with such constants is that if you ever write <code>constexpr unsigned int A_LOWERCASE = 'b'</code>, the compiler won't complain, the code won't work as expected, and someone reading the code will probably not think that <code>A_LOWERCASE</code> might be anything other than <code>'a'</code> and thus have a hard time finding the issue.</p>\n<h1>Move <code>TrieNode</code> inside <code>Trie</code></h1>\n<p>Since <code>TrieNode</code> is an implementation detail of <code>Trie</code>, it should be moved inside it:</p>\n<pre><code>class Trie {\npublic:\n class Node {\n ...\n };\n\n Node *get_root() {\n return root;\n }\n\n ...\n\nprivate:\n Node *root;\n};\n</code></pre>\n<p>Also note that the parent of a tree is not a node. The correct term to use here is &quot;root&quot;.</p>\n<h1>Use <code>std::array</code> to store trie node children</h1>\n<p>Instead of a fixed size vector, you should use <code>std::array</code>. It avoids a level of indirection:</p>\n<pre><code>class Trie {\n class Node {\n std::array&lt;Node *, 26&gt; children;\n ...\n</code></pre>\n<h1>Prefer using default member initializers</h1>\n<p>This avoids having to write a constructor in some cases, and is especially useful to avoid repeating yourself when a class has multiple constructors. In this case you can write:</p>\n<pre><code>class Trie {\n class Node {\n std::array&lt;Node *, 26&gt; children{};\n bool is_word{false};\n };\n ...\n};\n</code></pre>\n<h1>Avoid <code>new</code> when you can just declare a value</h1>\n<p>In the constructor of <code>Trie</code> you always allocate a new <code>Trie::Node</code>. This is unnecessary, you can just write:</p>\n<pre><code>class Trie {\npublic:\n class Node {...};\n\n Node *get_root() {\n return &amp;root;\n }\n\n ...\nprivate:\n Node root;\n};\n</code></pre>\n<p>Similarly, in <code>findWords()</code>, you can just write:</p>\n<pre><code>std::vector&lt;std::string&gt; findWords(std::vector&lt;std::vector&lt;char&gt;&gt; &amp;board, std::vector&lt;std::string&gt; &amp;words) {\n Trie words;\n ...\n}\n</code></pre>\n<h1>Use <code>std::unique_ptr</code> to manage memory</h1>\n<p>Avoid calling <code>new</code> and <code>delete</code> manually. It is easy to make mistakes and cause a memory leak. I don't see any call to <code>delete</code> in your code! A <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a> will manage memory for you and delete it automatically once it goes out of scope. Here is how to use it:</p>\n<pre><code>class Trie {\n class Node {\n std::array&lt;std::unique_ptr&lt;Node&gt;, 26&gt; children;\n ...\n };\n\n ...\n\n void set_word(const std::string &amp;word) {\n Node *curr = get_root();\n\n for (...) {\n ...\n\n if (!curr-&gt;children[index]) {\n curr-&gt;children[index] = std::make_unique&lt;Node&gt;();\n }\n \n curr = curr-&gt;children[index].get();\n }\n\n curr-&gt;is_word = true;\n }\n\n ...\n};\n</code></pre>\n<h1>Prefer using range-for</h1>\n<p>When iterating over containers (this includes iterating over the characters in a <code>std::string</code>), and you don't need to manipulate the iterator itself but just want to see the values, use a range-for loop. For example in the constructor of <code>Trie</code>:</p>\n<pre><code>Trie(const std::vector&lt;std::string&gt; &amp;words) {\n for (auto &amp;word: words) {\n set_word(word);\n }\n}\n</code></pre>\n<p>And in <code>set_word()</code>:</p>\n<pre><code>for (auto letter: word) {\n unsigned int index = letter - 'a';\n ...\n}\n</code></pre>\n<h1>Simplify return value of <code>findWords()</code></h1>\n<p>Instead of creating a temporary <code>std::vector</code> and copying elements manually from <code>found_words</code>, you can make use of the fact that <code>std::vector</code> has a <a href=\"https://en.cppreference.com/w/cpp/container/vector/vector\" rel=\"nofollow noreferrer\">constructor</a> that can copy elements from another container for you, and use brace-initialization in the <code>return</code> statement:</p>\n<pre><code>std::vector&lt;std::string&gt; findWords(std::vector&lt;std::vector&lt;char&gt;&gt; &amp;board, std::vector&lt;std::string&gt; &amp;words) {\n std::set&lt;std::string&gt; found_words;\n ...\n return {found_words.begin(), found_words.end()};\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T18:05:09.863", "Id": "248828", "ParentId": "244814", "Score": "1" } } ]
{ "AcceptedAnswerId": "248828", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T22:59:19.710", "Id": "244814", "Score": "1", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 212: Word Search II" }
244814
<p>I'm currently writing a small game in Lua, using the Love2d framework. I guess I'm doing it as a practice of sorts, but it did give me the opportunity to write my first pathfinding algorithm. I wrote it based off of a 10 minute Youtube video I saw explaining A*, and luckily it works fine. The pathfind function outputs a table of coordinates that traverse between two points, and it works based off my vague understanding of A*. I've stripped out most of the game code, so it's just the pathfinding function and a skeleton of the board that it traverses. I would love any and all critiques of it, as I'm trying to improve my programming skills. Thank you all for your time!</p> <pre><code>local board = {} local board_width = 12 local board_height = 12 -- initialize board for i=1,board_height do local t = {} for j=1,board_width,1 do t[j] = 0 end board[i] = t end function is_in_bounds(x, y) if x == nil or y == nil then return false end if x &lt; 1 or x &gt; board_width or y &lt; 1 or y &gt; board_height then return false else return true end end function get_tile(x, y) return board[y][x] end function pathfind(from_x, from_y, to_x, to_y) local coord_to_index = function(x, y) return (x - 1) + (y - 1) * board_width + 1 end local index_to_coord = function(i) return ((i - 1) % board_width) + 1, math.floor((i - 1) / board_width) + 1 end local dist = function(x1, y1, x2, y2) -- gets manhattan distance return math.abs(x1 - x2) + math.abs(y1 - y2) end local is_traversable = function(x, y) if is_in_bounds(x, y) and get_tile(x, y) == 0 then return true else return false end end if not is_traversable(to_x, to_y) then -- goal is on an obstacle; return nil return end local open_nodes = {} local open_nodes_count = 1 local closed_nodes = {} open_nodes[coord_to_index(from_x, from_y)] = { -- initialize first node g_cost = 0, h_cost = dist(from_x, from_y, to_x, to_y), come_from = nil } while open_nodes_count &gt; 0 do local current local lowest_f_cost = nil open_nodes_count = -1 --current node is going to be removed; start counting from -1 --find lowest f_cost and make it the current node for index, node in pairs(open_nodes) do if lowest_f_cost == nil or node.g_cost + node.h_cost &lt; lowest_f_cost then lowest_f_cost = node.g_cost + node.h_cost current = index elseif node.g_cost + node.h_cost == lowest_f_cost then -- tiebreaker; if f_costs are the same, get the lowest g_cost if node.h_cost &lt; open_nodes[current].h_cost then lowest_f_cost = node.g_cost + node.h_cost current = index end end open_nodes_count = open_nodes_count + 1 end closed_nodes[current] = open_nodes[current] open_nodes[current] = nil local current_x, current_y = index_to_coord(current) if current_x == to_x and current_y == to_y then -- path found; return the path of nodes local found_path = {} local step_path = current while step_path ~= nil do local point = {} local step_x, step_y = index_to_coord(step_path) point[1] = step_x point[2] = step_y found_path[#found_path + 1] = point step_path = closed_nodes[step_path].come_from end return found_path end for i,neighbor in ipairs({{1,0}, {-1, 0}, {0, 1}, {0, -1}}) do local check_x, check_y = current_x + neighbor[1], current_y + neighbor[2] local check_index = coord_to_index(check_x, check_y) if is_traversable(check_x, check_y) and closed_nodes[check_index] == nil then -- is traversable and not a closed node if open_nodes[check_index] == nil or closed_nodes[current].g_cost + 1 &lt; open_nodes[check_index].g_cost then -- if not open or g_cost can be improved if open_nodes[check_index] == nil then -- increase open_nodes_count if creating a new open node open_nodes_count = open_nodes_count + 1 end open_nodes[check_index] = { g_cost = closed_nodes[current].g_cost + 1, h_cost = dist(check_x, check_y, to_x, to_y), come_from = current } -- the following code is a hacky solution to make the path follow nice straight lines -- prioritize a node if the current node came from the same direction that this neighbor is coming from -- if not, apply a penalty to the g_cost -- is the current node didnt come from anywhere (i.e. is the first in the sequence), prefer horizontal directions -- this probably doesn't do a great job at finding the shortest route, but i think it looks better if closed_nodes[current].come_from ~= nil then local prev_x, prev_y = index_to_coord(current) local prev_x2, prev_y2 = index_to_coord(closed_nodes[current].come_from) if not (math.abs(prev_x - prev_x2) == math.abs(neighbor[1]) and math.abs(prev_y - prev_y2) == math.abs(neighbor[2])) then open_nodes[check_index].g_cost = open_nodes[check_index].g_cost + 0.1 end else if i &gt; 2 then open_nodes[check_index].g_cost = open_nodes[check_index].g_cost + 0.1 end end end end end end end <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>You can always return the condition expression itself instead of using <code>if</code>:</p>\n<pre><code>local is_traversable = function(x, y)\n return is_in_bounds(x, y) and get_tile(x, y) == 0\nend\n</code></pre>\n<p>As a side note, the operator <code>and</code> returns its first argument if it is false; otherwise, it returns its second argument.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-08T17:26:40.047", "Id": "256883", "ParentId": "244816", "Score": "1" } }, { "body": "<p>Having a &quot;global&quot; board (the variable is local, but there can only ever be one in the file) has a high potential for future headache; instead I'd just pass the board as the first argument to the other functions and have a <code>newboard</code> function that creates, initialises and returns a new board. The board's dimensions can be saved inside the board itself, since Lua tables can act as both arrays and objects at the same time.</p>\n<hr />\n<pre class=\"lang-lua prettyprint-override\"><code>function is_in_bounds(x, y)\n if x == nil or y == nil then\n return false\n end\n -- ...\nend\n</code></pre>\n<p>If you're going through the trouble of checking your arguments for <code>nil</code>, you might as well properly type-check them:</p>\n<pre class=\"lang-lua prettyprint-override\"><code>if type(x)==&quot;number&quot; and type(y)==&quot;number&quot; then\n</code></pre>\n<p>or simply</p>\n<pre class=\"lang-lua prettyprint-override\"><code>if tonumber(x) and tonumber(y) then\n</code></pre>\n<hr />\n<p>Declaring the <code>is_traversable</code> function inside the <code>pathfind</code> function is a potential performance problem. In your problem, the algorithm itself will by far outweigh the single function declaration, but you should be aware that you should avoid doing this in functions that a) otherwise run very fast and b) get called very often, as the performance loss will add up in those cases.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-28T08:02:12.033", "Id": "263539", "ParentId": "244816", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-06-30T23:28:55.797", "Id": "244816", "Score": "4", "Tags": [ "pathfinding", "lua", "a-star" ], "Title": "I wrote my first pathfinding algorithm" }
244816
<p>Here is a project that I worked on for a few days in June 2020. Since the algorithm is extremely slow, I looked into methods in order to parallelize operations but did not obtain any satisfactory answers.</p> <p><a href="https://github.com/aaronjohnsabu1999/tk2NN" rel="noreferrer">https://github.com/aaronjohnsabu1999/tk2NN</a></p> <p>The project is a Tkinter implementation of the k-Nearest Neighbor (kNN) algorithm which randomly chooses points and colors based on the user's input for the number of points, the number of labels and the type of distance (Euclidean or Manhattan).</p> <p>Please suggest anything ranging from how to make the algorithm faster to how to make the environment more attractive</p> <p>Here is the <a href="https://github.com/aaronjohnsabu1999/tk2NN/blob/master/main.py" rel="noreferrer">script</a> for the project:</p> <pre><code>import time from PIL import Image from colour import Color from random import random, randint from general import colorPicker, generatePoints from tkinter import * from canvasDev import canvasDetermine HEIGHT = 520 WIDTH = 540 BORDER_XL = 15 BORDER_YL = 15 BORDER_XH = 415 BORDER_YH = 415 numLabels = 3 numPoints = 9 resolution = 1 k = 1 def clearPointSpace(event): global selectPoints selectPoints = [] pointSpace.delete(ALL) def updateInput(event): global numLabels, numPoints, selectPoints, k nLChange = False nPChange = False nKChange = False try: nLChange = not (numLabels == int(FNumL.get())) numLabels = int(FNumL.get()) except Exception: pass try: nPChange = not (numPoints == int(FNumP.get())) numPoints = int(FNumP.get()) except Exception: pass try: nKChange = not (k == int(FKSet.get())) k = int(FKSet.get()) except Exception: pass FNumL.delete(0, END) FNumP.delete(0, END) FKSet.delete(0, END) FNumL.insert(0, str(numLabels)) FNumP.insert(0, str(numPoints)) FKSet.insert(0, str(k)) if nLChange or nPChange: selectPoints = generatePoints(BORDER_XH - BORDER_XL, BORDER_YH - BORDER_YL, numLabels, numPoints) updatePointSpace() def bindButtons(): pointSpace.delete(&quot;all&quot;) updatePointSpace() def updatePointSpace(): (canvas, error) = canvasDetermine(k, distType.get(), BORDER_XH - BORDER_XL, BORDER_YH - BORDER_YL, selectPoints) colors = colorPicker(selectPoints) for y in range(resolution, BORDER_YH - BORDER_YL + resolution, resolution*2): for x in range(resolution, BORDER_XH - BORDER_XL + resolution, resolution*2): try: color = colors[canvas[y][x]] except Exception: color = Color(&quot;#000000&quot;) color.saturation = (color.saturation + 1.0)/2.0 pointSpace.create_rectangle(x - resolution, y - resolution, x + resolution, y + resolution, fill = color) for point in selectPoints: pointX, pointY = point[0] pointSpace.create_rectangle(pointX - resolution*2, pointY - resolution*2, pointX + resolution*2, pointY + resolution*2, fill = colors[point[1]]) base = Tk() base.resizable(width = False, height = False) base.title(&quot;tk2NN&quot;) base.configure(bg = 'grey') base.geometry(str(WIDTH) + &quot;x&quot; + str(HEIGHT)) distType = IntVar() distType.set(1) selectPoints = generatePoints(BORDER_XH - BORDER_XL, BORDER_YH - BORDER_YL, numLabels, numPoints) background_image = PhotoImage(file = './bg.png') background_label = Label(base, image = background_image) background_label.place(x = 0, y = 0, relwidth = 1, relheight = 1) pointSpace = Canvas(base, width = BORDER_XH - BORDER_XL, height = BORDER_YH - BORDER_YL, borderwidth = 4, relief = SUNKEN, background = 'black', cursor = 'dot') pointSpace.grid(row = 0, column = 0, columnspan = 3, padx = (BORDER_XL, 5), pady = (BORDER_YL, 5)) pointSpace.bind(&quot;&lt;Button-2&gt;&quot;, clearPointSpace) updatePointSpace() typeSpace = Frame(base) typeSpace.grid(row = 0, column = 3, rowspan = 2, pady = (5, 5)) chooseEu = Radiobutton(typeSpace, text = &quot;Euclidean&quot;, variable = distType, value = 1, command = bindButtons) chooseEu.pack(anchor = W) chooseMh = Radiobutton(typeSpace, text = &quot;Manhattan&quot;, variable = distType, value = 2, command = bindButtons) chooseMh.pack(anchor = E) def clear_placeholder(event, e): inVal = e.get() if not isinstance(inVal, int): e.delete(0, END) def add_placeholder(event, e, ph): inVal = e.get() try: inVal = int(inVal) e.delete(0, END) e.insert(0, inVal) except Exception: e.delete(0, END) e.insert(0, ph) labelSpace = Frame(base) labelSpace.grid(row = 1, column = 0, columnspan = 2, padx = 25) FNumL = Entry (labelSpace, bg = 'white', bd = 3, width = 12) FNumP = Entry (labelSpace, bg = 'white', bd = 3, width = 12) FKSet = Entry (labelSpace, bg = 'white', bd = 3, width = 7) UpdtB = Button(labelSpace, bg = '#9999FF', activebackground = '#444499', bd = 3, text = &quot;Update&quot;, padx = 3) FNumL.insert(0, &quot;Num of Labels&quot;) FNumP.insert(0, &quot;Num of Points&quot;) FKSet.insert(0, &quot;k-level&quot;) FNumL.pack(side = LEFT) FNumP.pack(side = LEFT) FKSet.pack(side = LEFT) UpdtB.pack(side = LEFT) FNumL.bind(&quot;&lt;FocusIn&gt;&quot;, lambda event: clear_placeholder(event, FNumL)) FNumP.bind(&quot;&lt;FocusIn&gt;&quot;, lambda event: clear_placeholder(event, FNumP)) FKSet.bind(&quot;&lt;FocusIn&gt;&quot;, lambda event: clear_placeholder(event, FKSet)) FNumL.bind(&quot;&lt;FocusOut&gt;&quot;, lambda event: add_placeholder(event, FNumL, &quot;Num of Labels&quot;)) FNumP.bind(&quot;&lt;FocusOut&gt;&quot;, lambda event: add_placeholder(event, FNumP, &quot;Num of Points&quot;)) FKSet.bind(&quot;&lt;FocusOut&gt;&quot;, lambda event: add_placeholder(event, FKSet, &quot;k-level&quot;)) FNumL.bind(&quot;&lt;Return&gt;&quot;, updateInput) UpdtB.bind(&quot;&lt;Button-1&gt;&quot;, updateInput) base.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T04:44:02.690", "Id": "480641", "Score": "2", "body": "Please, include a description of what the code does. Also title should contain the goal accomplished by the code, not your concerns about it. And if you believe that reviewers will \"need to see the whole script\", then include the whole script in your question. Questions are supposed to be self-contained. And if you think there's something about the code that needs explanation, please include the explanation. In current state, your question is going to be \"look-and-leave\" for many potential reviewers, me including. Not bad enough to vote to close, not good enough to even upvote..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T04:49:44.400", "Id": "480642", "Score": "1", "body": "@slepic thanks for the comments. I do wish to post the whole code but it is enormous, at least for the scale of SE questions. I'll do it anyway but let me know if it is huge. I'll reduce it in that case" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T05:02:34.727", "Id": "480643", "Score": "0", "body": "Not long at all. I have yet modified the title. Upvoting now..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T05:04:08.040", "Id": "480644", "Score": "0", "body": "Alright. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T07:03:59.510", "Id": "480650", "Score": "1", "body": "The current code is size-wise no problem at all. Welcome to Code Review!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T03:53:52.403", "Id": "244818", "Score": "5", "Tags": [ "python", "algorithm", "tkinter", "git" ], "Title": "K nearest neighbours algorithm" }
244818
<p>I've started bash scripting recently and currently I'm working on a program that simplifies backuping using <code>rsync</code> . I'd appreciate any feedback on what I've done wrong / what can be improved.</p> <pre><code>#!/bin/bash # Copyright (C) 2020 ##########, e-mail: ################## # saver comes with NO WARRANTY. This program is completely free and you can # redistribute it under the GNU General Public License conditions. # See https://www.gnu.org/licenses/gpl-3.0.txt for more information # saver was made to simplify the process of backuping using rsync. # version 2.2-1 if [[ ! $(id -u) == 0 ]]; then # making sure the progream is executed as root exec sudo $0 &quot;$@&quot; fi for ((i=1; i=i; i++)); do # here input variables of the script are read one by another using the for loop [[ -z ${!i} ]] &amp;&amp; break case ${!i} in \-*) # this is where all the '-' options are case ${!i} in *s*) option=$option&quot;sync&quot; ;;&amp; *d*) rsyncoptions+=(-n) ;;&amp; *r*) rsyncoptions+=(--delete) ;;&amp; *p*) rsyncoptions+=(--progress) ;;&amp; *v*) rsyncoptions+=(-v) ;;&amp; *h*) option=$option&quot;help&quot; ;;&amp; *i*) option=$option&quot;diskinfo&quot; ;; esac ;; *) # here the paths and disks are set if [[ -b ${!i} ]]; then if [[ -z $sp ]]; then sdp=&quot;${!i}&quot; else tdp=&quot;${!i}&quot; fi else if [[ -b /dev/${!i} ]]; then if [[ -z $sp ]]; then sdp=&quot;/dev/${!i}&quot; # sdp = sync disk path else tdp=&quot;/dev/${!i}&quot; # tdp = target disk path fi else if [[ ${!i} == /* ]]; then if [[ -z $sp ]]; then sp=&quot;${!i}&quot; # sp = sync path else tp=&quot;${!i}&quot; # tp = target path fi fi fi fi ;; esac done case $option in sync) # the -s option if [[ ! -e $sp ]]; then # checking if the path to sync from exists echo -e &quot;The path to copy wasn't provided or doesn't exist\nType in 'saver -h' to see the list of commands&quot; logger &quot;saver: The path to copy wasn't provided or doesn't exist&quot; exit fi if [[ -z $tp ]]; then # checking if the target path isn't empty echo -e &quot;The target path wasn't provided\nType in 'saver -h' to see the list of commands&quot; logger &quot;saver: The target path wasn't provided&quot; exit fi fsp=$sp # these stand for the final paths that will be put to the rsync command (final sync path / final target path) ftp=$tp if [[ $sdp ]]; then echo &quot;Unmounting the disk to copy&quot; umount -q $sdp # mounting the sync external disk to a folder that's made echo &quot;Creating /mnt/saverbd&quot; mkdir /mnt/saverbd | grep -q a echo -e &quot;Mounting the disk to copy to /mnt/saverbd\n&quot; mount $sdp /mnt/saverbd fsp=/mnt/saverbd${sp} # updates the final path if it's from an external disk fi if [[ $tdp ]]; then echo &quot;Unmounting the target disk&quot; umount -q $tdp # mounting the target external disk to a folder that's made echo &quot;Creating /mnt/savertd&quot; mkdir /mnt/savertd | grep -q a echo -e &quot;Mounting the target disk to /mnt/savertd\n&quot; mount $tdp /mnt/savertd ftp=/mnt/savertd${tp} # updates the final path if it's from an external disk fi if [[ ! -e $tp ]]; then echo &quot;Creating ${ftp}&quot; mkdir -p $ftp | grep -q a fi echo rsync -aAX &quot;${rsyncoptions[@]}&quot; $fsp --exclude={&quot;/dev/*&quot;,&quot;/proc/*&quot;,&quot;/sys/*&quot;,&quot;/tmp/*&quot;,&quot;/run/*&quot;,&quot;/mnt/*&quot;,&quot;/media/*&quot;,&quot;/lost+found&quot;} $ftp if [[ $sdp ]]; then # unmounting the sync external disk and deleting the mount folder echo -e &quot;\nUnmounting the copied disk&quot; umount -q $sdp echo -e &quot;Deleting /mnt/saverbd\n&quot; rm -rf /mnt/saverbd fi if [[ $tdp ]]; then # unmounting the target external disk and deleting the mount folder echo -e &quot;\nUnmounting the target disk&quot; umount -q $tdp echo -e &quot;Deleting /mnt/savertd\n&quot; rm -rf /mnt/savertd fi ;; diskinfo) lsblk -o NAME,SIZE,MOUNTPOINT,FSTYPE # shows the available disks and partitions ;; help) # the help page echo -e &quot;\n Copyright (C) 2020 ###########, e-mail: ################## Version 2.2-1 \n saver comes with NO WARRANTY. This program is completely free and you\n can redistribute it under the GNU General Public License conditions.\n See https://www.gnu.org/licenses/gpl-3.0.txt for more information \n saver was made to simplify the process of backuping using rsync. \n This program will automaticly exclude these directories from syncing:\n /dev ; /proc ; /sys ; /tmp ; /run ; /mnt ; /media ; /lost+found. When typing in the disk name, you can use the full '/dev/(disk)' or just\n provide the name of the disk. Any disk you mention will be unmounted at the end of the program. \n Usage: \n -s [disk to copy (empty for current disk)] [copied path]\n [target disk (empty for current disk)] [target path] \n Options: \n -s Sync folders -r Delete any other files in the target folder -d Preform a 'dry run', no changes will be made -p Display progress for individual files (useful for large files) -v Display files that are being processed -i Show available disks/partitions -h Show this help\n&quot; ;; *) # in case no valid option is provided echo -e &quot;Invalid option provided\nType in 'saver -h' to see the list of commands&quot; logger saver: &quot;Invalid option provided&quot; ;; esac </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T11:12:08.767", "Id": "480658", "Score": "1", "body": "It does, what I mean by that is if the code I've written can be somehow optimized, if there can be any compatibility issues. I'm new to bash scripting so I tend to make mistakes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T12:41:20.013", "Id": "480669", "Score": "2", "body": "Welcome to Code Review. To increase the odds of receiving answers about your script, it could be better to modify the title of you post to include a brief description of the task implemented by the script." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T13:09:36.347", "Id": "480673", "Score": "1", "body": "As @dariosicily indicated a better title might be `bash backup script`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T13:22:54.187", "Id": "480676", "Score": "0", "body": "I changed the title, but \"bash backup script\" was taken." } ]
[ { "body": "<h1>loop</h1>\n<pre><code>for ((i=1; i=i; i++)); do \n [[ -z ${!i} ]] &amp;&amp; break\n</code></pre>\n<p>you know that <code>$#</code> hold number of argument from command line ?</p>\n<p>you can use</p>\n<pre><code>for ((i=1; i &lt;= $# ; i++)) \n</code></pre>\n<h1>test</h1>\n<pre><code>if [[ ! $(id -u) == 0 ]]\n</code></pre>\n<p>you know about <code>!=</code> ? use</p>\n<pre><code>if [[ $(id -u) != 0 ]]\n</code></pre>\n<h1>mkdir</h1>\n<p>what is the purpose of .. ?</p>\n<pre><code>mkdir /mnt/savertd | grep -q a\n</code></pre>\n<p>Do you want to get rid of <code>&quot;mkdir: cannot create directory ‘/mnt/savertd’: File exists&quot;</code> message ?</p>\n<p>this won't work (message is printed on stderr, while <code>|</code> will collect stdout), use either</p>\n<pre><code>test -d /mnt/savertd || mkdir /mnt/savertd\n</code></pre>\n<p>or</p>\n<pre><code>mkdir -p /mnt/savertd\n</code></pre>\n<ul>\n<li>second form is better, it will create all directory along the path, first one will fail if <code>/mnt</code> do not exists.</li>\n<li><code>mkdir -p</code> will also not complain if directory exists.</li>\n</ul>\n<h1>echo -e</h1>\n<p>you have some</p>\n<pre><code>echo -e &quot;Mounting the target disk to /mnt/savertd\\n&quot;\n</code></pre>\n<p><s>why use both <code>-e</code> (no new line) and a trailling <code>\\n</code> (new line) ?</s></p>\n<p>actually :</p>\n<ul>\n<li><code>-e</code> enable interpretation of backslash escapes</li>\n</ul>\n<p>long <code>echo -e</code> in help section can be replaced by a here documentation</p>\n<pre><code>cat &lt;&lt;EOF\n Copyright (C) 2020 ###########, e-mail: ##################\n Version 2.2-1\n\n saver comes with NO WARRANTY. This program is completely free and you\n can redistribute it under the GNU General Public License conditions.\n See https://www.gnu.org/licenses/gpl-3.0.txt for more information\n saver was made to simplify the process of backuping using rsync.\n This program will automaticly exclude these directories from syncing:\n /dev ; /proc ; /sys ; /tmp ; /run ; /mnt ; /media ; /lost+found.\n When typing in the disk name, you can use the full '/dev/(disk)' or just provide the name of the disk.\n Any disk you mention will be unmounted at the end of the program.\n\n Usage:\n -s [disk to copy (empty for current disk)] [copied path]\n [target disk (empty for current disk)] [target path]\n Options:\n -s Sync folders\n -r Delete any other files in the target folder\n -d Preform a 'dry run', no changes will be made\n -p Display progress for individual files (useful for large files)\n -v Display files that are being processed\n -i Show available disks/partitions\n -h Show this help\nEOF\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T12:49:36.977", "Id": "480670", "Score": "0", "body": "Thanks a lot I've heard about $#, but after I wrote that code so I haven't thought about that. All the other tips are really helpful too. I also wasn't sure how to use a here document, so I used a long echo, but this is much cleaner. Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T13:06:14.107", "Id": "480671", "Score": "0", "body": "I'm not sure about what you said of `echo -e` with `\\n` . `echo -e` doesn't block a new line. `echo -n` does that. I used 'echo -e' with '\\n' to have two new lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T13:08:13.920", "Id": "480672", "Score": "0", "body": "yes my fault, `-e enable interpretation of backslash escapes`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T11:59:56.600", "Id": "244826", "ParentId": "244824", "Score": "2" } } ]
{ "AcceptedAnswerId": "244826", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T10:14:06.430", "Id": "244824", "Score": "2", "Tags": [ "bash" ], "Title": "Bash script backup program" }
244824
<p>How can I improve the readability of the below function using a list comprehension? Also, is there a way to improve <code>items()</code> performance?</p> <pre class="lang-py prettyprint-override"><code>pricing = {'prices': [{'product_id': 1, 'price': 599, 'vat_band': 'standard'}, {'product_id': 2, 'price': 250, 'vat_band': 'zero'}, {'product_id': 3, 'price': 250, 'vat_band': 'zero'}], 'vat_bands': {'standard': 0.2, 'zero': 0}} order = {'order': {'id': 12, 'items': [{'product_id': 1, 'quantity': 1}, {'product_id': 2,'quantity': 5}]}} exchange_rate = 1.1 def items(): &quot;&quot;&quot; computes the item price and vat for a given pricing, order, and exchange rate. returns list of items dictionaries &quot;&quot;&quot; return [{'product_id': item['product_id'], 'quantity': item['quantity'], 'price': round(product['price'] * exchange_rate, 2), 'vat': round(pricing['vat_bands']['standard'] * product['price'] * exchange_rate, 2)} if product['vat_band'] == 'standard' else {'product_id': item['product_id'], 'quantity': item['quantity'], 'price': round(product['price'] * exchange_rate, 2), 'vat': 0} for item in order['order']['items'] for product in pricing['prices'] if item['product_id'] == product['product_id']] print(items()) </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code>[{'product_id': 1, 'quantity': 1, 'price': 658.9, 'vat': 131.78}, {'product_id': 2, 'quantity': 5, 'price': 275.0, 'vat': 0}] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T15:33:06.440", "Id": "480690", "Score": "3", "body": "This needs to be re-titled. What does the program actually do? Pricing for what?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:08:42.933", "Id": "480728", "Score": "5", "body": "Apart from the list comprehensions you asked for, Python dicts are not really meant to be used like this as far as I understand. In python, objects with properties are something different that dictionaries with keys; that's in contrast to JavaScript. You might want to use [namedtuple](https://docs.python.org/3/library/collections.html#collections.namedtuple) or [dataclass](https://docs.python.org/3/library/dataclasses.html#module-dataclasses) so that you have `Product`s with `prod.price` instead of `dict`s with `prod['price']`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T00:23:20.760", "Id": "480745", "Score": "0", "body": "Personally the source of the readability issue seems to be mostly a whitespace issue. I found using [hanging indents](https://www.python.org/dev/peps/pep-0008/#fn-hi) and keeping one expression per line to fix this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T17:56:02.263", "Id": "480828", "Score": "0", "body": "The conditional expression is duplicating the entire `dict` when the only difference between the two cases is the `vat` value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:43:27.157", "Id": "480836", "Score": "1", "body": "@SillyFreak That's basically what my answer proposes." } ]
[ { "body": "<p>As a general rule it is best not to nest comprehensions. It makes code hard to read. You are better off just writing a <code>for</code> loop and appending the results to a list or using a generator.</p>\n<p>Here are a couple rules with comprehensions that will make your code less brittle and easy for others to work with:</p>\n<ol>\n<li>Don't nest comprehensions.</li>\n<li>If a comprehension is too long for one line of code, don't use it.</li>\n<li>If you need an <code>else</code>, don't use a comprehension.</li>\n</ol>\n<p>Of course there are exceptions to these rules, but they are a good place to start.</p>\n<p>One of the reasons nested list comprehension is an issue is it often results in a exponential increase in computation needed. For each item in the order you have to loop through every product. This is not efficient. You want to go from <em>O(n x m)</em> to <em>O(n + m)</em>. You should loop through products once and through order items once.</p>\n<p>You can see in the updated code below that I loop through the list of products and create a dictionary with the key as the product ID. This makes it so that, while looping through the order items, I can simply get the product by looking up the key. It is much more performant and readable.</p>\n<pre class=\"lang-py prettyprint-override\"><code>pricing = {\n &quot;prices&quot;: [\n {&quot;product_id&quot;: 1, &quot;price&quot;: 599, &quot;vat_band&quot;: &quot;standard&quot;},\n {&quot;product_id&quot;: 2, &quot;price&quot;: 250, &quot;vat_band&quot;: &quot;zero&quot;},\n {&quot;product_id&quot;: 3, &quot;price&quot;: 250, &quot;vat_band&quot;: &quot;zero&quot;},\n ],\n &quot;vat_bands&quot;: {&quot;standard&quot;: 0.2, &quot;zero&quot;: 0},\n}\norder = {\n &quot;order&quot;: {\n &quot;id&quot;: 12,\n &quot;items&quot;: [{&quot;product_id&quot;: 1, &quot;quantity&quot;: 1}, {&quot;product_id&quot;: 2, &quot;quantity&quot;: 5}],\n }\n}\nexchange_rate = 1.1\n\n\ndef calculate_exchange_rate(price, rate=None):\n if rate is None:\n rate = exchange_rate\n return round(price * rate, 2)\n\n\ndef items():\n &quot;&quot;&quot;\n computes the item price and vat for a given pricing, order, and exchange rate.\n returns list of items dictionaries\n &quot;&quot;&quot;\n item_list = []\n products = {p[&quot;product_id&quot;]: p for p in pricing[&quot;prices&quot;]}\n\n for item in order[&quot;order&quot;][&quot;items&quot;]:\n product = products.get(item[&quot;product_id&quot;])\n vat = 0\n if product[&quot;vat_band&quot;] == &quot;standard&quot;:\n vat = pricing[&quot;vat_bands&quot;][&quot;standard&quot;] * product[&quot;price&quot;]\n item_list.append(\n {\n &quot;product_id&quot;: item[&quot;product_id&quot;],\n &quot;quantity&quot;: item[&quot;quantity&quot;],\n &quot;price&quot;: calculate_exchange_rate(product[&quot;price&quot;]),\n &quot;vat&quot;: calculate_exchange_rate(vat),\n }\n )\n return item_list\n\nprint(items())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T03:58:57.140", "Id": "480749", "Score": "2", "body": "I am bewildered by any discussion or proposal (including PEP8) that treats “readability” as a universal objectively definable standard. It is by its nature subjective. Honestly, I find nested list comprehensions *more* “readable” than nested `for` loops with an `append()` in the middle. Yes, like many people I grew up on plodding vanilla languages—C, pascal, BASIC—but to apply their standards to what is and is not “readable” in Python just demonstrates a failure to update one’s thinking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T09:38:56.117", "Id": "480765", "Score": "0", "body": "@jez Readability couldn't be 100% subjective though, there is something fundamental about the properties of information in regards to the readability by an agent. It's sometimes hard to get at since our experience and expectations shapes us so much, but I think it's a good endeavor to try to find the more objective bits here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T12:47:07.110", "Id": "480791", "Score": "0", "body": "@Alex 100% subjectivity is a straw man—*of course* I’m not suggesting that. I’m objecting to the way the other extreme, i.e. pretense of 100% objectivity (e.g. slavish adherence to PEP8) is commonly advocated. This post, which declares “nested comprehensions are less readable than nested for loops, so don’t use them” is a good illustration of the subjectivity that really lies behind that. To me it’s the other way round, and I doubt I’m alone in the universe." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T12:52:12.327", "Id": "480792", "Score": "0", "body": "“Shouldn’t have some rules”. No I didn’t say there shouldn’t be some rules. That’s called the fallacy of the excluded middle. Your pointer to gofmt is helpful. Your mocking use of mixed case OTOH is not (and not welcome on stack exchange—read the FAQs)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T14:41:11.637", "Id": "480804", "Score": "1", "body": "@jez Then we agree, thank you for clarifying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T17:22:54.037", "Id": "480826", "Score": "1", "body": "You forgot to return `item_list`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T13:47:26.747", "Id": "244832", "ParentId": "244828", "Score": "7" } }, { "body": "<h1>Readability</h1>\n<p>comprehensions have advantages</p>\n<ul>\n<li>they may be short one liners that are more readable (in the context code) than explicit loops</li>\n<li>they may be more efficient</li>\n</ul>\n<p>however - when done wrong they tend to be unreadable and thus unmaintainable.</p>\n<p>Yours is near unmaintainable. It did take me a little time to identify some of your code is superfluous. Your expression</p>\n<pre><code>return [{'product_id': item['product_id'],\n 'quantity': item['quantity'],\n 'price': round(product['price'] * exchange_rate, 2),\n 'vat': round(pricing['vat_bands']['standard'] * product['price'] * exchange_rate, 2)}\n if product['vat_band'] == 'standard' else\n {'product_id': item['product_id'],\n 'quantity': item['quantity'],\n 'price': round(product['price'] * exchange_rate, 2),\n 'vat': 0}\n for item in order['order']['items'] for product in pricing['prices']\n if item['product_id'] == product['product_id']]\n</code></pre>\n<p>contains a special handling for zero VAT - and your <code>pricing</code> does so as well. So we shorten the expression to</p>\n<pre><code>return [{'product_id': item['product_id'],\n 'quantity': item['quantity'],\n 'price': round(product['price'] * exchange_rate, 2),\n 'vat': round(pricing['vat_bands'][product['vat_band']] * product['price'] * exchange_rate, 2)}\n for item in order['order']['items'] for product in pricing['prices']\n if item['product_id'] == product['product_id']]\n</code></pre>\n<h1>Efficiency</h1>\n<p>Next the <code>n * m</code> loop. That is the most inefficient search. That is because your <code>pricing</code> data structure is not optimized for lookup.\nWe solve that by converting the existing list to a dict once(!)</p>\n<pre><code>prices = {e['product_id']: {'price': e['price'], 'vat_band':e['vat_band']} for e in pricing['prices']}\n</code></pre>\n<p>That is what comprehensions are for mostly. We also do a shortcut for</p>\n<pre><code>vat_bands = pricing['vat_bands']\n</code></pre>\n<p>and have a simpler comprehension with a loop over orders only as we can directly look up pricing information</p>\n<pre><code>return [{'product_id': item['product_id'],\n 'quantity': item['quantity'],\n 'price': round(prices[item['product_id']]['price'] * exchange_rate, 2),\n 'vat': round(vat_bands[prices[item['product_id']]['vat_band']] * prices[item['product_id']]['price'] * exchange_rate, 2)}\n for item in order['order']['items']]\n</code></pre>\n<h1>More readability</h1>\n<p>We pull out some code into a function. That allows us to have temporary variables which add more readability.</p>\n<pre><code>pricing = {'prices': [{'product_id': 1, 'price': 599, 'vat_band': 'standard'},\n {'product_id': 2, 'price': 250, 'vat_band': 'zero'},\n {'product_id': 3, 'price': 250, 'vat_band': 'zero'}],\n 'vat_bands': {'standard': 0.2, 'zero': 0}}\norder = {'order': {'id': 12, 'items': [{'product_id': 1, 'quantity': 2}, {'product_id': 2,'quantity': 5}]}}\nexchange_rate = 1.1\n\nprices = {e['product_id']: {'price': e['price'], 'vat_band': e['vat_band']} for e in pricing['prices']}\nvat_bands = pricing['vat_bands']\n\n\ndef do_format(item, product):\n price = round(product['price'] * exchange_rate, 2)\n vat = round(vat_bands[product['vat_band']] * product['price'] * exchange_rate, 2)\n return dict(item, **{'price': price, 'vat': vat})\n\n\ndef items():\n &quot;&quot;&quot;\n computes the item price and vat for a given pricing, order, and exchange rate.\n returns list of items dictionaries\n &quot;&quot;&quot;\n return [do_format(item, prices[item['product_id']]) for item in order['order']['items']]\n</code></pre>\n<p>Now everything is perfectly readable. So readable that we wonder why quantity has no effect on the price?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:53:35.007", "Id": "480738", "Score": "0", "body": "Don't know if it really matters, it's maybe less efficient if `item` is huge, but from the POV of readability I would write `{**item, 'price': price, 'vat': vat}` in preference to `dict(item, **{'price': price, 'vat': vat})`. Or if you don't like that, you can still tidy it up a bit as `dict(item, price=price, vat=vat)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T07:17:04.713", "Id": "480756", "Score": "0", "body": "@SteveJessop I did notice that only after posting. I agree with you." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T20:48:38.137", "Id": "244853", "ParentId": "244828", "Score": "6" } }, { "body": "<p>Ignoring the fact that your particular code doesn't actually need a nested loop, in general I would say that nested comprehensions can be fairly readable, but helps a lot to put each <code>for</code> on a line of its own:</p>\n<pre><code>return [\n some_function_of(item, product)\n for item in order['order']['items']\n for product in pricing['prices']\n if some_condition_on(item, product)\n]\n</code></pre>\n<p>The main issue with the way your code presents to the reader, is that the <code>if/else</code> clause is huge and the comprehension logic is tiny, so you can't easily see the structure of the comprehension itself until you've mentally eliminated the big if/else expression. This wouldn't be a problem if each logical part of the comprehension (the expression, the for clauses, the if clause) was small. If you can't achieve that, then a nested comprehension is going to be difficult to follow.</p>\n<p>Alternatively, in a case like this where the &quot;inner&quot; nested <code>for</code> clause actually doesn't depend on the value of <code>item</code> from the outer <code>for</code>, you can also eliminate nesting using <code>itertools.product</code>:</p>\n<pre><code>return [\n some_function_of(item, product)\n for item, product in itertools.product(order['order']['items'], pricing['prices'])\n if some_condition_on(item, product)\n]\n</code></pre>\n<p>Assuming the reader knows <code>itertools</code>, this has the advantage of immediately communicating that this is an N*M loop. Sometimes when reading nested comprehensions (or nested <code>for</code> loops for that matter), you spend a bit of time wondering in what way the inner loop bounds depend on the outer loop value: are we looking at a rectangle, or a triangle, or something wibbly? It's usually not particularly difficult to figure out when they are independent, but explicitly stating that this is a cartesian product eliminates the need to even think about that. Whenever you can show the reader the big structure first, that helps readability.</p>\n<p>Then with that done we see that:</p>\n<ul>\n<li>you're filtering a cartesian product</li>\n<li>using a condition which <strong>by definition</strong> is only true for one pair per <code>item</code></li>\n<li>because (we hope) <code>product_id</code> uniquely identifies a product,</li>\n</ul>\n<p>That is the clue that something is wrong here, and that it would be more efficient to look up the correct product for each item as in the other answers.</p>\n<p>You may also notice that I'm using a different indenting style from you -- I put opening punctuation at the end of a line, and the matching closing punctuation at the start of a line, and I indent by fixed tabs rather than vertically matching the opening punctuation. That is to say, I use &quot;hanging indents&quot;, and where PEP-8 says &quot;The 4-space rule is optional for continuation lines&quot;, I choose to stick with 4! I think I'm probably in a minority of Python programmers who prefer this, though, so feel free to ignore it. Provided your indentation is reasonably consistent, it's only a minor contributor to readability which convention you follow.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T18:58:35.553", "Id": "480832", "Score": "1", "body": "This is the answer I agree with the most. The comprehension itself is not the issue at all. The issue is in the conditional forming of the dictionary." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T22:01:45.160", "Id": "244857", "ParentId": "244828", "Score": "5" } }, { "body": "<p>There's a lot of good feedback on how to work with the data as it's structured now, but my opinion is that - as soon as humanly possible - you should deserialize it out of a collection of weakly-typed dictionaries and lists, to a set of classes. This will make a handful of things better-structured, more testable and verifiable, and more easily maintainable and expandable. For instance, I added methods to calculate subtotals and print an &quot;order table&quot;.</p>\n<p>Also of note: please (please) do not round financials until the very last step of output. Doing otherwise is risking the wrath of accuracy loss, and in accounting that is indeed a bad place to be.</p>\n<p>Example code:</p>\n<pre><code>from dataclasses import dataclass\nfrom io import StringIO\nfrom typing import Iterable, Dict, Tuple\n\n\nEXCHANGE_RATE = 1.1\n\n\n@dataclass\nclass Product:\n product_id: int\n price: float\n vat_band: float\n\n @classmethod\n def product_from_dict(cls, d: dict, bands: Dict[str, float]) -&gt; 'Product':\n kwargs = {**d, 'vat_band': bands[d['vat_band']]}\n return cls(**kwargs)\n\n @classmethod\n def products_from_dict(cls, d: dict) -&gt; Iterable['Product']:\n bands = d['vat_bands']\n return (\n cls.product_from_dict(price_d, bands)\n for price_d in d['prices']\n )\n\n @property\n def price_with_exchange(self) -&gt; float:\n return self.price * EXCHANGE_RATE\n\n @property\n def vat_with_exchange(self) -&gt; float:\n return self.vat_band * self.price_with_exchange\n\n @property\n def subtotal(self) -&gt; float:\n return self.price_with_exchange + self.vat_with_exchange\n\n\n@dataclass\nclass Item:\n product: Product\n qty: int\n\n @property\n def subtotal(self) -&gt; float:\n return self.qty * self.product.subtotal\n\n\nclass Order:\n def __init__(self, d: dict, products: Dict[int, Product]):\n d = d['order']\n self.id = d['id']\n self.items: Tuple[Item] = tuple(\n Item(products[item['product_id']], item['quantity'])\n for item in d['items']\n )\n\n def __str__(self):\n out = StringIO()\n out.write(f'{&quot;ID&quot;:2} {&quot;Price&quot;:&gt;6} {&quot;VAT&quot;:&gt;6} {&quot;Qty&quot;:3} {&quot;Subtotal&quot;:&gt;6}\\n')\n out.writelines(\n f'{item.product.product_id:2} '\n f'{item.product.price_with_exchange:6.2f} '\n f'{item.product.vat_with_exchange:6.2f} '\n f'{item.qty:3} '\n f'{item.subtotal:6.2f}\\n'\n for item in self.items\n )\n return out.getvalue()\n\n\ndef main():\n products = {\n prod.product_id: prod\n for prod in Product.products_from_dict({\n 'prices': [\n {'product_id': 1, 'price': 599, 'vat_band': 'standard'},\n {'product_id': 2, 'price': 250, 'vat_band': 'zero'},\n {'product_id': 3, 'price': 250, 'vat_band': 'zero'}],\n 'vat_bands': {'standard': 0.2, 'zero': 0},\n })\n }\n order = Order({\n 'order': {\n 'id': 12, 'items': [\n {'product_id': 1, 'quantity': 1},\n {'product_id': 2, 'quantity': 5}\n ]\n }\n }, products)\n\n print(str(order))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:39:04.310", "Id": "244899", "ParentId": "244828", "Score": "2" } } ]
{ "AcceptedAnswerId": "244832", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T12:17:35.270", "Id": "244828", "Score": "6", "Tags": [ "python", "performance", "comparative-review", "complexity" ], "Title": "Computing the item price and vat for a given pricing, order, and exchange rate" }
244828
<p>The code below runs perfectly fine as I want it to. I'd like to create more subclasses to get a better overview over the whole code. Can I place the setter and getter as well as the methods into the extended classes? I'd like to create subclasses as in 'single room', 'double room' etc., to extend room. Would it improve my code? My prof wants to see more classes.</p> <p>By the way, the code comments are in German, so if there are any questions, I'm happy help.</p> <p>To simplify my question, the option pet is just available for <code>Penthouse</code>. Does it make sense to create a subclass for <code>Penthouse</code> to move to setter and getter to the subclass?</p> <pre><code>import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.Scanner; public class Booking { private static boolean CustomerInterface = true;//Hauptprogramm boolean public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); Room[] hotel = new Room[8];//Array für Zimmer hotel[0] = new Room(40, true, 1);//Single room hotel[1] = new Room(40, true, 2);//Single room hotel[2] = new Room(70, true, 3);//Double room hotel[3] = new Room(70, true, 4);//Double room hotel[4] = new Room(100, true, 5);//Triple room hotel[5] = new Room(100, true, 6);//Triple room hotel[6] = new Penthouse(200, true, 7, false);//Penthouse hotel[7] = new Penthouse(200, true, 8, false);//Penthouse System.out.println(&quot;Willkommen im Hotel AppDev1&quot;);//Begrüßung while (CustomerInterface) {//Abfrage des Boolean zum Start des Hauptprogramms System.out.println(&quot;Bitte wählen sie eine der folgenden Auswahlmöglichkeiten:&quot;); System.out.println(&quot;********************************************************&quot;); System.out.println(&quot;1: Buchen sie einen Raum\n2: List der verfügbaren Zimmer anzeigen&quot; + &quot;\n3: Liste aller Zimmer anzeigen\n4: Kunde auschecken\n5: Gäste Anzeigen\n6: Program ende&quot;); System.out.println(&quot;********************************************************&quot;); String Selection = input.next(); switch (Selection) { case &quot;1&quot;: Booking(hotel);//Methode zum Buchen break; case &quot;2&quot;: ShowEmpty(hotel);//Freie Zimmer anzeigen break; case &quot;3&quot;: ShowAll(hotel);//Alle Zimmer anzeigen break; case &quot;4&quot;: DeleteCustomer(hotel);//Kundendaten je Zimmernummer löschen break; case &quot;5&quot;: Gastdaten(hotel);//Gästedaten:Name, Preise, Buchungsoptionen anzeigen break; case &quot;6&quot;: ShutDown();//Programm beenden break; default: WrongInput();//Flasche Eingabe getätigt CustomerInterface = true;//Hauptprogramm neu starten } } } private static void PreisKategorie(Room []hotel, int roomNr) {//Auswahl der Zimmerkategorie von Standart bis Luxus System.out.println(&quot;Welche Preiskategorie möchten sie?\n1 = Standard\n2 = Premium (10% Zuschlag)\n 3 = Luxus (20% Zuschlag)&quot;); Scanner input = new Scanner(System.in); String userInput; userInput = input.next(); switch(userInput) { case &quot;1&quot;: System.out.println(&quot;Sie haben Standard gewählt. &quot;); hotel[roomNr].setPriceLevel(1.0);//Standartpreis hotel[roomNr].setPricePerNight(hotel[roomNr].getPricePerNight() * hotel[roomNr].getPriceLevel()); break; case &quot;2&quot;: System.out.println(&quot;Sie haben Premium gewählt. &quot;); hotel[roomNr].setPriceLevel(1.1);//10% Premiumzuschlag hotel[roomNr].setPricePerNight(hotel[roomNr].getPricePerNight() * hotel[roomNr].getPriceLevel()); break; case &quot;3&quot;: System.out.println(&quot;Sie haben Luxus gewählt. &quot;); hotel[roomNr].setPriceLevel(1.2);//20% Luxuszuschlag hotel[roomNr].setPricePerNight(hotel[roomNr].getPricePerNight() * hotel[roomNr].getPriceLevel()); break; default: WrongInput();//Falsche Eingabe PreisKategorie(hotel, roomNr);//Zurück zum Beginn der Kategorieauswahl } } private static void ShutDown() {//Programm beenden System.out.println(&quot;Danke, auf wiedersehen.&quot;); System.exit(0); } private static void Booking(Room[] hotel) {//Zimmer buchen String userInput; Scanner input = new Scanner(System.in); System.out.println(&quot;Bitte geben sie eine der folgenden Zimmernummern ein:\n1-2 Einzelzimmer, Preis für eine&quot; + &quot; Übernachtung = &quot; + &quot; &quot; + &quot;\n3-4 Doppelzimmer&quot; + &quot;\n5-6 Drreibettzimmer\n7-8 Ferienwohnug\n9 Programm beenden&quot;); userInput = input.next(); switch (userInput) { case &quot;1&quot;: if (hotel[0].getAvailable(hotel[0].available)) { System.out.println(hotel[0].getPricePerNight()); int roomNr = 0; PreisKategorie(hotel, roomNr); Breakfast(hotel, roomNr); System.out.println(hotel[0].getPricePerNight()); Balcony(hotel, roomNr); BookingPeriode(hotel, roomNr); FinalizeBooking(hotel, roomNr); } else { AldreadyBooked(hotel); } break; case &quot;2&quot;: if (hotel[1].getAvailable(hotel[1].available)) { int roomNr = 1; PreisKategorie(hotel, roomNr); Breakfast(hotel, roomNr); Balcony(hotel, roomNr); BookingPeriode(hotel, roomNr); FinalizeBooking(hotel, roomNr); } else { AldreadyBooked(hotel); } break; case &quot;3&quot;: if (hotel[2].getAvailable(hotel[2].available)) { int roomNr = 2; PreisKategorie(hotel, roomNr); Breakfast(hotel, roomNr); Balcony(hotel, roomNr); SinglePerson(hotel, roomNr); BookingPeriode(hotel, roomNr); FinalizeBooking(hotel, roomNr); } else { AldreadyBooked(hotel); } break; case &quot;4&quot;: if (hotel[3].getAvailable(hotel[3].available)) { int roomNr = 3; PreisKategorie(hotel, roomNr); Breakfast(hotel, roomNr); Balcony(hotel, roomNr); SinglePerson(hotel, roomNr); BookingPeriode(hotel, roomNr); FinalizeBooking(hotel, roomNr); } else { AldreadyBooked(hotel); } break; case &quot;5&quot;: if (hotel[4].getAvailable(hotel[4].available)) { int roomNr = 4; PreisKategorie(hotel, roomNr); Breakfast(hotel, roomNr); SecondToilet(hotel, roomNr); BookingPeriode(hotel, roomNr); FinalizeBooking(hotel, roomNr); } else { AldreadyBooked(hotel); } break; case &quot;6&quot;: if (hotel[5].getAvailable(hotel[5].available)) { int roomNr = 5; PreisKategorie(hotel, roomNr); Breakfast(hotel, roomNr); SecondToilet(hotel, roomNr); BookingPeriode(hotel, roomNr); FinalizeBooking(hotel, roomNr); } else { AldreadyBooked(hotel); } break; case &quot;7&quot;: if (hotel[6].getAvailable(hotel[6].available)) { int roomNr = 6; PreisKategorie(hotel, roomNr); CountGuests(hotel, roomNr); Pet(hotel, roomNr); BookingPeriode(hotel, roomNr); RoomService(hotel, roomNr); FinalizeBooking(hotel, roomNr); } else { AldreadyBooked(hotel); } break; case &quot;8&quot;: if (hotel[7].getAvailable(hotel[7].available)) { int roomNr = 7; PreisKategorie(hotel, roomNr); CountGuests(hotel, roomNr); Pet(hotel, roomNr); BookingPeriode(hotel, roomNr); RoomService(hotel, roomNr); FinalizeBooking(hotel, roomNr); } else { AldreadyBooked(hotel); } break; case &quot;9&quot;: ShutDown(); break; default: WrongInput(); Booking(hotel); } //int roomNr; //roomNr = Integer.valueOf(userInput) - 1;//wandelt die eingabe in int um und -1 damit Zimmer 1 = room[0] //FinalizeBooking(hotel, roomNr); } private static void FinalizeBooking(Room @NotNull [] hotel, int roomNr) { String userInput; Scanner input = new Scanner(System.in); String rName; System.out.println(&quot;Bitte geben sie ihren Namen ein : &quot;); rName = input.next();//Kundenname für die Buchung //rName = String.valueOf(roomNr);//wandelt rName in int um es der arry zuzuodrnen //Option 1 mit boolean hotel[roomNr].setAvailable(false); //Option 2 mit equals hotel[roomNr].setName(rName);//hinterlegt in der arry den Namen des Gastes Receipt(hotel, roomNr); } private static void Receipt(Room @NotNull [] hotel, int roomNr) { System.out.println(&quot;Danke für ihre Buchung, das Zimmer&quot; + &quot; &quot; + (roomNr + 1) + &quot; &quot; + &quot;ist für sie reserviert\nDie Gesamtsumme beträgt: &quot; + (hotel[roomNr].getPricePerNight() * 1.19) + &quot;€&quot; + &quot;\n Die enthaltende Mehrwertsteuer beträgt: &quot; +(hotel[roomNr].getPricePerNight() * 0.19)); if ((hotel[roomNr].getFrühstück()==true) || (hotel[roomNr].getBalkon()==true) || (hotel[roomNr].getSinglePerson()==true) || (hotel[roomNr].getGästetoilette()==true) || (hotel[roomNr].getPet()==true) || (hotel[roomNr].getRoomService()==true)) { System.out.println(&quot;Sie haben die folgenden optionen mit gebucht:&quot;); if (hotel[roomNr].getFrühstück() == true) { System.out.println(&quot;Frühstück: &quot; + hotel[roomNr].getBreaky() * hotel[roomNr].getBookingPeriode() + &quot;€&quot;); } if (hotel[roomNr].getBalkon() == true) { System.out.println(&quot;Balkon: &quot; + hotel[roomNr].getBalcony() * hotel[roomNr].getBookingPeriode() + &quot;€&quot;); } if (hotel[roomNr].getSinglePerson() == true) { System.out.println(&quot;Einzelpersonrabatt: &quot; + hotel[roomNr].getEinzelPerson() * hotel[roomNr].getBookingPeriode() + &quot;€&quot;); } if (hotel[roomNr].getGästetoilette() == true) { System.out.println(&quot;Gäste Toilette: &quot; + hotel[roomNr].getSecondToilet() * hotel[roomNr].getBookingPeriode() + &quot;€&quot;); } if (hotel[roomNr].getPet() == true) { System.out.println(&quot;Haustierzuschlag: &quot; + hotel[roomNr].getHaustier() * hotel[roomNr].getBookingPeriode() + &quot;€&quot;); } if (hotel[roomNr].getRoomService() == true) { System.out.println(&quot;Zimmerservie: &quot; + hotel[roomNr].getZimmerservice() * hotel[roomNr].getBookingPeriode() + &quot;€&quot;); } } else { System.out.println(&quot;Sie haben keine Zusatzoptionen gebucht&quot;); } } private static void RoomService(Room[] hotel, int roomNr) { System.out.println(&quot;Möchten sie Zimmerservice dazubuchen? \n&quot; +&quot; 1 = ja 2= Nein&quot;); Scanner input = new Scanner(System.in); String userInput; userInput = input.next(); switch (userInput){ case &quot;1&quot;: System.out.println(&quot;Sie haben inklusive Zimmerservice gebucht&quot;); hotel[roomNr].setRoomService(true); hotel[roomNr].setPricePerNight(hotel[roomNr].getPricePerNight() + Room.getZimmerservice()); break; case &quot;2&quot;: System.out.println(&quot;Sie haben ohne Zimmerservice gebucht&quot;); hotel[roomNr].setRoomService(false); break; default: WrongInput(); RoomService(hotel, roomNr); } } private static void AldreadyBooked(Room[] hotel) { System.out.println(&quot;Dieses Zimmer ist leider schon belegt\n Bitte wählen sie ein anders Zimmer.&quot;); //CustomerInterface = true; Booking(hotel); } private static void WrongInput() { System.out.println(&quot;********************************************************&quot;); System.out.println(&quot;Ihre eingabe war leider nicht Korrekt.\nBitte versuchen sie es erneut.&quot;); System.out.println(&quot;********************************************************&quot;); } private static void Pet(Room[] hotel, int roomNr) { System.out.println(&quot;Kommen Sie mit oder ohne Haustier\n1 = mit \n2 = ohne&quot;); Scanner input = new Scanner(System.in); String userInput; userInput = input.next(); switch (userInput) { case &quot;1&quot;: System.out.println(&quot;sie nehmen ein Haustier mit&quot;); hotel[roomNr].setPricePerNight(hotel[roomNr].getPricePerNight() + hotel[roomNr].getHaustier());//3 € Aufpreis für ein Haustier hotel[roomNr].pet = true; break; case &quot;2&quot;: System.out.println(&quot;sie nehmen kein Haustier mit&quot;); hotel[roomNr].pet = false; break; default: WrongInput(); Pet(hotel, roomNr); break; } } private static void BookingPeriode(Room[] hotel, int roomNr) { if (roomNr &lt; 7){ System.out.println(&quot;Wie lange bleiben Sie? &quot;); Scanner input = new Scanner(System.in); String userInput; userInput = input.next(); switch (userInput) { case &quot;1&quot;: case &quot;2&quot;: case &quot;3&quot;: case &quot;4&quot;: case &quot;5&quot;: case &quot;6&quot;: case &quot;7&quot;: case &quot;8&quot;: case &quot;9&quot;: case &quot;10&quot;: case &quot;11&quot;: case &quot;12&quot;: case &quot;13&quot;: case &quot;14&quot;: System.out.println(&quot;sie haben&quot; + &quot; &quot; + userInput + &quot; &quot; + &quot;Tage gewählt&quot;); hotel[roomNr].setBookinperiode(Integer.valueOf(userInput)); hotel[roomNr].setPricePerNight(hotel[roomNr].getPricePerNight() * Integer.valueOf(userInput)); break; default: WrongInput(); BookingPeriode(hotel, roomNr);} } else{ System.out.println(&quot;Wie lange bleiben Sie? (Die Mindestbuchungsdauer beträgt 3 Tage\nDie maximale Buchungsdauer beträt 14 Tage)&quot;); Scanner input = new Scanner(System.in); String userInput; userInput = input.next(); switch (userInput) { case &quot;1&quot;: case &quot;2&quot;: MinBooking(hotel, roomNr); break; case &quot;3&quot;: case &quot;4&quot;: case &quot;5&quot;: case &quot;6&quot;: case &quot;7&quot;: case &quot;8&quot;: case &quot;9&quot;: case &quot;10&quot;: case &quot;11&quot;: case &quot;12&quot;: case &quot;13&quot;: case &quot;14&quot;: System.out.println(&quot;sie haben&quot; + &quot; &quot; + userInput + &quot; &quot; + &quot;Tage gewählt&quot;); hotel[roomNr].setBookinperiode(Integer.valueOf(userInput)); hotel[roomNr].setPricePerNight(hotel[roomNr].getPricePerNight() * Integer.valueOf(userInput)); break; default: WrongInput(); BookingPeriode(hotel, roomNr); } } } private static void MinBooking(Room[] hotel, int roomNr) { System.out.println(&quot;Sie unterschreiten die Mindestbuchungsdauer! \nMöchten Sie erneut wählen? 1 = neuwahl 2= Programm beenden&quot;); Scanner input = new Scanner(System.in); String userInput; userInput = input.next(); if (userInput.equals(&quot;1&quot;)) { BookingPeriode(hotel, roomNr); } else if (userInput.equals(&quot;2&quot;)) { ShutDown(); } else { WrongInput(); MinBooking(hotel, roomNr); } } private static void CountGuests(Room[] hotel, int roomNr) { System.out.println(&quot;Mit wie vielen Personen möchten sie buchen?\nDie maximale Anzahl beträt 6 Personen.)&quot;); Scanner input = new Scanner(System.in); String userInput; userInput = input.next(); switch (userInput) { case &quot;1&quot;: case &quot;2&quot;: case &quot;3&quot;: case &quot;4&quot;: case &quot;5&quot;: case &quot;6&quot;: System.out.println(&quot;sie haben&quot; + &quot; &quot; + userInput + &quot; Personen gewählt&quot;); hotel[roomNr].setCountGuests(Integer.valueOf(userInput)); break; default: WrongInput(); CountGuests(hotel, roomNr); } } private static void SecondToilet(Room[] hotel, int roomNr) { System.out.println(&quot;Möchten sie ein Zimmer mit Gäste Toilette? 1 = ohne Gäste Toilette 2 = 2 mit Gäste Toilette&quot;); Scanner input = new Scanner(System.in); String userInput; userInput = input.next(); switch (userInput) { case &quot;1&quot;: System.out.println(&quot;sie haben ein Zimmer ohne Gäste Toilette gewählt&quot;); hotel[roomNr].gästetoilette = false; break; case &quot;2&quot;: System.out.println(&quot;sie haben ein Zimmer mit Gäste Toilette gewählt&quot;); hotel[roomNr].setPricePerNight(hotel[roomNr].getPricePerNight() + Room.getSecondToilet());//10 € Aufpreis für eine extra Toilette hotel[roomNr].gästetoilette = true; break; default: WrongInput(); SecondToilet(hotel, roomNr); } } private static void SinglePerson(Room[] hotel, int roomNr) { System.out.println(&quot;Bitte geben sie an um wie viele Personen es sich bei ihrer Buchung handelt\n1 = Einzelperson 2= Paar&quot;); Scanner input = new Scanner(System.in); String userInput; userInput = input.next(); switch (userInput) { case &quot;1&quot;: System.out.println(&quot;sie haben Einzelperson gewählt&quot;); System.out.println(&quot;Sie bekommen einen Sondertarif (10 Euro weniger)&quot;); hotel[roomNr].singlePerson = true; hotel[roomNr].setPricePerNight(hotel[roomNr].getPricePerNight() - hotel[roomNr].getEinzelPerson()); System.out.println(hotel[roomNr].getPricePerNight()); break; case &quot;2&quot;: System.out.println(&quot;sie haben die Paaroption gewählt&quot;); hotel[roomNr].singlePerson = false; //System.out.println(hotel[roomNr].getPricePerNight()); break; default: WrongInput(); SinglePerson(hotel, roomNr); } } private static void Balcony(Room[] hotel, int roomNr) { System.out.println(&quot;Möchten sie ein Zimmer mit Balkon buchen? 1 = mit Balkon 2= ohne Balkon&quot;); Scanner input = new Scanner(System.in); String userInput; userInput = input.next(); switch (userInput) { case &quot;1&quot;: System.out.println(&quot;sie haben ein Zimmer mit Balkon gewählt&quot;); hotel[roomNr].setPricePerNight(hotel[roomNr].getPricePerNight() + Room.getBalcony());//5 € Aufpreis für einen Balkon hotel[roomNr].balkon = true; break; case &quot;2&quot;: System.out.println(&quot;sie haben ein Zimmer ohne Balkon gewählt&quot;); hotel[roomNr].balkon = false; break; default: WrongInput(); Balcony(hotel, roomNr); } } private static void Breakfast(Room @NotNull [] hotel, int roomNr) { System.out.println(&quot;Möchten sie Frühstück dazu buchen? 1 = mit Frühstück 2= ohne Frühstück&quot;); Scanner input = new Scanner(System.in); String userInput; userInput = input.next(); switch (userInput) { case &quot;1&quot;: System.out.println(&quot;sie haben ein Zimmer mit Frühstück gewählt&quot;); hotel[roomNr].setPricePerNight(hotel[roomNr].getPricePerNight() + Room.getBreaky());//3 € Aufprreis für Frühstück hotel[roomNr].frühstück = true; //System.out.println(hotel[roomNr].getPricePerNight()); break; case &quot;2&quot;: System.out.println(&quot;sie haben ein Zimmer ohne Frühstück gewählt&quot;); hotel[roomNr].frühstück = false; break; default: WrongInput(); Breakfast(hotel, roomNr); break; } } private static void ShowEmpty(Room @NotNull [] hotel) { for (int i = 0; i &lt; hotel.length; i++) { if (hotel[i].getAvailable(hotel[i].available)) { System.out.println(&quot;Zimmer &quot; + (i + 1) + &quot; steht zur Verfügung&quot;); }else { System.out.println(&quot;Zimmer &quot; + (i + 1) + &quot; ist belegt&quot;); } } } private static void ShowAll(Room @NotNull [] hotel) { for (int i = 0; i &lt; hotel.length; i++) { System.out.println(&quot;Wir bieten Zimmer &quot; + (i + 1) + &quot; an. &quot;); } } private static void DeleteCustomer(Room @NotNull [] hotel) { Scanner input = new Scanner(System.in); int roomNr; System.out.println(&quot;Bitte geben sie die Zimmernummer ein&quot;); roomNr = input.nextInt() - 1; hotel[roomNr].setName(&quot;Name&quot;); hotel[roomNr].setAvailable(true); System.out.println(&quot;Eintrag gelöscht&quot;); } private static void Gastdaten(Room @NotNull [] hotel) { for (int i = 0; i &lt; hotel.length; i++) { if (hotel[i].getAvailable(!(hotel[i].available))) { System.out.println(&quot;Es befinden sich zur Zeit Gäste in Zimmer: &quot; + hotel[i].roomNr + &quot;\nName: &quot; + hotel[i].getName() + &quot;\nGesamtpreis ohne MwST: &quot; + hotel[i].getPricePerNight()); switch (hotel[i].getRoomNr()) { case 1: case 2: System.out.println(&quot;Frühstück: &quot; + hotel[i].getFrühstück() + &quot;\nBalkon: &quot; + hotel[i].getBalkon() + &quot;\nDauer des Aufenthalts:&quot; + hotel[i].getBookingPeriode() + &quot;\n&quot;); break; case 3: case 4: System.out.println(&quot;Frühstück: &quot; + hotel[i].getFrühstück() + &quot;\nBalkon: &quot; + hotel[i].getBalkon() + &quot;\n&quot; + &quot;Einzelpersonenrabatt:&quot; + hotel[i].getSinglePerson() + &quot;\nDauer des Aufenthalts:&quot; + hotel[i].getBookingPeriode() + &quot;\n&quot;); break; case 5: case 6: System.out.println(&quot;Frühstück: &quot; + hotel[i].getFrühstück() + &quot;\nBalkon: &quot; + hotel[i].getBalkon() + &quot;\n&quot; + &quot;Gäste Toilette:&quot; + hotel[i].getGästetoilette() + &quot;\nDauer des Aufenthalts:&quot; + hotel[i].getBookingPeriode() + &quot;\n&quot;); break; case 7: case 8: System.out.println(&quot;Anzahl der Gäste: &quot; + hotel[i].getCountGuests() + &quot;\nHaustier: &quot; + hotel[i].getPet() + &quot;\n&quot; + &quot;Zimmerservice: &quot; + hotel[i].getRoomService() + &quot;\nDauer des Aufenthalts:&quot; + hotel[i].getBookingPeriode() + &quot;\n&quot;); break; } } else { System.out.println(&quot;Es befinden sich zur Zeit keine Gäste in Zimmer: &quot; + &quot; &quot; + hotel[i].getRoomNr() + &quot;\n&quot;); } } } } </code></pre> <pre><code>package Hotel; public class Room { //String CustomerName; private String Name; int roomNr; double pricePerNight; boolean available; //= true;//Zimmer frei oder belegt? static double breaky = 3; static double balcony = 5; boolean frühstück; boolean balkon; boolean singlePerson; boolean gästetoilette; static double secondToilet = 10; int countGuests; boolean pet; int bookinperiode; boolean roomservice; static double zimmerservice = 10; static double einzelPerson = 10; double haustier = 3; static double priceLevel; //Constructor public Room(double pricePerNight, boolean available,int roomNr) { this.pricePerNight = pricePerNight; this.available = available; this.roomNr = roomNr; } public boolean getPet() { return pet; } public double getHaustier() { return haustier; } public boolean getRoomService() { return roomservice; } public void setRoomService(boolean roomservice) { this.roomservice = roomservice; } public static double getZimmerservice() { return zimmerservice; } public boolean getGästetoilette() { return gästetoilette; } public static double getSecondToilet() { return secondToilet; } public void setCountGuests(int countGuests) { this.countGuests = countGuests; } public int getCountGuests() { return countGuests; } public boolean getSinglePerson() { return singlePerson; } public double getEinzelPerson() { return einzelPerson; } public boolean getBalkon() { return balkon; } public static double getBalcony() { return balcony; } public boolean getFrühstück() { return frühstück; } public static double getBreaky() { return breaky; } public void setPricePerNight(double pricePerNight) { this.pricePerNight = pricePerNight; } public double getPricePerNight() { return pricePerNight; } public void setBookinperiode(int bookinperiode) { this.bookinperiode = bookinperiode; } public int getBookingPeriode() { return bookinperiode; } public void setAvailable(boolean available) { this.available = available; } public boolean getAvailable(boolean available) { return available; } public String getName() { return Name; } public void setName(String Name) { this.Name = Name; } public double getPriceLevel() { return priceLevel; } public void setPriceLevel(double priceLevel) { this.priceLevel = priceLevel; } public int getRoomNr() { return roomNr; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T13:57:07.273", "Id": "480679", "Score": "4", "body": "\"My prof wants to see more classes.\" I agree. Your Room class contains everything but a kitchen sink (American euphemism). I don't speak German, so I cant show you, but I saw Customer, Booking, and Room classes all mixed in one Room class. (A customer books a room). Basically, every noun in the problem description is a potential class object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T14:03:07.580", "Id": "480680", "Score": "1", "body": "Also, separate your static and non-static class variables. Separate your class variables by data type. It makes the class easier for a person to understand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T08:25:20.610", "Id": "480900", "Score": "0", "body": "I'd guess most of the review hints in the answers could be sorted out by using a propert IDE. While it may slow down some learnings, it really helps in generating boilerplate properly, hinting typos, avoiding duplicates, etc." } ]
[ { "body": "<h2>OOAD - Object Orientated Analyze and Design</h2>\n<p>It's always a good idea to start with a pen and a pencil <strong>before</strong> you do any coding. Here is a demonstration on how such an Design could look like (I strongly recommend UML since this kind of diagramms is understood by everybody among engineers)</p>\n<p><a href=\"https://i.stack.imgur.com/Xu7Va.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Xu7Va.png\" alt=\"enter image description here\" /></a></p>\n<p>Honestly I do not fully understand your requirements (your homework task), so this design maybe a flawed. Take it and adjust it to your needs.</p>\n<h2>Pets</h2>\n<p>Since bringing pets to your room is not depending on any room feature (the hotel management might allow as an exception to bring your pet to a <em>regular</em> room) this feature is only a pricing feature. Having a <strong>design</strong> in your hands now, you can easily decide, where to put such extra-chargings into: the <code>Booking</code>! this is also where your breakfast should be.</p>\n<h2>Helpful hints</h2>\n<ul>\n<li>Avoid static members and methods, use your design and put them into the proper class</li>\n<li>Stick with the <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html\" rel=\"nofollow noreferrer\">java naming style guide</a> on naming</li>\n<li><a href=\"http://www.umlet.com/umletino/umletino.html\" rel=\"nofollow noreferrer\">UML-Tool UMLetino</a></li>\n<li>Look at the comments: <a href=\"https://codereview.stackexchange.com/users/3023/gilbert-le-blanc\">Gilbert Le Blanc</a> said: Basically, every noun in the problem description is a potential class object</li>\n<li>Additional: every verb is a method</li>\n<li>For beginners: read the <a href=\"https://clean-code-developer.de/die-grade/roter-grad/\" rel=\"nofollow noreferrer\">german clean code</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T05:26:29.850", "Id": "244919", "ParentId": "244829", "Score": "4" } }, { "body": "<ul>\n<li>Question: method and normal variable names in java start with a small letter by convention. As opposed to C#. Is it a special convention of the course?</li>\n<li>Repetitive code for array entries.</li>\n<li><code>X == true</code> is simply <code>X</code> and <code>X == false</code> is <code>!X</code> (not X).</li>\n<li>Parameters <code>f(X[] array, int index)</code> might just be <code>f(X x)</code>. It also might be that then the called method should be a method of <code>X.f()</code>. Call: <code>f(array[index])</code>. (You can change fields of the X inside f.)</li>\n<li><code>double haustier</code> (pet) would make me shiver, like <code>double children</code> - int?</li>\n</ul>\n<p>Now to the question:</p>\n<ul>\n<li>Subclasses of Room: Penthouse, Besenkammer, ... to be placed in a Room array will probably not be very manageable.</li>\n<li>But you have many features of a room and instead of many fields you could have a\n<code>RoomProperty</code> and derive subclasses like HavingPet (or whatever) and call overriden\n<code>ask()</code>, <code>String toString()</code>, <code>additionalPrice()</code> and so on. <em>That</em> would make sense. And then use a <code>RoomProperty[] properties = new RoomProperties[10];</code>. Instead of fixed size arrays you will later learn dynamic, growing List (i.e. ArrayList).</li>\n<li>A penthouse could then be realized by a Room subclass that fills its initial properties with a <code>HavingPet</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T07:16:23.310", "Id": "480890", "Score": "1", "body": "*double haustier (pet) would make me shiver* - very nice!!!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T06:32:13.617", "Id": "244922", "ParentId": "244829", "Score": "3" } }, { "body": "<h1>Naming</h1>\n<p>Naming is really important. There are conventions that help to give helpful hints to the reader about what a name refers to. <code>camelCase</code> names on their own are typically going to be variables, <code>camelCase(</code> with parenthesis are likely to be function calls. <code>Capitals</code> are typically used for classes, constants, enums.</p>\n<p>So, when I see something like this:</p>\n<blockquote>\n<pre><code>Booking(hotel);//Methode zum Buchen\n</code></pre>\n</blockquote>\n<p>It takes more processing to figure out what <code>Booking</code> is referring to, because it looks like a constructor call. This is reinforced by the name itself <code>Booking</code> sounds like a thing, rather than an action, so I'm expecting it to be a class name. If you need to add a comment to tell you it's the booking method, then it's probably a good sign that the name could be improved... <code>createBooking</code> might be a more descriptive name.</p>\n<h1>Don't cheat with your names...</h1>\n<blockquote>\n<pre><code>boolean roomservice;\nstatic double zimmerservice = 10;\n</code></pre>\n</blockquote>\n<p>I'd suggest picking a single language for your actual code, commenting in a different language is fine, however if you use both languages for the code then you can get into situations like the one above where you basically have the same name, meaning two different things. This is confusing. One of these should really have a different name. <code>roomServiceCost</code> perhaps?</p>\n<h1>Money...</h1>\n<p>People are funny about losing money to rounding errors... Generally when you're dealing with Money you want to consider using <code>BigDecimal</code>, rather than <code>double</code>. It is a bit harder to work with than <code>double</code> though and for this application may not be necessary.</p>\n<h1>Customer Interface?</h1>\n<blockquote>\n<pre><code>private static boolean CustomerInterface = true;//Hauptprogramm boolean\n</code></pre>\n</blockquote>\n<p>It's really unclear what this variable is for. It seems like it's possibly supposed to be used to determine if the interface is displayed, however it's always set to true...</p>\n<h1>Duplication</h1>\n<p>Look out for duplication in your code. It's a good sign that there may be other abstractions, either methods or classes. So, in your <code>Booking</code> method, you're doing more or less the same thing in each of the <code>case</code>'s</p>\n<blockquote>\n<pre><code> case &quot;2&quot;:\n if (hotel[1].getAvailable(hotel[1].available)) {\n int roomNr = 1;\n PreisKategorie(hotel, roomNr);\n Breakfast(hotel, roomNr);\n Balcony(hotel, roomNr);\n BookingPeriode(hotel, roomNr);\n FinalizeBooking(hotel, roomNr);\n</code></pre>\n</blockquote>\n<p>Consider if there's a way to convert the <code>userInput</code> into a number that can be used to drive this booking experience and remove some of this redundancy.</p>\n<h1>Call Depth</h1>\n<p>Be careful about call circles. So, your <code>Booking</code> method, can call <code>AldreadyBooked</code>, which in turn calls back to <code>Booking</code>. Each method call adds to the call stack. If this happens enough times, then you're running the risk of a stack overflow. Rather than following this circle, consider if there's a way to pass indicate success/failure back up to the caller so that it can make a decision about what to do next, rather than calling back out to the caller like this.</p>\n<h1>Booking vs Room vs Request</h1>\n<p>The most obvious first step for a split in your data is to consider what are attributes of a Room and what are attributes of a booking.</p>\n<p>A <code>Room</code> has certain attributes that aren't related to a booking, they're just a part of the room. That might be things like <code>roomNumber</code>, <code>beds</code>, <code>toilets</code>, <code>allowsPets</code> etc.</p>\n<p>A <code>RoomBooking</code> on the other hand might consist of things related to a specific booking, so things like <code>bookedRoom</code>, <code>price</code>, <code>breakfastRequired</code> etc.</p>\n<p>You then might have another abstraction, such as <code>BookingRequest</code>, which would have things like <code>numberPeople</code>, <code>breakfastRequired</code>, <code>fromDate</code>, <code>numberNights</code> etc, which could be used to determine which rooms would satisfy the customer and which are available.</p>\n<p>Having these sorts of abstractions makes it easier to think about how to rework the logic to add extra functionality... so, for example if the customer only needs to have room for a single, but all of the rooms with a single bed are reserved, then you could offer them a double room instead.</p>\n<h1>Visibility</h1>\n<p>Your <code>Room</code> class has one private member and a lot of internal ones. Consider if this really makes sense...</p>\n<h1>Statics</h1>\n<p>If you're going to have <code>static</code>s in your <code>class</code>, it's a good idea to group them together, rather than sprinkling them amongst the other variables.</p>\n<p>If your statics are supposed to be constant, which I think a lot of yours are, you should mark them as <code>final</code> to indicate that they're not going to change.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T07:51:08.823", "Id": "244926", "ParentId": "244829", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T12:19:03.460", "Id": "244829", "Score": "5", "Tags": [ "java", "beginner", "homework" ], "Title": "Hotel booking with multiple options. Improvement through subclasses?" }
244829
<p>I have below code which works fine as its written in <code>bash</code>, i am just posting it here to see if this can be better optimised as per the BASH way. I am have an intermediate understanding in <code>bash</code> so, looking for any expert advise.</p> <p>Thanks for the reveiw and comments in advanced .</p> <h2>BASH CODE:</h2> <pre><code>#!/bin/bash ####################################################################### # Section-1 , this script logs in to the Devices and pulls all the Data ####################################################################### # timestamp to be attached to the log file TIMESTAMP=$(date &quot;+%m%d%Y-%H%M%S&quot;) # logfile to collect all the Firmware Version of C7000 components LOGFILE_1=&quot;/home/myuser/firmware_version-${TIMESTAMP}.log&quot; LOGFILE_2=&quot;/home/myuser/fmv_list-${TIMESTAMP}.log&quot; # read is a built-in command of the Bash shell. It reads a line of text from standard input. # -r option used for the &quot;raw input&quot;, -s option used for Print the string prompt, # while option -s tells do not echo keystrokes when read is taking input from the terminal. # So, altogether it reads password interactively and save it to the environment read -rsp $'Please Enter password below:\n' SSHPASS export SSHPASS for host in $(cat enc_list); do echo &quot;========= $host =========&quot;; sshpass -e timeout -t 20 ssh -o &quot;StrictHostKeyChecking no&quot; $host -l tscad show firmware summary ; done | tee -a &quot;${LOGFILE_1}&quot; # at last clear the exported variable containing the password unset SSHPASS ###################################################################################### # Section-2, This will just grep the desired data from the log file as produced from # Section-1, log file ###################################################################################### data_req=&quot;`ls -l /home/myuser/firmware_version-* |awk '{print $NF}'| tail -1`&quot; cat &quot;${data_req}&quot; | egrep '=|1 BladeSystem|HP VC' | awk '{$1=$1};1' | tee -a &quot;${LOGFILE_2}&quot; </code></pre> <h2>Data Pulled by Script as outlined in section-1 in the code.</h2> <pre><code>========= enc1001 ========= HPE BladeSystem Onboard Administrator (C) Copyright 2006-2018 Hewlett Packard Enterprise Development LP OA-9457A55F4C75 [SCRIPT MODE]&gt; show firmware summary Enclosure Firmware Summary Blade Offline Firmware Discovery: Disabled Onboard Administrator Firmware Information Bay Model Firmware Version --- -------------------------------------------------- ---------------- 1 BladeSystem c7000 DDR2 Onboard Administrator with KVM 4.85 2 OA Absent Enclosure Component Firmware Information Device Name Location Version NewVersion ----------------------------------------------------------------------------------- TRAY | BladeSystem c7000 Onboard Administrator Tray | - | 1.7 | 1.7 FAN | Active Cool 200 Fan | 1 | 2.9.4 | 2.9.4 FAN | Active Cool 200 Fan | 2 | 2.9.4 | 2.9.4 FAN | Active Cool 200 Fan | 3 | 2.9.4 | 2.9.4 FAN | Active Cool 200 Fan | 4 | 2.9.4 | 2.9.4 FAN | Active Cool 200 Fan | 5 | 2.9.4 | 2.9.4 FAN | Active Cool 200 Fan | 6 | 2.9.4 | 2.9.4 FAN | Active Cool 200 Fan | 7 | 2.9.4 | 2.9.4 FAN | Active Cool 200 Fan | 8 | 2.9.4 | 2.9.4 FAN | Active Cool 200 Fan | 9 | 2.9.4 | 2.9.4 FAN | Active Cool 200 Fan | 10 | 2.9.4 | 2.9.4 BLD | HP Location Discovery Services | - | 2.1.3 | 2.1.3 Device Firmware Information Device Bay: 1 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 09/12/2016 iLO4 2.50 Sep 23 2016 Power Management Controller 1.0.9 Device Bay: 2 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 09/12/2016 iLO4 2.50 Sep 23 2016 Power Management Controller 1.0.9 Device Bay: 3 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 05/21/2018 iLO4 2.61 Jul 27 2018 Power Management Controller 1.0.9 Device Bay: 4 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 09/12/2016 iLO4 2.50 Sep 23 2016 Power Management Controller 1.0.9 Device Bay: 5 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 09/12/2016 iLO4 2.50 Sep 23 2016 Power Management Controller 1.0.9 Device Bay: 6 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 09/12/2016 iLO4 2.50 Sep 23 2016 Power Management Controller 1.0.9 Device Bay: 7 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 09/12/2016 iLO4 2.50 Sep 23 2016 Power Management Controller 1.0.9 Device Bay: 8 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 10/25/2017 iLO4 2.70 May 07 2019 Power Management Controller 1.0.9 Device Bay: 9 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 09/12/2016 iLO4 2.70 May 07 2019 Power Management Controller 1.0.9 Device Bay: 10 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 10/25/2017 iLO4 2.55 Aug 16 2017 Power Management Controller 1.0.9 Device Bay: 11 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 10/25/2017 iLO4 2.55 Aug 16 2017 Power Management Controller 1.0.9 Device Bay: 12 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 05/05/2016 iLO4 2.40 Dec 02 2015 Power Management Controller 1.0.9 Device Bay: 13 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 12/28/2015 iLO4 2.40 Dec 02 2015 Power Management Controller 1.0.9 Device Bay: 14 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 05/05/2016 iLO4 2.40 Dec 02 2015 Power Management Controller 1.0.9 Device Bay: 15 Discovered: No Firmware Component Current Version Firmware ISO Version ------------------------------------ -------------------- --------------------- System ROM I36 09/12/2016 iLO4 2.70 May 07 2019 Power Management Controller 1.0.9 Interconnect Firmware Information Bay Device Model Firmware Version --- -------------------------- ---------------- 1 HP VC Flex-10/10D Module 4.50 2 HP VC Flex-10/10D Module 4.50 </code></pre> <h2>The Overall output of the code is as follows:</h2> <pre><code>========= enc1001 ========= 1 BladeSystem c7000 DDR2 Onboard Administrator with KVM 4.85 1 HP VC Flex-10/10D Module 4.50 2 HP VC Flex-10/10D Module 4.50 </code></pre> <p>Thanks </p>
[]
[ { "body": "<ul>\n<li>there is no need for final semicolon <code>;</code></li>\n</ul>\n<h1>loop</h1>\n<pre><code>for host in $(cat enc_list);\n</code></pre>\n<ul>\n<li><code>$(cat )</code> can be writen as <code>$(&lt; )</code>, latter form is builtin and will not fork a <code>cat</code> command.</li>\n</ul>\n<h1>data</h1>\n<pre><code>data_req=&quot;`ls -l /home/myuser/firmware_version-* |awk '{print $NF}'| tail -1`&quot;\n</code></pre>\n<ul>\n<li>no need for quote</li>\n<li>back tick ( ` ) is deprecated use <code>$( )</code> construct.</li>\n<li>you use <code>ls -l</code> then <code>awk</code> to filter filename ( <code>$NF</code> ), just use <code>ls | tail -1</code></li>\n<li>sorting by <code>ls</code> won't work when year change.</li>\n<li>sorting <code>ls</code> is frowned upon (well if you build all the sorted files without space or newline in their name, it might be OK)</li>\n<li>if you still want <code>ls</code> sorting use either <code>ls -t</code> or <code>ls -rt</code> to filter by date (newest first, oldest first)</li>\n<li>use <code>\\ls</code> to skip any aliased <code>ls</code> (when piped ls will put one file per line, this can be forced by <code>ls -1</code>, column display can be forced with <code>ls -C</code> )</li>\n<li>you use <code>${LOGFILE_1}</code> above, then use a parsed <code>ls</code> to retrieve the file, why not use <code>${LOGFILE_1}</code> again ?</li>\n</ul>\n<h1>parsing</h1>\n<pre><code>cat &quot;${data_req}&quot; | egrep '=|1 BladeSystem|HP VC' | awk '{$1=$1};1' | tee -a &quot;${LOGFILE_2}&quot;\n</code></pre>\n<ul>\n<li><code>grep</code> can read file, this is a useless use of cat.</li>\n<li><code>awk '{$1=$1};1'</code> will do nothing</li>\n</ul>\n<p>the line can be written as</p>\n<pre><code>egrep '=|1[ ]+BladeSystem|HP VC' &quot;${LOGFILE_1}&quot; | tee -a &quot;${LOGFILE_2}&quot;\n</code></pre>\n<hr />\n<ul>\n<li>I am pretty sure you can use public/private keys with HP enclosure.</li>\n<li>those enclosure might give you XML answer, it might be worth the effort to analyse and parse it using XML tools ( xmlstartlet/xsltproc/xmllint ), not awk/sed/grep</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T05:30:38.623", "Id": "480754", "Score": "0", "body": "Thanks for the detailed reveiw @Archemer, +1 , However.. i have to use `awk '{$1=$1};1'` for trimming the trailing white spaces because this is causing issue for me while i am using a python parser to modify the data... even after using strip/lstrip or rstrip, so for now its kind of required. Secondly, i can not use `${LOGFILE_1}` again as it will not match the TIMESTAMP which i defined based to `TIMESTAMP=$(date \"+%m%d%Y-%H%M%S\")` which looks/ count for a seconds as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T19:50:40.590", "Id": "244849", "ParentId": "244835", "Score": "3" } } ]
{ "AcceptedAnswerId": "244849", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T14:54:52.593", "Id": "244835", "Score": "5", "Tags": [ "bash", "linux", "shell" ], "Title": "Bash Code optimization For ssh login on the remote device" }
244835
<p>The objective is to get a list of number and then switch the last person surname with the first person surname; when I type '$' it do the changes and finish the program! (POINTERS and DYNAMIC ALLOCATION).</p> <p>I have to use pointers and dynamic allocation, my code is nice, but I know that it can be better.</p> <p>How can I start to identify parts of my code that could be extracted to functions?</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; int main() { char ***names=NULL; int i, j, k, letter, totalNames, auxInt; int *wordsbyname= NULL; char *auxWord; i=j=k=0; do { names=realloc(names, (i+1)*sizeof(char**)); names[i]=NULL; wordsbyname=realloc(wordsbyname, (i+1)*sizeof(int)); j=0; do { names[i]=realloc(names[i],(j+1)*sizeof(char*)); names[i][j]=NULL; k=0; do{ letter=getchar(); names[i][j]=realloc(names[i][j], (k+1)*sizeof(char)); names[i][j][k]=letter; k++; }while ((letter!= 10) &amp;&amp; (letter!=32) &amp;&amp; (letter!=36)); names[i][j][k-1]='\0'; j++; }while((letter!= 10)&amp;&amp;(letter!=36)); wordsbyname[i]=j; i++; }while (letter!=36); totalNames=i; printf(&quot;\n&quot;); for(i=0;i&lt;totalNames/2;i++){ auxInt=totalNames-i-1; auxWord=malloc(sizeof(char)*(strlen(names[i][wordsbyname[i]-1])+1)); strcpy(auxWord,names[i][wordsbyname[i]-1]); names[i][wordsbyname[i]-1]=realloc(names[i][wordsbyname[i]-1], sizeof(char)*strlen((names[auxInt][wordsbyname[auxInt]-1])+1)); strcpy(names[i][wordsbyname[i]-1],names[auxInt][wordsbyname[auxInt]-1]); names[auxInt][wordsbyname[auxInt]-1]=realloc(names[auxInt][wordsbyname[auxInt]-1],sizeof(char)*(strlen(auxWord)+1)); strcpy(names[auxInt][wordsbyname[auxInt]-1],auxWord); free (auxWord); } for(i=0 ; i&lt;totalNames; i++){ for (j=0; j&lt;wordsbyname[i];j++){ printf(&quot;%s &quot;, names[i][j]); free(names[i][j]); } free(names[i]); printf(&quot;\n&quot;); } free(wordsbyname); free(names); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T14:20:59.220", "Id": "480800", "Score": "1", "body": "This post has been un-deleted by the community, with the following rationale: it was on-topic; and any concerns about language were intended to communicate that the descriptive bodies of answers are in English on StackExchange. I apologise that I did not make that clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T16:39:08.227", "Id": "480823", "Score": "2", "body": "@Miguel Avila I noticed you formatted code. Suggest reviewing [Should you edit someone else's code in a question?](https://codereview.meta.stackexchange.com/q/762/29485), rollback your edit and apply reinderien changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T17:50:05.830", "Id": "480827", "Score": "1", "body": "@MiguelAvila Please stop editing / formatting code we generally don't approve code edits unless they are made by the original poster. Format is part of what gets reviewed, especially certain languages such as python." } ]
[ { "body": "<p>I can't comment on variable names because I don't know your language, this will limit the scope of the review I can do and I hope you understand everything in this review / answer. The memory management is good, I don't see any memory leaks.</p>\n<p><strong>Test for Possible Memory Allocation Errors</strong><br />\nIn modern high level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. While it rare in modern computers because there is so much memory, memory allocation can fail, especially if the code is working in a limited memory application such as embedded control systems. In the C programming language when memory allocation fails, the functions <code>malloc()</code>, <code>calloc()</code> and <code>realloc()</code> return <code>NULL</code>. Referencing any memory address through a <code>NULL</code> pointer results in <strong>unknown behavior</strong> (UB).</p>\n<p>Possible unknown behavior in this case can be a memory page error (in Unix this would be call Segmentation Violation), corrupted data in the program and in very old computers it could even cause the computer to reboot (corruption of the stack pointer).</p>\n<p>To prevent this <strong>unknown behavior</strong> a best practice is to always follow the memory allocation statement with a test that the pointer that was returned is not NULL.</p>\n<p><em>Example of Current Code:</em></p>\n<pre><code> nomes = realloc(nomes, (i + 1) * sizeof(char **));\n nomes[i] = NULL;\n palavraspornome = realloc(palavraspornome, (i + 1) * sizeof(int));\n j = 0;\n do\n</code></pre>\n<p><em>Example of Current Code with Test:</em></p>\n<pre><code> do\n {\n nomes = realloc(nomes, (i + 1) * sizeof(char **));\n if (nomes != NULL)\n {\n nomes[i] = NULL;\n palavraspornome = realloc(palavraspornome, (i + 1) * sizeof(int));\n if (palavraspornome == NULL)\n {\n fprintf(stderr, &quot;Memory allocation error when allocating palavraspornome.\\nUnable to recover, program exiting.\\n&quot;);\n return EXIT_FAILURE;\n }\n }\n else {\n fprintf(stderr, &quot;Memory allocation error when allocating nomes.\\nUnable to recover, program exiting.\\n&quot;);\n return EXIT_FAILURE;\n }\n j = 0;\n do\n</code></pre>\n<p>A good way to get rid of some of the code repetition would be to create a function that allocates memory, does the test, reports the error when it happens and exits the program.</p>\n<pre><code>void *safe_memory_allocation(size_t size_to_allocate)\n{\n void *return_pointer = malloc(size_to_allocate);\n if (return_pointer == NULL)\n {\n fprintf(stderr, &quot;Memory allocation error .\\nUnable to recover, program exiting.\\n&quot;);\n exit(EXIT_FAILURE);\n }\n \n return return_pointer;\n}\n</code></pre>\n<p><strong>Convention When Using Memory Allocation in C</strong><br />\nWhen using malloc(), calloc() or realloc() in C a common convetion is to sizeof(*PTR) rather sizeof(PTR_TYPE), this make the code easier to maintain and less error prone, since less editing is required if the type of the pointer changes.</p>\n<pre><code> do\n {\n nomes = realloc(nomes, (i + 1) * sizeof(*nomes);\n if (nomes != NULL)\n {\n nomes[i] = NULL;\n palavraspornome = realloc(palavraspornome, (i + 1) * sizeof(*palavraspornome));\n if (palavraspornome == NULL)\n {\n fprintf(stderr, &quot;Memory allocation error when allocating palavraspornome.\\nUnable to recover, program exiting.\\n&quot;);\n return EXIT_FAILURE;\n }\n }\n else {\n fprintf(stderr, &quot;Memory allocation error when allocating nomes.\\nUnable to recover, program exiting.\\n&quot;);\n return EXIT_FAILURE;\n }\n j = 0;\n do\n</code></pre>\n<p><strong>Complexity</strong><br />\nThe function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>There are at least 3 sub functions that can be extracted from <code>main()</code>, each of the major loops is a candidate for a function, some of the smaller loops may also be good candidates. A sample function that you could implement if you are not on a <code>POSIX</code> where this is a C library function is <a href=\"https://en.cppreference.com/w/c/experimental/dynamic/strdup\" rel=\"nofollow noreferrer\">char *strdup(const char *str1)</a> (this function was merged into the C ISO standard in 2019).</p>\n<p>The implementation of <code>strdup()</code> would look something like this:</p>\n<pre><code>char *strdup(const char *original_string)\n{\n size_t new_size = strlen(original_string) + 1;\n char *duplicate = calloc(sizeof(*original_string), new_size);\n if (duplicate != NULL)\n {\n memcpy(&amp;duplicate[0], original_string, new_size);\n }\n return duplicate;\n}\n</code></pre>\n<p>Whether you write or own or use the library version <code>strdup()</code> returns NULL if the memory allocation failed so the value must be tested before use.</p>\n<p><strong>Possible Performance Improvements</strong><br />\nRather than use character input (<code>letra = getchar();</code>) get a line of text at a time using <a href=\"http://www.cplusplus.com/reference/cstdio/fgets/\" rel=\"nofollow noreferrer\">fgets(char *buffer, size_t buffer_size, FILE *filename)</a>. This reduces the amount of code necessary and it will be faster than character input.</p>\n<p><em>Instead of</em></p>\n<pre><code> do\n {\n nomes[i] = realloc(nomes[i], (j + 1) * sizeof(char *));\n nomes[i][j] = NULL;\n k = 0;\n do\n {\n letra = getchar();\n nomes[i][j] = realloc(nomes[i][j], (k + 1) * sizeof(char));\n nomes[i][j][k] = letra;\n k++;\n } while ((letra != 10) &amp;&amp; (letra != 32) &amp;&amp; (letra != 36));\n nomes[i][j][k - 1] = '\\0';\n j++;\n } while ((letra != 10) &amp;&amp; (letra != 36));\n</code></pre>\n<p>Use</p>\n<pre><code> do\n {\n nomes[i] = realloc(nomes[i], (j + 1) * sizeof(char *));\n nomes[i][j] = NULL;\n k = 0;\n char buffer[1024];\n if (fgets(buffer, 1024, stdin) != 0)\n {\n nomes[i] = strdup(buffer);\n }\n j++;\n } while ((letra != 10) &amp;&amp; (letra != 36));\n palavraspornome[i] = j;\n</code></pre>\n<p>Rather than calling realloc() for every new string create an array of an arbitrary number of names and then reallocate that array when the capacity is reached.\n<em>the following code is a basic idea, it may not compile properly or run</em></p>\n<pre><code>char ***resize_nomes_array(char ***nomes, size_t *current_capacity, int i)\n{\n char ***new_nomes = NULL;\n\n if (current_capacity == 0)\n {\n *current_capacity = 10;\n }\n else\n {\n *current_capacity = (size_t)(*current_capacity * 1.5);\n }\n\n if (nomes == NULL)\n {\n new_nomes = calloc(*current_capacity, sizeof(*new_nomes));\n }\n else\n {\n new_nomes = realloc(nomes, *current_capacity * sizeof(*nomes));\n }\n\n if (new_nomes == NULL) {\n fprintf(stderr, &quot;Memory allocation error when allocating nomes.\\nUnable to recover, program exiting.\\n&quot;);\n exit(EXIT_FAILURE);\n }\n\n for (size_t index = i; index &lt; *current_capacity; index++)\n {\n new_nomes[index] = NULL;\n }\n return new_nomes;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T23:10:49.320", "Id": "480867", "Score": "0", "body": "It's called _undefined behavior_, not _unknown_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T23:12:41.990", "Id": "480868", "Score": "0", "body": "Why `calloc` in `strdup`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T00:00:22.520", "Id": "480869", "Score": "0", "body": "@RolandIllig to automatically set the last character to `\\0`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T05:53:49.943", "Id": "480884", "Score": "0", "body": "That's a useless argument since the code already copies `n + 1` bytes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T19:54:10.553", "Id": "480985", "Score": "0", "body": "@RolandIllig suppose you explain why calloc() rather than malloc() is a bad idea?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-04T01:55:39.640", "Id": "481008", "Score": "0", "body": "Can I change the entire code and keep it running normally? I have to change this code anda have no idea how to make that!\n\nThank you for you help" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-04T02:05:21.473", "Id": "481009", "Score": "0", "body": "You can't change the code in the questions, you can post a new question with the updated code and create a link to this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-04T11:07:11.677", "Id": "481028", "Score": "0", "body": "My main point of preferring `malloc` over `calloc` is that it is more commonly used and has a simpler API. On the other hand, `calloc` (hopefully) performs an overflow check on the product of the two parameters. Therefore the more complicated API should be preferred." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:58:44.433", "Id": "244900", "ParentId": "244838", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T16:42:26.330", "Id": "244838", "Score": "4", "Tags": [ "c", "pointers" ], "Title": "Switching first names with surnames" }
244838
<p>I have created a small selenium script that checks for available times to write a test for a drivers license. The program runs every minute and takes approx 50 seconds to run. I have noticed that it's quite unstable, and do not preform optimally because the web-page loads elements dynamically. Even if I use seleniums <code>wait</code> I am unable to optimise it fully as connectivity vary on my wifi, and may lead to longer loading times than expected. Feedback on error-handling and code optimisation for greater stability would be highly appreciated and how to schedule the task to run without a back-log of jobs waiting to be executed as memory is small on my mac-book air 2013.</p> <pre class="lang-py prettyprint-override"><code>import datetime import schedule import threading from datetime import date import smtplib import time import multiprocessing as mp from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import TimeoutException from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait def selenium_get_time(ort): &quot;&quot;&quot;Checks if time is available for a county&quot;&quot;&quot; options = Options() options.headless = True driver = webdriver.Chrome(chrome_options=options, executable_path='/Users/andreas/.wdm/chromedriver/83.0.4103.39/mac64/chromedriver') driver.get(&quot;https://fp.trafikverket.se/boka/#/search/dIccADaISRCIi/5/0/0/0&quot;) element = WebDriverWait(driver, 40).until(EC.element_to_be_clickable((By.CLASS_NAME, &quot;form-control&quot;))) driver.find_element_by_xpath(&quot;//select[@id='examination-type-select']/option[@value='3']&quot;).click() driver.find_element_by_xpath(&quot;//select[@id='language-select']/option[@value='13']&quot;).click() driver.find_element_by_id('id-control-searchText').clear() inputElement = driver.find_element_by_id(&quot;id-control-searchText&quot;) inputElement.send_keys(ort) inputElement.send_keys(Keys.ENTER) # time.sleep(10) try: element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, &quot;//div[@class='col-sm-3 text-center']/button[@data-bind='click:$parent.select']&quot;))) first_time = driver.find_element_by_xpath(&quot;//div[@class='col-xs-6']/strong&quot;) return first_time.text except (NoSuchElementException, TimeoutException) as e: driver.close() if NoSuchElementException: print('Nothing found for: ', ort, ' NoElemFound') driver.close() driver.quit() else: print('Nothing found for: ', ort, ' TimedOut') driver.close() driver.quit() def convert_time(time_stamp): &quot;&quot;&quot;converts a timestamp&quot;&quot;&quot; date_time_obj = datetime.datetime.strptime(time_stamp, '%Y-%m-%d %H:%M') return date_time_obj def check_schedule(date, start_date, end_date): start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d') end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d') if start_date &lt;= date &lt;= end_date: return True else: return False def send_email(first_availible, ort): &quot;&quot;&quot;sends an email&quot;&quot;&quot; gmailUser = 'nor###rov@###.com' gmailPassword = '######' recipient = '###########' message=msg = 'Första lediga tid i'+' '+ str(ort) +' '+ str(first_availible) +' '+ 'https://fp.trafikverket.se/boka/#/search/SPHHISiPAfhpP/5/0/0/0' msg = MIMEMultipart() msg['From'] = gmailUser msg['To'] = recipient msg['Subject'] = &quot;Ledig tid körkortsprov&quot; msg.attach(MIMEText(message)) mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmailUser, gmailPassword) mailServer.sendmail(gmailUser, recipient, msg.as_string()) mailServer.close() def main(ort): &quot;&quot;&quot;main program&quot;&quot;&quot; first_availible = selenium_get_time(ort) if first_availible: date = convert_time(first_availible) if check_schedule(date, '2020-07-01', '2020-07-05'): print('FOUND: ', ort +' '+ first_availible) send_email(first_availible, ort) else: now = datetime.datetime.now() dt_string = now.strftime(&quot;%H:%M:%S&quot;) print('Found Nothing for: ', ort, ' ', dt_string) def run(): &quot;&quot;&quot;runs program&quot;&quot;&quot; ORTER = ['Södertälje', 'Stockholm', 'Järfälla', 'Sollentuna'] for ort in ORTER: main(ort) def worker(): &quot;&quot;&quot;&quot;spans processes for program&quot;&quot;&quot; p = mp.Process(target=run) # run `worker` in a subprocess p.start() # make the main process wait for `worker` to end p.join() # all memory used by the subprocess will be freed to the OS if __name__ == '__main__': &quot;&quot;&quot;schedule to run every minute&quot;&quot;&quot; schedule.every(55).seconds.do(worker) while True: try: schedule.run_pending() time.sleep(1) except Exception as e: schedule.run_pending() time.sleep(1) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T19:31:25.510", "Id": "480714", "Score": "0", "body": "Scrapy with splash can be used but I haven't used it personally because it's not easy to use. It's a well known fact that selenium is slow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T20:27:12.653", "Id": "480724", "Score": "1", "body": "@VisheshMangla I haven't used it either, and barely know enough to execute a proper selenium script. Thank you for pointing out that selenium is sub-par on speed, will keep that for future reference!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T06:17:27.257", "Id": "480755", "Score": "0", "body": "Learning scrapy basics is super easy, https://www.youtube.com/watch?v=vkA1cWN4DEc&list=PLZyvi_9gamL-EE3zQJbU5N3nzJcfNeFHU but I left watching the tutorial on 8th video." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T07:24:07.117", "Id": "480759", "Score": "0", "body": "@VisheshMangla Thank you for the resource, will check it out!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T15:22:07.110", "Id": "480810", "Score": "0", "body": "Selenium is made for testing your created websites, not for scrapping them." } ]
[ { "body": "<h1><code>convert_time</code></h1>\n<p>This function can just be</p>\n<pre><code>def convert_time(time_stamp):\n return datetime.datetime.strptime(time_stamp, '%Y-%m-%d %H:%M')\n</code></pre>\n<h1><code>check_schedule</code></h1>\n<p>This function can just be</p>\n<pre><code>def check_schedule(date, start_date, end_date):\n start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')\n end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')\n return start_date &lt;= date &lt;= end_date\n</code></pre>\n<p>Since the last line is a boolean comparison in itself.</p>\n<h1>Proper scraping tools</h1>\n<p>Selenium doesn't have a reputation for being a good website scraper. Here are a few that do:</p>\n<ul>\n<li><a href=\"https://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeautifulSoup4</a></li>\n<li><a href=\"https://github.com/lxml/lxml\" rel=\"nofollow noreferrer\">LXML</a></li>\n<li><a href=\"https://3.python-requests.org\" rel=\"nofollow noreferrer\">Requests</a> (Mainly HTTP Requests, but can be helpful)</li>\n<li><a href=\"https://scrapy.org\" rel=\"nofollow noreferrer\">Scrapy</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-14T04:04:42.267", "Id": "245445", "ParentId": "244839", "Score": "0" } }, { "body": "<p>Optimized code: Runs fast, stable and does not consume more RAM over time.</p>\n<pre><code>###For written test\n\nimport datetime\nimport schedule\nimport threading\n\nfrom datetime import date\n\nimport smtplib\nimport time\n\nimport multiprocessing as mp\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom urllib3.exceptions import MaxRetryError\nfrom urllib3.exceptions import NewConnectionError\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\ndriver = None \n\n\ndef tear_down():\n driver.quit()\n\n\ndef selenium_get_time(ort):\n global driver\n options = Options()\n options.headless = True\n driver = webdriver.Chrome(chrome_options=options, executable_path='/Users/andreas/.wdm/chromedriver/83.0.4103.39/mac64/chromedriver')\n driver.get(&quot;https://fp.trafikverket.se/boka/#/search/dIccADaISRCIi/5/0/0/0&quot;)\n element = WebDriverWait(driver, 40).until(EC.element_to_be_clickable((By.CLASS_NAME, &quot;form-control&quot;)))\n driver.find_element_by_xpath(&quot;//select[@id='examination-type-select']/option[@value='3']&quot;).click()\n driver.find_element_by_xpath(&quot;//select[@id='language-select']/option[@value='13']&quot;).click()\n driver.find_element_by_id('id-control-searchText').clear()\n inputElement = driver.find_element_by_id(&quot;id-control-searchText&quot;)\n inputElement.send_keys(ort)\n inputElement.send_keys(Keys.ENTER)\n # time.sleep(10)\n try:\n element = WebDriverWait(driver, 40).until(EC.element_to_be_clickable((By.XPATH, &quot;//div[@class='col-sm-3 text-center']/button[@data-bind='click:$parent.select']&quot;)))\n first_time = driver.find_element_by_xpath(&quot;//div[@class='col-xs-6']/strong&quot;)\n return first_time.text\n except (NoSuchElementException, TimeoutException, MaxRetryError, ConnectionRefusedError, NewConnectionError) as e:\n if NoSuchElementException:\n print('Nothing found for: ', ort, ' NoElemFound')\n elif MaxRetryError or ConnectionRefusedError or NewConnectionError:\n print('Connection TimedOut: ', ort)\n else:\n print('Nothing found for: ', ort, ' TimedOut')\n finally:\n driver.close()\n driver.quit()\n\n\n\ndef convert_time(time_stamp):\n date_time_obj = datetime.datetime.strptime(time_stamp, '%Y-%m-%d %H:%M')\n return date_time_obj\n\ndef check_schedule(date, start_date, end_date):\n start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')\n end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')\n if start_date &lt;= date &lt;= end_date:\n return True\n else:\n return False\n\ndef send_email(first_availible, ort):\n gmailUser = '####@gmail.com'\n gmailPassword = '#######'\n recipient = '########@gmail.com'\n message=msg = 'Första lediga tid i'+' '+ str(ort) +' '+ str(first_availible) +' '+ 'https://fp.trafikverket.se/boka/#/search/SPHHISiPAfhpP/5/0/0/0'\n\n msg = MIMEMultipart()\n msg['From'] = gmailUser\n msg['To'] = recipient\n msg['Subject'] = &quot;Ledig tid körkortsprov&quot;\n msg.attach(MIMEText(message))\n\n mailServer = smtplib.SMTP('smtp.gmail.com', 587)\n mailServer.ehlo()\n mailServer.starttls()\n mailServer.ehlo()\n mailServer.login(gmailUser, gmailPassword)\n mailServer.sendmail(gmailUser, recipient, msg.as_string())\n mailServer.close()\n\ndef main(ort):\n first_availible = selenium_get_time(ort)\n if first_availible:\n date = convert_time(first_availible)\n if check_schedule(date, '2020-07-01', '2020-07-05'):\n print('FOUND: ', ort +' '+ first_availible)\n send_email(first_availible, ort)\n else:\n now = datetime.datetime.now()\n dt_string = now.strftime(&quot;%H:%M:%S&quot;)\n print('Found Nothing for: ', ort, ' ', dt_string)\n tear_down()\n\n\n\ndef run():\n ORTER = ['Södertälje', 'Stockholm', 'Järfälla', 'Sollentuna']\n for ort in ORTER:\n main(ort)\n\n\ndef worker():\n p = mp.Process(target=run)\n # run `worker` in a subprocess\n p.start()\n # make the main process wait for `worker` to end\n p.join()\n # all memory used by the subprocess will be freed to the OS\n\n\n\n\nif __name__ == '__main__':\n\n\n schedule.every(10).seconds.do(worker)\n while True:\n try:\n schedule.run_pending()\n time.sleep(1)\n\n except Exception as e:\n schedule.run_pending()\n time.sleep(1)\n \n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T07:38:46.643", "Id": "247885", "ParentId": "244839", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T17:11:12.943", "Id": "244839", "Score": "6", "Tags": [ "python", "python-3.x", "web-scraping", "selenium" ], "Title": "Web scraper for driver's license test times" }
244839
<p>I have modified a recursive function designed to print all the integer partitions of a positive integer to create a function that returns all partitions of the &quot;number&quot; parameter if they include a number contained in the &quot;interesting&quot; parameter. I would like to use this for very large numbers (10-50 million), but am getting errors referring to the recursion depth. My question is whether there is a way to do this more efficiently by recursion, and if not, whether there is another way to do this.</p> <pre><code>def partition(number, interesting): # returns all the partitions of number that are included in the interesting list answer = set() if number in interesting: answer.add((number, )) for x in range(1, number): if x in interesting: for y in partition(number - x, interesting): answer.add(tuple(sorted((x, ) + y))) return answer </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T18:31:08.013", "Id": "480707", "Score": "0", "body": "If you have more of the program you haven't posted, please include it. Also, please rename the question to reflect what you're doing with the application, not your review concerns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T18:41:53.403", "Id": "480983", "Score": "0", "body": "What do you do with your answer? You are returning a `Set[Tuple[int,...]]`, but do you need to return the entire set at once, or could you use return the set elements one at a time using a generator? Is this a programming challenge? If so post a link to the problem, as well as the full problem description in the question, including limits, such as the number of interesting numbers, as well as their ranges." } ]
[ { "body": "<p>Python is not designed for recursion. To avoid stack overflows there is a limit</p>\n<pre><code>In [2]: import sys\n\nIn [3]: sys.getrecursionlimit()\nOut[3]: 1000\n</code></pre>\n<p>So we can easily design a test that will fail</p>\n<pre><code>In [4]: partition(1000, {1})\n---------------------------------------------------------------------------\nRecursionError Traceback (most recent call last)\n&lt;ipython-input-4-884568e60acd&gt; in &lt;module&gt;()\n----&gt; 1 partition(1000, {1})\n\n&lt;ipython-input-1-60a0eb582d3c&gt; in partition(number, interesting)\n 6 for x in range(1, number):\n 7 if x in interesting:\n----&gt; 8 for y in partition(number - x, interesting):\n 9 answer.add(tuple(sorted((x, ) + y)))\n 10 return answer\n\n... last 1 frames repeated, from the frame below ...\n\n&lt;ipython-input-1-60a0eb582d3c&gt; in partition(number, interesting)\n 6 for x in range(1, number):\n 7 if x in interesting:\n----&gt; 8 for y in partition(number - x, interesting):\n 9 answer.add(tuple(sorted((x, ) + y)))\n 10 return answer\n\nRecursionError: maximum recursion depth exceeded in comparison\n</code></pre>\n<p>You may increase the recursion limit</p>\n<pre><code>In [5]: sys.setrecursionlimit(1500)\n\nIn [6]: partition(1000, {1})\nOut[6]: \n{(1, ...\n</code></pre>\n<p>but that is only applicable if your numbers are guaranteed to be in a certain range. Most probably you should implement a non-recursive solution. For 10-50 million you have to.</p>\n<p>If your problem e. g. guarantees <code>1 &lt;= number &lt;= 500</code> you should still do some assertions in your function</p>\n<pre><code>assert 1 &lt;= number &lt;= 500\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T08:19:41.967", "Id": "244927", "ParentId": "244842", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T17:25:16.493", "Id": "244842", "Score": "0", "Tags": [ "python", "recursion", "mathematics" ], "Title": "Recursive Function to Produce Constrained List of Integer Partitions" }
244842
<p>I have a range of two columns that I want to search for a &quot;key&quot; and then find the corresponding value in the directly adjacent column. The key is stored in a dictionary that I populated earlier in the program. I then store the value with its corresponding key in the dictionary to display later.</p> <p>I am using <code>.Find</code> to search the range for the key and then getting the value using <code>.Offset</code> to get the adjacent cell. The code follows:</p> <pre><code>Dim key As Variant Dim filRange As Range Dim found As Range Set filRange = ws.Range(&quot;D2:E36419&quot;).SpecialCells(xlCellTypeVisible) Dim count As Integer Dim i As Long For i = 0 To partsDict.count - 1 key = partsDict.Keys(i) Set found = filRange.Find(key) If Not found Is Nothing Then count = found.Offset(0, 1).value partsDict(i) = count Else partsDict(i) = Empty End If Next i </code></pre> <p>The code functions as expected and I am able to print all values later in the program. The issue is the program takes over 15 seconds to run. I've seen the <code>.Find</code> method is slow and feel like there is a better way to search and retrieve my values. Should I store the range in an array somehow? Use another dictionary? Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T18:58:52.260", "Id": "480710", "Score": "0", "body": "Cant you create a named table for the D:E entries and then search on the named table? This should reduce the search to actually used cells instead of 72k cells." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T19:09:40.243", "Id": "480711", "Score": "0", "body": "Yes, I should have mentioned. I filtered the table before the loop and the range being searched is just the visible cells after the filtering. In the current iteration there are ~16,500 cells in the range." } ]
[ { "body": "<p>The most probable culprit for your performance issues are the constant context switches betwwe vba and Excel whenever you call find. Depending on the number of keys in your dictionary, this can add up.</p>\n<p>One thing you could try is to load the entire <code>filRange</code> into a 2d array via the range's <code>Value</code> property. Then you could search that. Unfortunately, there is no built-in support for that. You could sort the array and then use a binary search for every key.</p>\n<p>One other thing I observed in your code is that you access the dictionary in a way it really is not built for. A dictionary is built to be accessed by key.</p>\n<p>The first thing you can do is to use a <code>For Each</code> loop on <code>partsDict.Keys</code>, i.e. <code>For Each key in partsDict.Keys</code>. Then, when you assign the values, you can do it by key, i.e. <code>partsDict(key) = whatever</code> or <code>partsDict.Item(key)</code>, which is what the first one complies to.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T23:40:57.780", "Id": "480743", "Score": "0", "body": "Do we think putting every pair in a new Dictionary structure would work? I'm thinking once everything is in the Dictionary, searching for my keys should be quick (does Dictionary use hashing?)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T20:40:18.463", "Id": "244852", "ParentId": "244843", "Score": "1" } }, { "body": "<blockquote>\n<pre><code>Set filRange = ws.Range(&quot;D2:E36419&quot;).SpecialCells(xlCellTypeVisible)\n</code></pre>\n</blockquote>\n<p>Hard coding range references will makes your code unnecessarily inflexible. It is best to create a dynamic range reference that will resize itself to fit the data.</p>\n<blockquote>\n<pre><code>With ws\n Set filRange = .Range(&quot;D2:E&quot; &amp; .Rows.Count).End(xlUp)\nEnd With\n</code></pre>\n</blockquote>\n<p>The <code>filRange </code> is set to 2 columns. I am assuming that column 1 is the key column and column 2 is the value column. If this is the case then you should either adjust your fill range:</p>\n<blockquote>\n<pre><code>With ws\n Set filRange = .Range(&quot;D2&quot; &amp; Cells(.Rows.Count, &quot;D&quot;).End(xlUp))\nEnd With\n</code></pre>\n</blockquote>\n<p>Or adjust your search:</p>\n<blockquote>\n<pre><code>Set found = filRange.Columns(1).Find(key)\n</code></pre>\n</blockquote>\n<p><code>Range.CurrentRegion</code> is a convenient way to create a dynamic range.</p>\n<blockquote>\n<p>Set filRange = ws.CurrentRegion.Columns(&quot;D&quot;)</p>\n</blockquote>\n<h2>Question:</h2>\n<blockquote>\n<p>Do we think putting every pair in a new Dictionary structure would work? I'm thinking once everything is in the Dictionary, searching for my keys should be quick (does Dictionary use hashing?).</p>\n</blockquote>\n<h2>Answer:</h2>\n<p>Yes and yes. Dictionaries use hashing for super fast look ups. You may find this article interesting <a href=\"https://analystcave.com/excel-vlookup-vs-index-match-vs-sql-performance/\" rel=\"nofollow noreferrer\">EXCEL VLOOKUP VS INDEX MATCH VS SQL VS VBA</a>.</p>\n<p>The reason that we use dictionaries in the first place is for the super fast look ups. The problem in your project setup is that you are using <code>Range.Find()</code> for your lookups.\nIts hard to give advice about what is the best approach with just a small snippet of code. Proving a more detailed question with all your relevant code, data samples, and perhaps a test stub will give you the best results.</p>\n<h2>Solution</h2>\n<p>Whatever you decide to do the key is to loop over the range values once and use the dictionary lookup up the values. Personally, I would write a function that returns a dictionary that holds the filtered keys and values and compare it to <code>partsDict</code>.</p>\n<pre><code>Function GetFilteredRangeMap(Target As Range, KeyColumn As Variant, ValueColumnOffset As Variant) As Scripting.Dictionary\n \n Dim Column As Range\n \n Rem Set Column to the Visible Cells in the Key Column Range\n With Target.CurrentRegion.Columns(KeyColumn)\n On Error Resume Next\n Set Column = .SpecialCells(xlCellTypeVisible)\n On Error GoTo 0\n End With\n \n If Not Column Is Nothing Then\n Dim Map As New Scripting.Dictionary\n Dim Cell As Range\n For Each Cell In Column\n Map(KeyPrefix &amp; Cell.Value) = Cell.Offset(ValueColumnOffset)\n Next\n End If\n \n Set GetFilteredRangeMap = Map\nEnd Function\n</code></pre>\n<h2>Usage</h2>\n<blockquote>\n<pre><code>Dim Target As Range\nSet Target = Sheet2.Range(&quot;A1&quot;).CurrentRegion\n\nDim Map As New Scripting.Dictionary\nSet Map = GetFilteredRangeMap(Target, 1, 2)\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T12:27:24.803", "Id": "480788", "Score": "0", "body": "GetFilteredRangeMap() did the trick! Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T00:51:12.940", "Id": "480871", "Score": "0", "body": "Thanks for accepting my answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T11:02:50.490", "Id": "244870", "ParentId": "244843", "Score": "2" } }, { "body": "<p>Two things will speed up this:</p>\n<ul>\n<li>read the sheet data into an internal array and work on that</li>\n<li>use an auxiliary dict for searching</li>\n</ul>\n<p>like this</p>\n<pre><code>Sub list2dict()\n ' 2020-07-02\n \n Dim key As Variant\n Dim ws As Worksheet\n \n Dim NewpartsDict As Dictionary\n Set NewpartsDict = New Dictionary\n \n ' Set ws = ...\n \n ' read range data into array\n ' SpecialCells... might contain several areas!\n Dim myData\n Dim partrange As Range\n \n For Each partrange In ws.Range(&quot;D2:E36419&quot;).SpecialCells(xlCellTypeVisible).Areas\n myData = partrange\n ' store array data into auxiliary dict\n Dim i As Long\n For i = 1 To UBound(myData, 1)\n NewpartsDict(myData(i, 1)) = myData(i, 2) ' dict(key) = value\n Next i\n Next partrange\n\n ' update partsDict's existing entries\n For Each key In partsDict\n If NewpartsDict.Exists(key) Then ' a.k.a. Find()\n partsDict(key) = NewpartsDict(key)\n Else\n partsDict(key) = Empty\n End If\n Next key\n \n ' optional: add new entries\n For Each key In NewpartsDict\n If Not partsDict.Exists(key) Then\n partsDict(key) = NewpartsDict(key)\n End If\n Next key\n \n ' now use the updated data in partsDict\n End Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T15:52:10.823", "Id": "480813", "Score": "0", "body": "This looks like something I could use. However, I am getting a type mismatch error in the first for-loop using UBound. Any thoughts about that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T00:50:50.640", "Id": "480870", "Score": "1", "body": "he OP is working with filtered data which will often consist of noncontinuous ranges. The Range that is return by`SpecialCells(xlCellTypeVisible)` consists of 1 Area for each continuous set of cells. In you example, `myData` is only referring to the values of the first area of the target range. In order for an array based approach to work, you will need to iterate over each area of the target range." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T13:45:56.950", "Id": "480923", "Score": "0", "body": "yes, of course. I will work on that, it's not complicated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T14:33:23.290", "Id": "480930", "Score": "1", "body": "I've added a loop over all `.areas` of the visible range, as suggested by @TinMan (thanks!)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-07T13:51:31.017", "Id": "481348", "Score": "0", "body": "@user1016274 I am having some trouble with updating the partsDict's existing entries. Newpartsdict populates fine and has all elements in it. However, after updating partsDict, less than 10 keys have values mapped to them. Weird issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-07T16:18:17.873", "Id": "481374", "Score": "0", "body": "The key search needs to be case-insensitive. You can set a dictionary property to enable this: `dict.CompareMode = vbTextMode` right after `Set NewpartsDict = New Dictionary`. `range.find()` is case-insensitive by default." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-07T17:43:46.387", "Id": "481379", "Score": "0", "body": "Is Newpartsdict.CompareMode = TextCompare the same thing? If it is, I still have the same issue. I get a runtime error using vbTextMode" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-08T14:25:45.460", "Id": "481470", "Score": "0", "body": "The issue was the type of the keys for the two dictionaries. The keys of Newpartdict were being stored as strings while partsDict's keys were doubles. Just had to convert partsDict keys to strings and everything worked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-09T08:40:25.363", "Id": "481529", "Score": "0", "body": "Good you spotted this, I was about to ask for data source samples to debug it. Hope it works satisfactorily." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T12:57:54.977", "Id": "244875", "ParentId": "244843", "Score": "2" } } ]
{ "AcceptedAnswerId": "244875", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T18:31:57.927", "Id": "244843", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Getting Rid of .Find in VBA Code" }
244843
<p>I am communicating with a machine that sends/received structured binary data to my netcore service. The machine supplier's new library uses Memory in their library's API.</p> <p>I have written the following code for Ser/Des which works, but seems verbose. I know I can wrap some of this in methods/helpers, but it feels cumbersome compared to the &quot;old&quot; Streams &amp; BinaryWriter/BinaryReader approach.</p> <p><em><strong>Is there a better way to approach this? A better part of the framework or technique I should be using?</strong></em></p> <h3>Deserialising from Memory:</h3> <pre class="lang-csharp prettyprint-override"><code>public void Read(Memory&lt;byte&gt; data) { if (data.Length &lt; StaticSize) // StaticSize = 56. Defined by machine's struct. throw new ArgumentOutOfRangeException($&quot;Span length too small. Minimum: {StaticSize}, Received: {data.Length}.&quot;); var s = data.Span; MemoryMarshal.TryRead&lt;bool&gt;(s.Slice(0, 1), out _forward); MemoryMarshal.TryRead&lt;bool&gt;(s.Slice(1, 2), out _reverse); SomeString = Encoding.UTF8.GetString(s.Slice(2, 22)).Replace(&quot;\0&quot;, string.Empty); Dynamics = new TcDynamics(data.Slice(24)); // &quot;TcDynamics&quot; object de-serialized in same manner as this. } </code></pre> <h3>Serialising to Memory:</h3> <pre class="lang-csharp prettyprint-override"><code> public void Write(Memory&lt;byte&gt; data) { if (data.Length &lt; StaticSize) // StaticSize = 56. Defined by machine's struct. throw new ArgumentOutOfRangeException($&quot;Span length too small. Minimum: {StaticSize}, Received: {data.Length}.&quot;); var s = data.Span; MemoryMarshal.TryWrite&lt;bool&gt;(s.Slice(0, 1), ref _forward); MemoryMarshal.TryWrite&lt;bool&gt;(s.Slice(1, 2), ref _reverse); Encoding.UTF8.GetBytes(_someString).CopyTo(s.Slice(2,22)); // Strings are fixed length (21 + termination). Dynamics.Write(data.Slice(24)); // &quot;TcDynamics&quot; object serialized in same manner as this. } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T09:47:04.327", "Id": "480766", "Score": "0", "body": "Why do you think it is cumbersome? Have you considered `SequenceReader` and `PipeWriter` [1](https://devblogs.microsoft.com/dotnet/system-io-pipelines-high-performance-io-in-net/), [2](https://docs.microsoft.com/en-us/dotnet/standard/io/pipelines)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T14:27:51.083", "Id": "480801", "Score": "1", "body": "@PeterCsala, when using a binary reader, I could just call something like: `myDouble= reader.ReadDouble();` or `writer.Write(myDouble);` `writer.Write(myString, lengthInBytes);` I know I can create that myself using Facade pattern to hide away most of the above, but thought there would be a better way somewhere else. I will have a look at your suggestions, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T08:05:23.773", "Id": "480897", "Score": "0", "body": "Yes, I agree that those abstractions make the usage more convenient. `Memory`, `Span` and `ReadOnlySpan`were designed to work mainly with `byte`and `char` types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T10:59:14.300", "Id": "481104", "Score": "0", "body": "If the data structure in `data` is the same, couldn't you then load a `MemoryStream` with the data, and then use a `BinaryReader-/Writer as you did before?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T14:53:50.603", "Id": "481122", "Score": "0", "body": "@HenrikHansen, I couldn't figure out how to do this without copying data into the Memory Stream. That feels like I'm losing one of the efficiency benefits of Memory<T>. I.e. I'd be creating memory in the stream to copy the memory<> into. Then the read operation would be copying to variable. The last copy is unavoidable, but the interim one I was hoping to avoid with these new classes. have I misunderstood the MemoryStream WriteAsync docs?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T19:11:26.790", "Id": "244844", "Score": "1", "Tags": [ "c#", "serialization", ".net-core" ], "Title": "Better way to Read /Write Memory<byte> to/from POCO" }
244844
<p>I'm pretty new to php coding, but i know wordpress for a long time. Also experimenting with bootstrap. I created a new Page Template and modified it a bit. What I'm looking for is to optimize this php code:</p> <pre><code>&lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col kb_landing_left&quot;&gt; &lt;?php global $post; $post = get_post(56); setup_postdata($post); get_template_part( 'template-parts/content', 'page', get_post_format() ); ?&gt; &lt;/div&gt; &lt;div class=&quot;col -sm-6&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col kb_landing_right&quot;&gt; &lt;?php global $post; $post = get_post(1); setup_postdata($post); get_template_part( 'template-parts/content', 'page', get_post_format() ); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col kb_landing_right&quot;&gt; &lt;?php global $post; $post = get_post(3); setup_postdata($post); get_template_part( 'template-parts/content', 'page', get_post_format() ); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col kb_landing_right&quot;&gt; &lt;?php global $post; $post = get_post(2); setup_postdata($post); get_template_part( 'template-parts/content', 'page', get_post_format() ); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>As you can see, it's calling for 4 specific post IDs, since i want them to appear on my homepage in a bootsrap grid. I guess this could be done better by using an array?</p> <p>Any suggestion is very much appreciated! Stay healthy!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:54:25.097", "Id": "480739", "Score": "2", "body": "Please do not change the code in the question after you have received a review, read https://codereview.stackexchange.com/help/someone-answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T07:22:53.297", "Id": "480757", "Score": "1", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>Here is an improvement, but I would recommend a few additional changes as well.</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php global $post; ?&gt;\n\n&lt;div class=&quot;col kb_landing_left&quot;&gt;\n &lt;?php\n $post = get_post(56);\n setup_postdata($post);\n get_template_part('template-parts/content', 'page');\n ?&gt;\n&lt;/div&gt;\n&lt;div class=&quot;col -sm-6&quot;&gt;\n &lt;?php foreach ([1, 3, 2] as $post_id) : ?&gt;\n &lt;div class=&quot;row&quot;&gt;\n &lt;div class=&quot;col kb_landing_right&quot;&gt;\n &lt;?php\n $post = get_post($post_id);\n setup_postdata($post);\n get_template_part('template-parts/content', 'page');\n ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php endforeach; ?&gt;\n&lt;/div&gt;\n\n&lt;?php\n// Reset back to the original post\n$post = get_queried_object();\nsetup_postdata($post);\n?&gt;\n</code></pre>\n<p>Since you're new to PHP here are some notes on PHP specifically</p>\n<ul>\n<li>you only need to get the <code>global</code> variable once. Once a global variable is pulled in, it exists for the entire scope (whatever that scope happens to be).</li>\n<li>if your column code is the same it should be in a foreach loop</li>\n</ul>\n<p>Some WordPress stuff</p>\n<ul>\n<li><code>get_template_part</code> should only accept two parameters $slug and $name, maybe you meant <code>get_template_part( 'template-parts/content', 'page' . get_post_format() )</code> possibly?</li>\n<li>changing the global $post will typically cause a lot of problems down the line, so I would not do that unless you're certain it needs to be done. I would recommend something like a WordPress shortcode or PHP function that handles your template for non-current post data. Only use get_template_part for calling templates for the currently queried post.</li>\n<li>if you do change the global $post, you'll (typically) need to reset it back to the original value because the rest of the (WordPress) code is dependent on it.</li>\n</ul>\n<p>Please let me know if you're interested in using a WordPress shortcode for your columns.</p>\n<p>Hope that helps!</p>\n<p><strong>Edit:</strong> As a side note, it looks like your html is malformed and a little bit different from the init question. Can you please check that as well. Also, please let me know if you're interested in using WordPress shortcodes. We can certainly optimize more, as we can write a little extra something today to will provide us a lot of value in the future. If WordPress is something you're never going to come back to again, then these micro-optimizes are not worth while. If this is something you plan to stick we, then it would be a good idea to take things a bit further. Thanks!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:24:21.193", "Id": "480729", "Score": "0", "body": "Again, thanks so much!\n\nYes, i would be very intrested in using the shortcodes as well, because I'm indeed planning to use wordpress on a long term." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:27:05.400", "Id": "480730", "Score": "0", "body": "I edited the code, it was wrongly pasted. But your code works perfectly alreday!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:34:32.213", "Id": "480731", "Score": "0", "body": "Awesome, glad I can help! Could you please mark the question as 'Accepted'. And if you need anything else feel free to ask. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:36:26.087", "Id": "480733", "Score": "0", "body": "Of course, just did so.If you could give me some further advice about the shortcodes, that would be amazing! Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:39:25.273", "Id": "480734", "Score": "1", "body": "Of course, what is your current knowledge about WordPress shortcodes? https://codex.wordpress.org/Shortcode_API Are you familiar with what they are, or never heard of them until just now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:41:10.970", "Id": "480735", "Score": "0", "body": "Perfect, i know a little something about them. I created one myself a few weeks ago, but just for testing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:47:23.543", "Id": "480736", "Score": "0", "body": "K, good. Simply put they are just a formalized way to call functions with arguments in string form. Idea being someone who doesn't have access to the code (or doesn't know how to code) can put this little snippet (shortcode) into the WYSIWYG/Gutenberg/etc and it will display the result of a dynamic template via the arguments ($atts) that get passed. I'll go ahead and mock up an example using your code. I'll just need a moment as I'm wrapping up some other things right now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T21:51:38.280", "Id": "480737", "Score": "0", "body": "You're amazing!!!!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T20:51:20.023", "Id": "244854", "ParentId": "244847", "Score": "4" } }, { "body": "<p>Here is the anatomy of a shortcode, and how to add and then use them.</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_shortcode('my_custom_shortcode', function ($atts, $content = NULL, $tag = NULL) {\n $defaults = ['a' =&gt; 'default A', 'b' =&gt; 'default B', 'c' =&gt; 'default C'];\n $atts = shortcode_atts($defaults, $atts, $tag);\n\n ob_start();\n ?&gt;\n &lt;h2&gt;This is shortcode &quot;&lt;?= $tag ?&gt;&quot;&lt;/h2&gt;\n\n &lt;p&gt;&lt;em&gt;With the attributes of:&lt;/em&gt;&lt;/p&gt;\n &lt;ul&gt;\n &lt;?php foreach ($atts as $key =&gt; $value) : ?&gt;\n &lt;li&gt;&lt;strong&gt;&lt;?= $key ?&gt;:&lt;/strong&gt; &lt;?= $value ?&gt;&lt;/li&gt;\n &lt;?php endforeach; ?&gt;\n &lt;/ul&gt;\n\n &lt;p&gt;&lt;em&gt;With the content of:&lt;/em&gt;&lt;/p&gt;\n &lt;?= $content ?: '(Content was not passed to this shortcode)' ?&gt;\n &lt;?php\n return ob_get_clean();\n});\n</code></pre>\n<ul>\n<li>In order to create a shortcode you need use the <code>add_shortcode</code> function\n<ul>\n<li>It takes two arguments: a <code>$tag</code> and a <code>$callback</code> (a callback can either be an anonymous function, as used in this example, a string that is the name of the callback function defined elsewhere, or an array of class and method).</li>\n<li><code>$tag</code> can be whatever you want, just as long as no other shortcode is already using that name. I chose <code>my_custom_shortcode</code> for this example</li>\n<li><code>$callback</code> accepts three arguments <code>$atts, $content = NULL, $tag = NULL</code>\n<ul>\n<li><code>$atts</code> is an array of the arguments the user defined</li>\n<li><code>$content</code> is any text the user defined inside of a shortcode (<code>[my_custom_shortcode]This text right here (if applicable)[/my_custom_shortcode]</code>)</li>\n<li><code>$tag</code> is the shortcode name, if you are using an anonymous function it will always be identical to the $tag name when adding the shortcode. It can be helpful because you can use the same (non-anonymous) callback function for different shortcodes and just change them slightly depending the the tag name.</li>\n</ul>\n</li>\n</ul>\n</li>\n<li>inside the callback you can optionally use the <code>shortcode_atts</code> function. It allows you to restrict/expect certain values from the user, set defaults (if not passed by the user), and drop/ignore params that are invalid (as decided by you). I typically will do this, but it's not required.</li>\n<li>you want to return a string in the callback. DON'T echo/display the contents directly to the buffer. That is a common mistake. You can use <code>ob_start()</code> to start capturing the output buffer and <code>ob_get_clean()</code> to get then clear the buffer when you're done.</li>\n</ul>\n<p>Here is how a user (or you) can call a shortcode in code:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// This is the most primitive form, no params or content is passed\n// NOTE: just like html, if there is no content, you don't need to close the shortcode tag\necho do_shortcode('[my_custom_shortcode]');\n\n// This example has one param, in this case `b`, passed and content\n// NOTE: since you do want to pass content here, you do need to have a closing shortcode tag\necho do_shortcode('[my_custom_shortcode b=&quot;some user defined value for B&quot;]The user contents[/my_custom_shortcode]');\n</code></pre>\n<p>If you want to call a shortcode from some WYSIWYG/Gutenberg type UI tool in WordPress, you just need the string, like this...</p>\n<pre class=\"lang-html prettyprint-override\"><code>[my_custom_shortcode]\n\n-or-\n\n[my_custom_shortcode b=&quot;some user defined value for B&quot;]The user contents[/my_custom_shortcode]\n</code></pre>\n<p>...and WordPress with call <code>do_shortcode</code> behind the scenes.</p>\n<p><strong>So...</strong>\nHow would you use it? Well I don't know what's inside your template file you're using for this question, but what's in there would go inside your shortcode callback. Here is your HTML, optimized from the original question</p>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;div class=&quot;col kb_landing_left&quot;&gt;\n &lt;?= do_shortcode('[my_custom_shortcode post_id=&quot;56&quot;]') ?&gt;\n&lt;/div&gt;\n&lt;div class=&quot;col -sm-6&quot;&gt;\n &lt;?php foreach ([1, 3, 2] as $post_id) : ?&gt;\n &lt;div class=&quot;row&quot;&gt;\n &lt;div class=&quot;col kb_landing_right&quot;&gt;\n &lt;?= do_shortcode(&quot;[my_custom_shortcode post_id='{$post_id}']&quot;) ?&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;?php endforeach; ?&gt;\n&lt;/div&gt;\n</code></pre>\n<p>That's it, I would not mess with changing the global $post, it will cause you more problems than it's worth.</p>\n<p>Here is how you write the shortcode:</p>\n<pre class=\"lang-php prettyprint-override\"><code>add_shortcode('my_custom_shortcode', function ($atts, $content = NULL, $tag = NULL) {\n $atts = shortcode_atts(['post_id' =&gt; 0], $atts, $tag);\n\n if (empty($atts['post_id']) || empty($post = get_post($atts['post_id']))) {\n return ''; // return nothing, a proper post_id was not passed by the user\n }\n\n ob_start();\n ?&gt;\n &lt;h2&gt;Title: &lt;?= $post-&gt;post_title ?&gt;&lt;/h2&gt;\n &lt;p&gt;&lt;?= $content ?: $post-&gt;post_excerpt ?&gt;&lt;/p&gt;\n &lt;p&gt;&lt;a href=&quot;&lt;?= get_permalink($post-&gt;ID) ?&gt;&quot;&gt;Read More&lt;/a&gt;&lt;/p&gt;\n &lt;?php\n return ob_get_clean();\n});\n</code></pre>\n<p>In my example, I'm creating a custom shortcode called <code>my_custom_shortcode</code>. I'm only accepting a post_id param. If post_id is not passed, or is not a valid id for a post, I exit early with an empty string. If a valid post is found, then I display the Title, content (if passed by user or fallback to the post excerpt), then a Read More link that takes me to that post's url. Then catch the buffer and return it.</p>\n<p>Let me know if you have questions!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T15:40:12.567", "Id": "480812", "Score": "0", "body": "Now that is truly great, i can't thank you enough!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T16:11:37.503", "Id": "480821", "Score": "0", "body": "I added the custom shortcode to my functions.php and my custom page template contains the HTML part with the embeded shortcodes.\n\nEverything seems to work properly, except for the excerpt. The content is not displaying, just the title and the Read More link." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:35:13.980", "Id": "480835", "Score": "0", "body": "@Sniffles quick sanity check, are you passing `$content` via the shortcode or does the `$post` have an excerpt? what does your shortcode call look like?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:52:46.443", "Id": "480837", "Score": "0", "body": "I'm not sure what you mean by that. I've just copied and pasted the code above (the one where it's saying \"Here is how you write the shortcode* into my functions.php\n\nNext i pasted the HTML part into my custom page template, called landingpage.php" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:58:32.710", "Id": "480841", "Score": "0", "body": "The Title and the \"Read More\" link are displayed, but only that. Actually i wouldn't even need that, only the content of the posts is enough. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T20:05:52.607", "Id": "480846", "Score": "0", "body": "K, given that, I'm guessing the code is working as expected, just both `$content` and `$post->post_excerpt` happen to be empty. Since you said you don't need that anyway go ahead and replace that part with `<?= get_the_content(null, false, $post) ?>` to get the post content." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T20:18:49.580", "Id": "480847", "Score": "0", "body": "Excellent, that's working perfectly, thank you so much!\nJust out of curiosity; you mentioned that `$content` and `$post->post_excerpt` are probably empty. Where should i put the content for it to work? The posts with the specifiied IDs have a content, which was added through wordpress backend, as usual. I'm sorry for all the questions... wont bother you after this anymore. Thank you so much again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T20:31:12.043", "Id": "480848", "Score": "0", "body": "It's no problem, I'm thinking that's what this website is for. To your question, I think the fact that `$content` is a generic term, we're probably mixing context. $content in the context of a shortcode is what get's put inside the shortcode tag by the user `[some_tag]some user content[/some_tag]`. \"some user content\" gets passed to the shortcode callback as the second parameter (arbitrarily named $content). Once inside the callback we are querying a $post which has it's own context for content. That context, `$post->post_content`, is the texted saved to the post through the admin." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T20:34:52.747", "Id": "480849", "Score": "0", "body": "My code was saying if the user passed content via the shortcode, display that. If not, fallback to display the queried post's (via the post_id passed by the user) excerpt. However, it's very possible both of those are blank. I was doing a simple example of a shortcode, I wasn't worrying too much about what that shorcode was doing as long as you could get the gist of how you could use it in your situation. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T20:53:28.360", "Id": "480851", "Score": "0", "body": "Thanks for the detailed explanation. Then i thin i understood it right. \n\nI made a test, so i opened the post with the ID 56 and entered this:\n\n`[custom_landingpage]test content[/custom_landingpage]`, but the result is still empty. Btw. i changed the shortcode name to \"custom_landingpage\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T15:44:19.940", "Id": "480947", "Score": "0", "body": "Hi again. I was just wondering if you got to test it again? I still can't get a content by using the shortcode. I entered this into my post with the ID 56:\n\n`[custom_landingpage]Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.[/custom_landingpage]`\n\nBut still nothing. Text which is entered outside of the shortcode isn't displayed as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T16:19:43.003", "Id": "480954", "Score": "0", "body": "Now, if a add an excerpt to the text in the post, that content shows up. But it's also displaying the shortcode closing tag [/custom_landingpage]. Looks like it's not processing the shortcode itself" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T20:39:08.493", "Id": "480989", "Score": "0", "body": "It works for me so there might be something else in your code. Are you still validating the post_id in your shortocde `if (empty($atts['post_id']) || empty($post = get_post($atts['post_id']))) { return ''; /* return nothing, a proper post_id was not passed by the user */ }`? Because that would look like the shortcode isn't processing if you don't pass it a valid `post_id`. You could return a message that says `return 'post_id is missing';` for debugging purposes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T20:44:17.493", "Id": "480991", "Score": "0", "body": "Actually, you might want to mark my original answer as accepted and create a new code review for this latest issue. I think that would be best. Once you do that, post the link to the new question and we can debug over in that ticket, since this is a different scope than the original question. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-04T13:25:27.810", "Id": "481038", "Score": "0", "body": "Hi again, here is the new post i created https://codereview.stackexchange.com/questions/244996/wordpress-troubleshooting-of-custom-shortcode-where-no-content-is-displayed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T01:41:19.653", "Id": "481095", "Score": "0", "body": "Hi @Sniffles thanks! but the link is a 404 for me. let me know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T13:40:12.727", "Id": "481237", "Score": "0", "body": "Hi @Phil; thanks so much for getting back to me. I had to move the post to Stack overflow. Here it is: https://stackoverflow.com/questions/62730634/wordpress-troubleshooting-of-custom-shortcode-where-no-content-is-displayed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T21:02:12.387", "Id": "481282", "Score": "0", "body": "Awesome, thanks, posted comment there. I think one thing I'd I like to clear up is the line giving you trouble `<?= $content ?: $post->post_excerpt ?>` was actually meant to show the flexibility in a shortcode. In other words, you can pass content directly from a call to the shortcode and/or get data from the post and display it, or you can do both as one as a fallback to the other. However, in a instructional sense its fine, but in a real world scenario is probably isn't what you want and I think there is where the confusion is. Translating from a tutorial example to a real world use case." } ], "meta_data": { "CommentCount": "18", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T03:39:46.707", "Id": "244863", "ParentId": "244847", "Score": "0" } } ]
{ "AcceptedAnswerId": "244863", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T19:31:51.777", "Id": "244847", "Score": "1", "Tags": [ "php", "wordpress" ], "Title": "Shorten and optimize php custom code for wordpress page template and use shortcodes" }
244847
<p>I wrote a JavaScript app with allows the user to add events and get countdown for every event. Also the events and their dates are stored in localStorage. I want a general review and I think that every second the browser makes a lot of operations like here:</p> <pre><code> let interval = setInterval(() =&gt; { let timerValue = this.__timer.tick(values); if (timerValue === &quot;Timed out&quot;) { alert(`${values.title} is out now !`); this.__adapter.removeEvent(values.title); clearInterval(interval); } else { this.__adapter.createEventOrUpdateIfExisted(values, timerValue); } }, 1000); </code></pre> <p>What's the best approach to follow?</p> <p>Source code: <a href="https://github.com/dvmhmdsd/Events-countdown" rel="nofollow noreferrer">https://github.com/dvmhmdsd/Events-countdown</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T04:45:09.023", "Id": "480750", "Score": "2", "body": "Welcome to CodeReview@SE. Please heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) and include *all* the code you want reviewed in your post." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T20:52:46.373", "Id": "244855", "Score": "1", "Tags": [ "javascript", "object-oriented" ], "Title": "events countdown OOP app" }
244855
<p>I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <blockquote> <p>Given an Iterator class interface with methods: <code>next()</code> and <code>hasNext()</code>, design and implement a <code>PeekingIterator</code> that support the peek() operation -- it essentially <code>peek()</code> at the element that will be returned by the next call to <code>next()</code>.</p> <p>Example:</p> <pre><code>list: [1,2,3]. Call next() gets you 1, the first element in the list. Now you call peek() and it returns 2, the next element. Calling next() after that still return 2. You call next() the final time and it returns 3, the last element. Calling hasNext() after that should return false. </code></pre> <p>Follow up: How would you extend your design to be generic and work with all types, not just integer?</p> </blockquote> <h3>Code</h3> <pre><code>#include &lt;vector&gt; class PeekingIterator : public Iterator { int next_num; bool num_has_next; public: PeekingIterator(const std::vector&lt;int&gt; &amp;nums) : Iterator(nums) { num_has_next = Iterator::hasNext(); if (num_has_next) { next_num = Iterator::next(); } } int peek() const { return next_num; } int next() { int curr_next = next_num; num_has_next = Iterator::hasNext(); if (num_has_next) { next_num = Iterator::next(); } return curr_next; } bool hasNext() const { return num_has_next; } }; </code></pre> <h3>Reference</h3> <p>LeetCode has a template for answering questions. There is usually a class named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename. For this question, the template is:</p> <pre><code>/* * Below is the interface for Iterator, which is already defined for you. * **DO NOT** modify the interface for Iterator. * * class Iterator { * struct Data; * Data* data; * Iterator(const vector&lt;int&gt;&amp; nums); * Iterator(const Iterator&amp; iter); * * // Returns the next element in the iteration. * int next(); * * // Returns true if the iteration has more elements. * bool hasNext() const; * }; */ class PeekingIterator : public Iterator { public: PeekingIterator(const vector&lt;int&gt;&amp; nums) : Iterator(nums) { // Initialize any member here. // **DO NOT** save a copy of nums and manipulate it directly. // You should only use the Iterator interface methods. } // Returns the next element in the iteration without advancing the iterator. int peek() { } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. int next() { } bool hasNext() const { } }; </code></pre> <ul> <li><p><a href="https://leetcode.com/problems/peeking-iterator/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/peeking-iterator/solution/" rel="nofollow noreferrer">Solution</a></p> </li> <li><p><a href="https://leetcode.com/problems/peeking-iterator/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-17T03:03:08.873", "Id": "482339", "Score": "2", "body": "What if you peek from the last element? `peek()` after the 3 has been returned. In your case; it'd keep returning 3, but it should be null." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-26T01:06:06.343", "Id": "500736", "Score": "0", "body": "how to implement a working `Iterator` ?" } ]
[ { "body": "<ul>\n<li><p>Passing larger sized data in functions by <code>const &amp;data</code> is a good idea since it does not make a copy. Note that when a parameter is passed by <code>const&amp;</code>, the extra cost dereferencing and fewer opportunities for compile optimizing. You should do this typically when the data is large in size</p>\n</li>\n<li><p>From your <code>next()</code> function</p>\n</li>\n</ul>\n<blockquote>\n<pre class=\"lang-cpp prettyprint-override\"><code> int next() {\n int curr_next = next_num;\n num_has_next = Iterator::hasNext();\n\n if (num_has_next) {\n next_num = Iterator::next();\n }\n\n return curr_next;\n } ```\n</code></pre>\n</blockquote>\n<p>What is the use of the <code>if (num_has_next)</code> branch? You are returning a copy of <code>next_num</code> that was copied <strong>before</strong> any modifications, and since <code>curr_next</code> is not a reference of <code>next_num</code>, any changes to <code>next_num</code> will not effect <code>return curr_next</code>. I think what you might want to do is</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int next(){\n next_num = (num_has_next) ? Iterator::next() : NULL;\n return next_num;\n} \n</code></pre>\n<p><a href=\"https://en.wikipedia.org/wiki/%3F:\" rel=\"nofollow noreferrer\">ternary operators</a> <br>\nSince @hjpotter92 has mentioned it, calling <code>next()</code> or <code>peek()</code> on the last element should return <code>NULL</code>.</p>\n<ul>\n<li>Have a look at <a href=\"https://www.geeksforgeeks.org/templates-cpp/\" rel=\"nofollow noreferrer\">templates in C++</a> if you want to work with multiple types.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-14T03:50:16.543", "Id": "492877", "Score": "1", "body": "@Emma I have just talked about the key parts of your solution, otherwise, the solution by itself is already pretty good :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-14T05:15:25.160", "Id": "492883", "Score": "1", "body": "Note that you will have to set `next_num` to `NULL` in the constructor if you want to use this function `next()`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-14T03:42:36.407", "Id": "250632", "ParentId": "244860", "Score": "2" } } ]
{ "AcceptedAnswerId": "250632", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-01T23:03:15.250", "Id": "244860", "Score": "4", "Tags": [ "c++", "beginner", "object-oriented", "programming-challenge", "c++17" ], "Title": "LeetCode 284: Peeking Iterator" }
244860
<p>For practice, I wrote a small program that goes through a string in the data section (although, it could be easily adapted to take user input), and print out the characters in the string until it finds a newline, then stops.</p> <p>This is by far the most complicated assembly program I've ever written. It's the first time I've ever used a jump and <code>cmp</code>. It's simple, but there's likely improvements I can make, so I thought I'd try to get feedback.</p> <p>I decided to write it in 32-bit because the system calls are a little easier to wrap my head around. I'll transition to x86-64 once I know what exactly my school is going to be using; because I've seen both so far in slides.</p> <p><strong>firstjmp.asm</strong></p> <pre class="lang-none prettyprint-override"><code>global _start section .data input: db `1234567890\n` section .text _start: mov esi, input ; Current head of string .loop: mov eax, 4 mov ebx, 1 mov ecx, esi mov edx, 1 int 0x80 inc esi cmp BYTE [esi], 10 jne .loop ; Stop looping once we've found the newline mov eax, 1 mov ebx, 0 int 0x80 </code></pre> <hr /> <pre class="lang-none prettyprint-override"><code>nasm firstjmp.asm -g -f elf32 -Wall -o firstjmp.o ld firstjmp.o -m elf_i386 -o firstjmp ┌─[brendon@parrot]─[~/Desktop/Classes/CompArc/Lab4/asm] └──╼ $./firstjmp 1234567890┌─[brendon@parrot]─[~/Desktop/Classes/CompArc/Lab4/asm] </code></pre>
[]
[ { "body": "<p>I haven't used <code>nasm</code>, but superficially, it looks like you are calling out to the kernel for each character in the string. This is likely to be a relatively expensive operation.</p>\n<p>Looking at <a href=\"https://www.tutorialspoint.com/assembly_programming/assembly_system_calls.htm\" rel=\"nofollow noreferrer\">this</a>, it would appear that <code>edx</code> can be used to specify the number of characters to output. With this in mind, it would probably be more efficient to find the string length first and then output the entire string in a single system call.</p>\n<p>It's also worth considering breaking up your logic into functions. This doesn't make a lot of difference with such a small program, however it'll be important as you start trying to do more complex logic. I'm not sure what the standard calling conventions are, however you could end up with something 'like' this...</p>\n<pre><code>global _start\n\nsection .data\n input: db `1234567890\\n`\n\nsection .text\n _exit:\n mov eax, 1\n mov ebx, 0\n int 0x80\n\n ; Input esi points to string\n ; Output edx contains length\n ; Modifies eax\n _linelen:\n mov eax, esi\n .loop:\n inc eax\n \n cmp BYTE [eax], 10\n jne .loop \n mov edx, eax\n sub edx, esi\n ret \n\n ; Input esi points to string\n ; edx contains string length\n ; Modifies eax, ebx\n _print:\n mov eax, 4\n mov ebx, 1\n int 0x80\n ret\n\n _start:\n mov esi, input ; Current head of string\n\n call _linelen\n\n mov ecx, esi\n call _print\n\n call _exit\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T14:30:12.043", "Id": "480802", "Score": "0", "body": "It definately would, and that's my next progression for this. That requires walking the string and keeping track of the found length though, which seemed more complicated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T14:43:21.517", "Id": "480805", "Score": "0", "body": "@Carcigenicate You're essentially already doing it by incrementing `esi`. At the point that you drop out of the loop, `esi` - it's original value is the length of the string." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T14:24:35.520", "Id": "244879", "ParentId": "244862", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T00:46:50.760", "Id": "244862", "Score": "3", "Tags": [ "beginner", "nasm" ], "Title": "Simple program to print from a buffer until a newline is found" }
244862
<p>Following is the piece of code which is working fine, but somehow it looks bit odd to me to have a function inside a render method and using it in both conditions. Let me know how can I improve this react code as <code>showContainer</code> is only adding a wrapper to the function JSX.</p> <p>Code -</p> <pre><code>render () { const childJsx = () =&gt; (&lt;&gt;&lt;h3&gt;Random Child JSX&lt;/h3&gt;&lt;/&gt;) return ( &lt;&gt; { showContainer ? &lt;Modal&gt; {childJsx()} &lt;/Modal&gt; : &lt;div className=&quot;parent&quot;&gt; {childJsx()} &lt;/div&gt; } &lt;/&gt; ) } </code></pre>
[]
[ { "body": "<p>Your <code>functional</code>method is fine, just the place You have defined is a bit anti pattern. (But well, if you really want to use that component in JUST in that scope its still fine.)</p>\n<p>But let me try to refactor it in a react way:</p>\n<pre><code>render () {\n\n return (\n &lt;&gt;\n {\n showContainer\n ? (\n &lt;Modal&gt;\n &lt;ChildJsx /&gt;\n &lt;/Modal&gt;\n )\n : (\n &lt;div className=&quot;parent&quot;&gt;\n &lt;ChildJsx /&gt;\n &lt;/div&gt;\n )\n } \n &lt;/&gt;\n )\n}\n\nfunction ChildJsx(props){\n return (\n &lt;&gt;\n &lt;h3&gt;Random Child JSX&lt;/h3&gt;\n &lt;/&gt;\n )\n}\n</code></pre>\n<p>React is about <b>reusability</b>. In this case you can use that small component again and again as many as you want.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T18:32:49.947", "Id": "480830", "Score": "0", "body": "Thanks for the answer. Can you please explain this `You have defined is a bit anti pattern` . How can i remove this ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T18:57:59.153", "Id": "480831", "Score": "0", "body": "`just the place You have defined is a bit anti pattern` means that you have defined a fully functional component inside a `React.Component`. You can have the reason to define it right there, but havent seend that context. If you have no a specific reason to define it in that scope, its better to separate it in a new `functional` component.(Because of reusability)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T03:20:03.397", "Id": "480875", "Score": "0", "body": "@Peter React key is completely unnecessary in this case, they are only required (and useful) when rendering arrays. [Lists and Keys](https://reactjs.org/docs/lists-and-keys.html) I also completely disagree with defining functions that return JSX within a component being an anti-pattern, it is very common in fact to do this. Even functional components can be defined and used this way. The only real reason to externalize them is if you *want* to reuse them in other components, otherwise, this is perfectly valid." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T07:21:59.993", "Id": "480891", "Score": "0", "body": "@DrewReese As I said, if you have a reason to define a function inside a component, lets do that. But im pretty sure your wrapper is pretty fine as a standalone component. And sooner or later in a bigger project that will be a standalone component." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T07:45:40.203", "Id": "480893", "Score": "0", "body": "@DrewReese `The only real reason to externalize them is if you want to reuse them in other components, otherwise, this is perfectly valid` React is about reuasbility. You should HAVE a reason to not externalise the components" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T07:54:54.933", "Id": "480896", "Score": "0", "body": "@Peter Yes, it's called scope. You should always limit the scope of defined variables as much as is reasonably possible. It's the same reason you don't define all your variables globally. Anyway, the comment was with regards to your assumption it was an anti-pattern which you, oddly enough, later indirectly say it is *actually* ok. It can't be both anti-pattern and pattern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T08:29:20.730", "Id": "480901", "Score": "0", "body": "Second line was directly said that" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T09:11:32.490", "Id": "244867", "ParentId": "244864", "Score": "2" } }, { "body": "<p>You can conditionally select the wrapper instead. Use the ternary to create an internal wrapper component. Not much of a code reduction though, but rather just moving the logic a bit. You can also remove the react Fragments as all the returns are returning single react nodes, which <em>does</em> help reduce the code and IMO improve readability.</p>\n<pre><code>render() {\n const childJsx = () =&gt; &lt;h3&gt;Random Child JSX&lt;/h3&gt;;\n\n const Wrapper = showContainer\n ? ({ children }) =&gt; &lt;Modal&gt;{children}&lt;/Modal&gt;\n : ({ children }) =&gt; &lt;div className=&quot;parent&quot;&gt;{children}&lt;/div&gt;;\n\n return &lt;Wrapper&gt;{childJsx()}&lt;/Wrapper&gt;;\n}\n</code></pre>\n<p><em>Note: all internally defined render functions or functional components can be defined externally if you desire to use elsewhere in other components.</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T03:31:09.763", "Id": "244916", "ParentId": "244864", "Score": "2" } }, { "body": "<p>While Drew and Peter provide some useful techniques when dealing with complex components, this case cries out for the simplest solution possible.</p>\n<pre><code>render () {\n if (showContainer) {\n return (\n &lt;Modal&gt;\n &lt;h3&gt;Random Child JSX&lt;/h3&gt;\n &lt;/Modal&gt;\n );\n } else {\n return (\n &lt;div className=&quot;parent&quot;&gt;\n &lt;h3&gt;Random Child JSX&lt;/h3&gt;\n &lt;/div&gt;\n );\n }\n}\n</code></pre>\n<p>Why would I start with this where there's so much repeated code? Simplicity is the first step in refactoring. Once you've simplified the problem, you can easily spot where you can make further refactorings once things grow in complexity. As written, this takes only a few seconds to read and understand—something you'll do far more often than writing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-20T16:09:36.143", "Id": "245761", "ParentId": "244864", "Score": "0" } } ]
{ "AcceptedAnswerId": "244867", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T04:11:45.330", "Id": "244864", "Score": "3", "Tags": [ "javascript", "performance", "html", "react.js", "jsx" ], "Title": "JSX render method in react" }
244864
<p>I have a Pandas DataFrame that contains a row per member per day, expressing member interaction with a website. Members interact only on some days, each member is identified with an ID. Here is a simulated example:</p> <pre><code>import pandas as pd import numpy as np # Generate data. ids = np.repeat(np.arange(100), np.random.randint(100, size = 100)) test = ( pd.Series( ids, index = pd.Series(pd.date_range('2020-01-01', '2020-02-01').values).sample(ids.shape[0], replace = True) ) .sort_index() ) print(test.head()) </code></pre> <p>Gives:</p> <pre><code>2020-01-01 4 2020-01-01 65 2020-01-01 95 2020-01-01 40 2020-01-01 88 dtype: int32 </code></pre> <p>I'd like to calculate a unique count of members within a 7 day rolling window. After some experimentation and research on Stack Overflow (including Pandas rolling / groupby function), I arrived at an explicit loop and slicing.</p> <pre><code># Calculate rolling 7 day unique count. unique_count = {} for k in test.index.unique(): unique_count[k] = test.loc[k - pd.Timedelta('7 days'):k].nunique() # Store as a dataframe and truncate to a minimum period. unique_count = pd.DataFrame.from_dict(unique_count, orient = 'index', columns = ['7_day_unique_count']).iloc[7:] print(unique_count.tail()) </code></pre> <p>Gives:</p> <pre><code> 7_day_unique_count 2020-01-28 98 2020-01-29 98 2020-01-30 98 2020-01-31 97 2020-02-01 97 </code></pre> <p>This seems to work correctly and performs OK. But is it possible to do this without the explicit loop, such as with resample / groupby / rolling functions? If so, is that more efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T04:49:15.793", "Id": "480752", "Score": "0", "body": "Welcome to CodeReview@SE. This seems at the very border of [what's on- and off-topic here](https://codereview.stackexchange.com/help/on-topic): looking for information and opinions on one implementation alternative not written (yet) rather than a review of the code presented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T07:48:22.303", "Id": "480760", "Score": "2", "body": "@greybeard This is on-topic. However I'm interested, what train of thought is making you think that this is potentially off-topic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T21:49:13.437", "Id": "480856", "Score": "0", "body": "(@Peilonrayz his is the night before an 8-dayish holiday trip; in a pinch for time and not likely to respond a gain any time soon. Pretty much what I commented before: 1) got the impression that *feedback about any or all facets of the code* is not wanted 2) the alternative explicitly asked about/for is a not presented b) not coded (yet).)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T22:08:08.297", "Id": "480862", "Score": "0", "body": "@greybeard thanks for taking the time to reply. I hope you have a nice holiday!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T08:15:35.247", "Id": "483763", "Score": "0", "body": "I don't know if you've seen the discussion and issues on Github, but you might like [this one](https://github.com/pandas-dev/pandas/issues/26959) and the discussion around it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-02T23:20:09.347", "Id": "484189", "Score": "0", "body": "Thanks @Juho, that looks very similar to my issue. It sounds like this is a gap in pandas." } ]
[ { "body": "<p>How about something like this:</p>\n<pre><code>test.rolling('7d').apply(lambda s:s.nunique()).groupby(level=0).max()\n</code></pre>\n<p><code>rolling('7d')</code> is the rolling window. The window is determined for each row. So the first window starts from the row &quot;2020-01-01 4&quot; and extends 7 days in the past. The second window starts from the row &quot;2020-01-01 65&quot; and extends 7 days in the past.</p>\n<p><code>.apply(lambda s:s.nunique())</code> determines the number of unique items in the window. But, because of the way rolling works, we get multiple results for the same day.</p>\n<p><code>.groupby(level=0)</code> groups the results by the date.</p>\n<p><code>.max()</code> takes the maximum nunique value for that date.</p>\n<p>The above approach seemed rather slow, so here's a different approach. Basically use a Counter as a multiset and use a deque as a FIFO queue. For each day update the Counter with the id's for that day and subtract the ones for the day at the beginning of the window. The len of the Counter is then the number of unique ids.</p>\n<pre><code>from collections import Counter, deque\n\nWINDOW = 7\n\nfifo = deque(maxlen=WINDOW)\nuniq = Counter()\n\ndef unique_in_window(x):\n if len(fifo) == WINDOW:\n uniq.subtract(fifo.popleft())\n \n uniq.update(x)\n fifo.append(x)\n \n return len(uniq)\n\ntest.groupby(level=0).apply(unique_in_window)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T01:05:08.763", "Id": "248789", "ParentId": "244865", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T04:27:38.057", "Id": "244865", "Score": "7", "Tags": [ "python", "python-3.x", "pandas" ], "Title": "Calculating a unique count within a rolling time window" }
244865
<p>I've just started my journey into functional programming and tried to implement a TicTacToe game Recursively without State in Scala.</p> <p>What I dislike is the JOptionPane but I don't know if i can solve this more elegantly.</p> <p>Does anyone know if i can solve this in a more &quot;Scala&quot; like way?</p> <pre class="lang-scala prettyprint-override"><code>import javax.swing.JOptionPane import scala.annotation.tailrec class TicTacToe { } object TicTacToe { val l1: List[Int] = List(0, 1, 2) val l2: List[Int] = List(3, 4, 5) val l3: List[Int] = List(6, 7, 8) val c1: List[Int] = List(0, 3, 6) val c2: List[Int] = List(1, 4, 7) val c3: List[Int] = List(2, 5, 8) val d1: List[Int] = List(0, 4, 8) val d2: List[Int] = List(2, 4, 6) val patterns: List[List[Int]] = List(l1, l2, l3, c1, c2, c3, d1, d2) val winConditions: List[String] = List(&quot;xxx&quot;, &quot;ooo&quot;) val startBoard = Array('#', '#', '#', '#', '#', '#', '#', '#', '#') def main(args: Array[String]): Unit = { startGame } def startGame: Unit ={ @tailrec def playGameAt(game: List[Array[Char]], atPosition: Int): Unit = { val board: Array[Char] = game.head board.update(atPosition, nextPlayer(board)) printBoard(board) if (!isWon(board)) { playGameAt(List(board) ++ game, Integer.parseInt(JOptionPane.showInputDialog())) } } playGameAt(List(startBoard), Integer.parseInt(JOptionPane.showInputDialog())) } def nextPlayer(board: Array[Char]): Char = { val turnNumber = board.count(_ == '#') if(turnNumber%2 == 0) 'x' else 'o' } def isWon(board: Array[Char]): Boolean = { patterns.foreach(pattern=&gt;{ val rowValues = pattern.foldLeft(&quot;&quot;)(_+board(_)) if (winConditions.contains(rowValues)){ println(&quot;Winner is &quot; + rowValues) return true } }) false } def printBoard(board: Array[Char]): Unit = { List(l1, l2, l3).foreach(row =&gt; println(&quot;&quot; + board(row(0)) + board(row(1)) + board(row(2)))) println(&quot;------&quot;) } } </code></pre> <p><a href="https://codereview.stackexchange.com/questions/245574/improving-my-tic-tac-toe-solution-in-scala">New, Improoved but still imperfect version</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T20:58:09.283", "Id": "481280", "Score": "1", "body": "By the way, you should look up ScalaFX if you don't like Swing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T18:05:48.407", "Id": "482300", "Score": "2", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>Sorry for the ridiculously long answer. I've added an (in my opinion) better way of doing this at the very bottom.</p>\n<p>Here are a few things you could improve:</p>\n<h2><code>class TicTacToe</code></h2>\n<p><s>There's no need for this class. As far as I can tell, you can get rid of it.</s> Actually, as Simon Forsberg <a href=\"https://codereview.stackexchange.com/questions/244868/improvements-tictactoe-in-scala/245189?noredirect=1#comment520627_245189\">said</a> in the comments, a class could be useful for having multiple instances of the game running at once. However, you'll have to move at least the <code>startGame</code> method into the class for that to happen. You can also make the class stateful and expose modified versions of methods such as <code>playRound</code> if you want to. I'll add a class to my code at the bottom later.</p>\n<h2>Spaces</h2>\n<p>Overall, your code is well-formatted, but there a few instances like these, where you missed spaces:</p>\n<pre><code>if(turnNumber%2 == 0) |&gt; if (turnNumber % 2 == 0)\npattern=&gt;{ |&gt; pattern =&gt; {\ndef startGame: Unit ={ |&gt; def startGame(): Unit = {\n</code></pre>\n<hr />\n<h2>Type aliases</h2>\n<p>I don't know about you, but I like using type aliases because they help me remember what each type represents. It's also handy when you have to refactor your code, e.g., if you want to represent moves using tuples representing the row and column (<code>(Int, Int)</code>) or you want to make a <code>Board</code> class instead of just using an array of characters, you don't have to change your method signatures - they can still return and accept objects of type <code>Player</code> and <code>Board</code>.</p>\n<pre><code>type Player = Char\ntype Board = Array[Player]\n</code></pre>\n<hr />\n<h2>Unnecessary braces and the <code>main</code> method</h2>\n<p>Instead of</p>\n<pre><code>def main(args: Array[String]): Unit = {\n startGame\n}\n</code></pre>\n<p>you could make it a one-liner</p>\n<pre><code>def main(args: Array[String]) = startGame\n</code></pre>\n<p>However, it'd be much more helpful to announce instructions before starting the game (I know those instructions don't match your own game, but bear with me).</p>\n<pre><code>def main(args: Array[String]): Unit = {\n println(&quot;Welcome to Tic Tac Toe!&quot;)\n println(&quot;To play, enter the row and column of the cell where you want to move when prompted&quot;)\n println(&quot;Both the row and column must be numbers from 1 to 3&quot;)\n\n runGame()\n}\n</code></pre>\n<hr />\n<h2><code>startGame</code></h2>\n<p>Rather than <code>startGame</code>, I feel like you should name it <code>runGame</code>, but that's entirely subjective, and you should pick whatever feels more intuitive to you.</p>\n<p>More importantly, I think the <code>startGame</code> should be a nilary method rather than a nullary method, i.e., it should have an empty parameter list so that it looks like a proper method call rather than a property access. Currently, it looks very confusing when you just have <code>startGame</code> to run the entire game, since it looks like an unused expression.</p>\n<hr />\n<h2>Storing the board</h2>\n<p>Using a 1-D array of characters to represent a board is fine for now, although not very good functional programming style. There are a lot of other issues here, though.</p>\n<h3><code>board.update</code></h3>\n<p>You can use <code>board(atPosition) = nextPlayer(board)</code> instead of <code>board.update(atPosition, nextPlayer(board))</code>, since the <code>update</code> method is one of Scala's special methods that let you use syntactic sugar.</p>\n<h3>Adding the current board to the game</h3>\n<p>Currently, you use <code>List(board) ++ game</code>, which creates a new list and then concatenates <code>game</code> to it. A better approach would be <code>board :: game</code>, which is more idiomatic and simpler.</p>\n<h3>Why using a <code>List[Array[Char]]</code> is bad</h3>\n<p>First of all, there is absolutely no reason to maintain a list of all the past boards. You don't use the <code>game</code> variable everywhere. You can just have a single <code>Array[Char]</code> to keep track of the current board. Even if you do need to be able to go back to a previous move, you can just maintain a <code>List[Move]</code> and use it to reconstruct the board at a specific time.</p>\n<p>Second, every single board you store in <code>game</code> refers to the exact same object! You're not copying <code>board</code> anywhere, so when you write the below code, you're getting the head of <code>game</code>, updating it, and then prepending that same board back onto <code>game</code>.</p>\n<pre><code>val board: Array[Char] = game.head\nboard.update(atPosition, nextPlayer(board))\n</code></pre>\n<p>A better solution would be to use tuples or a case class of your making. I'm going to just use tuples for now, because case classes would bloat the code.</p>\n<pre><code>type Row = (Player, Player, Player)\ntype Board = (Row, Row, Row)\n</code></pre>\n<p>Now that the board's 2-D, let's also make our moves 2-D, actually. They'll represent the row and column of each move. I made them 1-indexed in my code because I also make the user pick a number from 1 to 3 instead of 0 to 2 because I feel it'd be easier. By also internally using 1 instead of 0, we'll reduce off-by-one errors.</p>\n<pre><code>type Move = (Int, Int)\n</code></pre>\n<hr />\n<h2>Variables</h2>\n<p>At the top of your object, you have a ton of variables, of which you need only one - patterns (which I'm going to rename to <code>winCases</code>, because that is more descriptive to me). There's no need to make separate public variables for <code>l1</code>, <code>l2</code>, etc. You can just do it like this (I used <code>Set</code> because the order doesn't matter):</p>\n<pre><code>val winCases = Set(\n Set((1, 1), (1, 2), (1, 3)),\n Set((2, 1), (2, 2), (2, 3)),\n Set((3, 1), (3, 2), (3, 3)),\n Set((1, 1), (2, 1), (3, 1)),\n Set((1, 2), (2, 2), (3, 2)),\n Set((1, 3), (2, 3), (3, 3)),\n Set((1, 1), (2, 2), (3, 3)),\n Set((1, 3), (2, 2), (3, 1)),\n )\n</code></pre>\n<p><code>startBoard</code> can just be a local variable in <code>runGame</code> and doesn't have to be accessible by everyone.</p>\n<p><code>winConditions</code> we won't need because the whole <code>isWon</code> method can be refactored. There's absolutely no need to make a new string for each element of <code>patterns</code>/<code>winCases</code>.</p>\n<hr />\n<h2>Finding the winner</h2>\n<p>I don't like the fact that your <code>isWon</code> method prints the winner instead of only returning whether or not someone has won the game. A better way to do it would be to return a player and let the calling method decide what to display to the user. For that, I made this method:</p>\n<pre><code>def findWinner(board: Board): Option[Option[Player]] =\n if (isWinner(player1, board)) Some(Some(player1))\n else if (isWinner(player2, board)) Some(Some(player2))\n else if (isTie(board)) Some(None)\n else None\n</code></pre>\n<p>Having an <code>Option[Option[Player]]</code> lets us encode multiple things into that single value. If it's a <code>None</code>, we know the game will continue. If it's a <code>Some</code>, the game's ended. If it's the latter, containing a <code>Some</code>, there's a winner, and if it contains a <code>None</code>, there's a tie.</p>\n<hr />\n<h2>Back to <code>startGame</code>/<code>runGame</code></h2>\n<p>Among other things, I've renamed the <code>playGameAt</code> function to <code>playRound</code>. I also changed the signature. It takes the current board and player, and outputs the winner of the game. If there's a winner, it's a <code>Some</code>. If there's a tie, it's a <code>None</code>.</p>\n<pre><code>def playRound(board: Board, curr: Player): Option[Player]\n</code></pre>\n<p>Here's how the new function looks:</p>\n<pre><code>@tailrec\ndef playRound(board: Board, curr: Player): Option[Player] = {\n printBoard(board)\n println(s&quot;Player $curr's move&quot;)\n val move = nextMove(board)\n val newBoard = moveTo(curr, move, board)\n findWinner(newBoard) match {\n case Some(possWinner) =&gt; possWinner\n case None =&gt; playRound(newBoard, nextPlayer(curr))\n }\n}\n</code></pre>\n<p>I've put the call to <code>printBoard</code> at the very top, because even though all tic-tac-toe boards are the same (unless you're playing a special variant), I personally would like to see the board I'm going to be moving on before I actually select a move. It's totally subjective, but I prefer it this way.</p>\n<p>The print statement lets you know which player is supposed to move. The way you have it now, the users have to scroll up to see whose move it is currently, and this seems more helpful.</p>\n<p>After that, it gets the next move with the <code>nextMove</code> function (which I'll put in later), creates a <em>new</em> board using that move, and tries to find the winner (see above for how the <code>findWinner</code> method works). If the game's ended, it returns the winner (or <code>None</code> if it's a tie). If not, it plays another round using a new board and the other player.</p>\n<p><code>nextPlayer</code> is implemented like this, by the way:</p>\n<pre><code>def nextPlayer(curr: Player): Player =\n if (curr == player1) player2\n else player1\n</code></pre>\n<p>The entire <code>runGame</code> function looks like this:</p>\n<pre><code>def runGame() = {\n @tailrec\n def playRound(board: Board, curr: Player): Option[Player] = ...\n\n val startBoard = (\n (default, default, default),\n (default, default, default),\n (default, default, default)\n )\n\n val winner = playRound(startBoard, player1)\n winner match {\n case Some(player) =&gt; println(s&quot;Player $player won!&quot;)\n case None =&gt; println(&quot;Tie&quot;)\n }\n}\n</code></pre>\n<p>Here, <code>startBoard</code> is just a local variable, because I don't think there's any reason for anybody outside this method to know about it. <code>default</code> is a <code>Char</code> that represents a cell where no one's moved. <code>player1</code> and <code>player2</code> are used to mark where Player 1 and Player 2 moved, respectively.</p>\n<pre><code>val default = ' '\nval player1 = 'x'\nval player2 = 'o'\n</code></pre>\n<p>I also moved the print statement from <code>isWon</code> to here, so that there could be a customized message. Otherwise, if there was a tie, nothing would happen.</p>\n<hr />\n<h2>User input</h2>\n<p>It doesn't make sense to me that you're using a <code>JOptionPane</code> and displaying everything in the terminal. Why not make the user input also come from the console? We can write our <code>nextMove</code> method like this:</p>\n<pre><code>@tailrec\ndef nextMove(board: Board): Move = {\n val move = (nextRowOrCol(&quot;Row&quot;), nextRowOrCol(&quot;Column&quot;))\n\n if (isValid(move, board)) {\n move\n } else {\n println(&quot;That move is already taken. Please enter a different move.&quot;)\n nextMove(board)\n }\n}\n</code></pre>\n<p>The above code reads a row and column using the helper function <code>nextRowOrCol</code>, then checks if it's a valid move, i.e., no one's moved there already. If it is, it just returns it, and if not, it gets the user to re-enter a move. I'll add the <code>isValid</code> function a little below.</p>\n<p><code>nextRowOrCol</code> is implemented like this (prompt can be either &quot;Row&quot; or &quot;Column&quot;). It uses regex to ensure that the input is a number between 1 and 3. Like the <code>nextMove</code> function, if the row or column inputted is valid, it returns it directly, otherwise, it prompts the user(s) again.</p>\n<pre><code>private def nextRowOrCol(prompt: String): Int = {\n val input = readLine(s&quot;$prompt: &quot;)\n\n if (input.matches(&quot;[1-3]&quot;)) {\n input.toInt\n } else {\n println(&quot;Please enter a number from 1 to 3&quot;)\n nextRowOrCol(prompt)\n }\n}\n</code></pre>\n<hr />\n<h2>The entire code</h2>\n<p>As the heading says, here's the entire code. You'll notice that it's wayyy longer than what you have currently, mostly because I used tuples, which complicated everything, but also because your original solution didn't have a lot of functionality.</p>\n<p>I'm sure you can find a way to make it shorter, especially if you use your own case classes to represent everything. I've made almost every function that deals with tiny details like destructuring tuples <code>private</code>, but the public functions shouldn't need to be changed much even if you do decide to make a <code>case class Board</code> or something like that.</p>\n<pre><code>import scala.io.StdIn.readLine\nimport scala.annotation.tailrec\n\nobject TicTacToe {\n\n type Player = Char\n type Move = (Int, Int)\n type Row = (Player, Player, Player)\n type Board = (Row, Row, Row)\n\n val winCases = Set(\n Set((1, 1), (1, 2), (1, 3)),\n Set((2, 1), (2, 2), (2, 3)),\n Set((3, 1), (3, 2), (3, 3)),\n Set((1, 1), (2, 1), (3, 1)),\n Set((1, 2), (2, 2), (3, 2)),\n Set((1, 3), (2, 3), (3, 3)),\n Set((1, 1), (2, 2), (3, 3)),\n Set((1, 3), (2, 2), (3, 1)),\n )\n\n val default = ' '\n val player1 = 'x'\n val player2 = 'o'\n\n def main(args: Array[String]) = {\n println(&quot;Welcome to TicTacToe!&quot;)\n println(&quot;To play, enter the row and column of the cell where you want to move when prompted&quot;)\n println(&quot;Both the row and column must be numbers from 1 to 3&quot;)\n\n runGame()\n }\n\n def runGame() = {\n @tailrec\n def playRound(board: Board, curr: Player): Option[Player] = {\n printBoard(board)\n println(s&quot;Player $curr's move&quot;)\n val move = nextMove(board)\n val newBoard = moveTo(curr, move, board)\n findWinner(newBoard) match {\n case Some(possWinner) =&gt; possWinner\n case None =&gt; playRound(newBoard, nextPlayer(curr))\n }\n }\n\n val startBoard = (\n (default, default, default),\n (default, default, default),\n (default, default, default)\n )\n\n val winner = playRound(startBoard, player1)\n winner match {\n case Some(player) =&gt; println(s&quot;Player $player won!&quot;)\n case None =&gt; println(&quot;Tie&quot;)\n }\n }\n\n def findWinner(board: Board): Option[Option[Player]] =\n if (isWinner(player1, board)) Some(Some(player1))\n else if (isWinner(player2, board)) Some(Some(player2))\n else if (isTie(board)) Some(None)\n else None\n\n def moveTo(player: Player, move: Move, board: Board): Board = {\n val (row0, row1, row2) = board\n val (r, c) = move\n\n def updateTuple[T](tup: (T, T, T), ind: Int)(f: T =&gt; T): (T, T, T) = \n ind match {\n case 1 =&gt; tup.copy(_1 = f(tup._1))\n case 2 =&gt; tup.copy(_2 = f(tup._2))\n case 3 =&gt; tup.copy(_3 = f(tup._3))\n }\n\n updateTuple(board, r) {\n row =&gt; updateTuple(row, c)(_ =&gt; player)\n }\n }\n\n def isWinner(player: Player, board: Board): Boolean =\n winCases.exists(winCase =&gt;\n winCase.forall(move =&gt; playerAt(move, board) == player)\n )\n\n def isTie(board: Board): Boolean = !board.productIterator.exists {\n row =&gt; row.asInstanceOf[Row].productIterator.contains(default)\n }\n\n def playerAt(move: Move, board: Board): Player = {\n val (r, c) = move\n elementAt(elementAt(board, r), c)\n }\n\n private def elementAt[T](tup: (T, T, T), ind: Int): T =\n ind match {\n case 1 =&gt; tup._1\n case 2 =&gt; tup._2\n case 3 =&gt; tup._3\n }\n\n @tailrec\n def nextMove(board: Board): Move = {\n val move = (nextRowOrCol(&quot;Row&quot;), nextRowOrCol(&quot;Column&quot;))\n\n if (isValid(move, board)) {\n move\n } else {\n println(&quot;That move is already taken. Please enter a different move.&quot;)\n nextMove(board)\n }\n }\n\n private def nextRowOrCol(prompt: String): Int = {\n val input = readLine(s&quot;$prompt: &quot;)\n\n if (input.matches(&quot;[1-3]&quot;)) {\n input.toInt\n } else {\n println(&quot;Please enter a number from 1 to 3&quot;)\n nextRowOrCol(prompt)\n }\n }\n\n def isValid(move: Move, board: Board): Boolean = \n playerAt(move, board) == default\n\n def nextPlayer(curr: Player): Player =\n if (curr == player1) player2\n else player1\n\n def printBoard(board: Board): Unit =\n print(\n &quot;__________________\\n&quot; + \n tup2String(\n mapTuple(board) {row =&gt; tup2String(row, &quot;|&quot;)},\n &quot;------\\n&quot;\n )\n )\n\n private def tup2String[T](tup: (T, T, T), sep: String): String =\n s&quot;${tup._1}$sep${tup._2}$sep${tup._3}\\n&quot;\n\n private def mapTuple[T, R](tup: (T, T, T))(f: T =&gt; R): (R, R, R) =\n (f(tup._1), f(tup._2), f(tup._3))\n}\n</code></pre>\n<hr />\n<h2>An alternative way of storing the board</h2>\n<p>Working with tuples is really annoying, and even with case classes, you'd have to define your own methods and stuff. A nicer way to store the board would be to just maintain a list of all the moves anyone's ever made. Every move should contain where that move was made and the player who made that move, so let's makes these two types. By the way, the <code>Move</code> from before is more like <code>Coord</code> here.</p>\n<pre><code>type Coord = (Int, Int)\ntype Move = (Coord, Player)\n</code></pre>\n<p>Now everywhere we use <code>board: Board</code>, we just replace that with <code>moves: List[Move]</code>.</p>\n<p><code>playRound</code> doesn't change all that much. The variable <code>move</code> now has to include the current player because of how we defined <code>Move</code> above, and the <code>newMoves</code> variable (analogous to <code>newBoard</code>) is constructed by prepending <code>moves</code> to the pre-existing list of moves, which is a lot easier than creating a <code>moveTo</code> function that does all sorts of crazy stuff inside. Everywhere else, just remember that <code>board</code> has been replaced with <code>moves</code>.</p>\n<pre><code>@tailrec\ndef playRound(moves: List[Move], curr: Player): Option[Player] = {\n println(s&quot;Player $curr's move&quot;)\n val move = (nextMove(moves), curr)\n val newMoves = move :: moves\n printBoard(newMoves)\n findWinner(newMoves) match {\n case Some(possWinner) =&gt; possWinner\n case None =&gt; playRound(newMoves, nextPlayer(curr))\n }\n}\n</code></pre>\n<p><code>runGame</code> only has 1 change: instead of manually creating a variable called <code>startBoard</code> filled with the default character (<code>' '</code>), you can use <code>List.empty</code> (or <code>Nil</code>):</p>\n<pre><code>val winner = playRound(List.empty, player1)\n</code></pre>\n<hr />\n<p><code>playerAt</code> is a lot simpler now. It tries to find a move with the given coordinates, and if no move with those coordinates is found in our <code>List[Move]</code>, then <code>default</code> is chosen.</p>\n<pre><code>def playerAt(coord: Coord, moves: List[Move]): Player =\n moves.find(move =&gt; move._1 == coord).map(_._2).getOrElse(default)\n</code></pre>\n<hr />\n<p><code>isTie</code> is also a lot simpler - just check if 9 moves have been made!</p>\n<pre><code>def isTie(moves: List[Move]): Boolean = moves.size == 9\n</code></pre>\n<hr />\n<p><code>printBoard</code> is the only one with big-ish changes (the good kind). You can just use <code>map</code> and <code>mkString</code> now that we're not using tuples.</p>\n<pre><code>def printBoard(moves: List[Move]): Unit =\n print(\n 1 to 3 map { r =&gt;\n 1 to 3 map { c =&gt;\n playerAt((r, c), moves)\n } mkString &quot;|&quot;\n } mkString (&quot;__________\\n&quot;, &quot;\\n------\\n&quot;, &quot;\\n&quot;)\n )\n</code></pre>\n<hr />\n<p>The entire code (note that I've used two spaces to indent here, since that appears to be more commonly used in the Scala world, and it's what <a href=\"https://scalameta.org/scalafmt/\" rel=\"nofollow noreferrer\">scalafmt</a> uses):</p>\n<pre><code>import scala.io.StdIn.readLine\nimport scala.annotation.tailrec\n\nobject TicTacToe2 {\n\n type Player = Char\n type Coord = (Int, Int)\n type Move = (Coord, Player)\n\n val winCases: Set[Set[Coord]] = Set(\n Set((1, 1), (1, 2), (1, 3)),\n Set((2, 1), (2, 2), (2, 3)),\n Set((3, 1), (3, 2), (3, 3)),\n Set((1, 1), (2, 1), (3, 1)),\n Set((1, 2), (2, 2), (3, 2)),\n Set((1, 3), (2, 3), (3, 3)),\n Set((1, 1), (2, 2), (3, 3)),\n Set((1, 3), (2, 2), (3, 1))\n )\n\n val default = ' '\n val player1 = 'x'\n val player2 = 'o'\n\n def main(args: Array[String]) = {\n println(&quot;Welcome to TicTacToe!&quot;)\n println(\n &quot;To play, enter the row and column of the cell where you want to move when prompted&quot;\n )\n println(&quot;Both the row and column must be numbers from 1 to 3&quot;)\n printBoard(List.empty)\n\n runGame()\n }\n\n def runGame() = {\n @tailrec\n def playRound(moves: List[Move], curr: Player): Option[Player] = {\n println(s&quot;Player $curr's move&quot;)\n val move = (nextMove(moves), curr)\n val newMoves = move :: moves\n printBoard(newMoves)\n findWinner(newMoves) match {\n case Some(possWinner) =&gt; possWinner\n case None =&gt; playRound(newMoves, nextPlayer(curr))\n }\n }\n\n val winner = playRound(List.empty, player1)\n winner match {\n case Some(player) =&gt; println(s&quot;Player $player won!&quot;)\n case None =&gt; println(&quot;Tie&quot;)\n }\n }\n\n def findWinner(board: Board): Option[Option[Player]] =\n if (isWinner(player1, board)) Some(Some(player1))\n else if (isWinner(player2, board)) Some(Some(player2))\n else if (isTie(board)) Some(None)\n else None\n\n def isWinner(player: Player, moves: List[Move]): Boolean =\n winCases.exists { winCase =&gt;\n winCase.forall(move =&gt; playerAt(move, moves) == player)\n }\n\n def isTie(moves: List[Move]): Boolean = moves.size == 9\n\n def playerAt(coord: Coord, moves: List[Move]): Player =\n moves.find(move =&gt; move._1 == coord).map(_._2).getOrElse(default)\n\n @tailrec\n def nextMove(moves: List[Move]): Coord = {\n val coord = (nextRowOrCol(&quot;Row&quot;), nextRowOrCol(&quot;Column&quot;))\n\n if (isValid(coord, moves)) {\n coord\n } else {\n println(&quot;That move is already taken. Please enter a different move.&quot;)\n nextMove(moves)\n }\n }\n\n private def nextRowOrCol(prompt: String): Int = {\n val input = readLine(s&quot;$prompt: &quot;)\n\n if (input.matches(&quot;[1-3]&quot;)) {\n input.toInt\n } else {\n println(&quot;Please enter a number from 1 to 3&quot;)\n nextRowOrCol(prompt)\n }\n }\n\n def isValid(coord: Coord, moves: List[Move]): Boolean =\n playerAt(coord, moves) == default\n\n def nextPlayer(curr: Player): Player =\n if (curr == player1) player2\n else player1\n\n def printBoard(moves: List[Move]): Unit =\n print(\n 1 to 3 map { r =&gt;\n 1 to 3 map { c =&gt;\n playerAt((r, c), moves)\n } mkString &quot;|&quot;\n } mkString (&quot;__________\\n&quot;, &quot;\\n------\\n&quot;, &quot;\\n&quot;)\n )\n}\n</code></pre>\n<hr />\n<p>By the way, here's a small change you can make concerning the <code>isValid</code> method. Instead of returning a boolean, return an <code>Option</code> with which you can do <code>getOrElse</code>. If you write a <code>validate</code> function like this:</p>\n<pre><code>def validate(coord: Coord, moves: List[Move]): Option[Coord] =\n Option.when(playerAt(coord, moves) == default)(coord)\n</code></pre>\n<p>you can use it in <code>nextMove</code> like this, which looks much more idiomatic. The only thing is that you'll have to drop the <code>tailrec</code> annotation.</p>\n<pre><code>def nextMove(moves: List[Move]): Coord = {\n val coord = (nextRowOrCol(&quot;Row&quot;), nextRowOrCol(&quot;Column&quot;))\n\n validate(coord, moves).getOrElse {\n println(&quot;That move is already taken. Please enter a different move.&quot;)\n nextMove(moves)\n }\n}\n</code></pre>\n<hr />\n<p>Let me know if there's anything I did wrong or can improve.</p>\n\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-09T06:43:51.150", "Id": "481519", "Score": "3", "body": "keep up the good work! wow" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T18:20:07.943", "Id": "482302", "Score": "0", "body": "[link](https://codereview.stackexchange.com/questions/245574/improving-my-tic-tac-toe-solution-in-scala) Follow up, also yeah I need to change it to private. Thanks I'll look more into it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-16T18:46:01.183", "Id": "482307", "Score": "1", "body": "[I changed the Win Conditions function in the new Post](https://codereview.stackexchange.com/questions/245574/improving-my-tic-tac-toe-solution-in-scala), what do you think about it? And I totally agree the win conditions bugged me because the logic was twisted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-02T09:35:30.957", "Id": "520627", "Score": "4", "body": "Great answer. But I would recommend to move most of this functionality into a `TicTacToe` class so that it would be *possible* to have multiple instances of the game running simultaneously and decouple the game code from the main program." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-08T14:57:03.010", "Id": "245189", "ParentId": "244868", "Score": "9" } } ]
{ "AcceptedAnswerId": "245189", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T09:54:14.677", "Id": "244868", "Score": "3", "Tags": [ "functional-programming", "scala" ], "Title": "Improvements, TicTacToe in Scala" }
244868
<p>I am new to ASP.NET Core 3.1 with no background of MVC. I am just moving from Web Forms to ASP.NET Core. I asked elsewhere and I got the following comments regarding my code. The code is working fine for me, but I am not sure how to improve it with the provided feedback.</p> <p>I want to know how can I clean this code and write more optimized code based on the below code. I would appreciate examples with code.</p> <blockquote> <p>it's actually a bit buggy. There's no need to explicitly open or close the connection (Dapper will open it), and using will dispose the connection even in cases where finally won't execute.</p> <p>Another bug - catch(Exception ex){throw ex;} throws a new exception with a different stack trace. It's worse than no catch at all. To rethrow the original exception after eg logging, use throw;, without an exception object</p> </blockquote> <p><strong>Editor note</strong>: the quote says &quot;buggy&quot; or &quot;bug&quot;, but the things cited are not actually <em>bugs</em>. They are suggestions to remove redundant code, or to change minutiae side-effects of exception semantics.</p> <p><code>NewsController.cs</code></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BookListRazor.Model; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Dapper; using Microsoft.Data.SqlClient; using System.Data; using BookListRazor.Data; namespace BookListRazor.Controllers { // [Route(&quot;api/News&quot;)] //[Route(&quot;api/News/[action]&quot;)] [ApiController] public class NewsController : Controller { //for EF private readonly ApplicationDbContext _db; //For Dapper private readonly SqlConnectionConfiguration _configuration; public NewsController(ApplicationDbContext db, SqlConnectionConfiguration configuration) { _db = db; _configuration = configuration; } //get all news [HttpGet] [Route(&quot;api/news/GetAll&quot;)] public async Task&lt;IActionResult&gt; GetAll() { //fetch data using EF // return Json(new { data = await _db.News.OrderByDescending(x =&gt; x.NewsDate).ToListAsync() }); //Fetch data using Dapper IEnumerable&lt;News&gt; newslist; using (var conn = new SqlConnection(_configuration.Value)) { string query = &quot;select * FROM News&quot;; conn.Open(); try { newslist = await conn.QueryAsync&lt;News&gt;(query, commandType: CommandType.Text); } catch (Exception ex) { throw ex; } finally { conn.Close(); } } return Json(new { data = newslist }); } } } </code></pre> <p>and in the razor/cshtml:</p> <pre><code>&lt;script&gt; $(document).ready(function () { $.ajax({ url: &quot;api/news/getallnews/1&quot;, type: &quot;GET&quot;, dataType: &quot;json&quot;, success: function (response) { var len = response.data.length; var table = $(&quot;&lt;table&gt;&lt;tr&gt;&lt;th&gt;Details&lt;/th&gt;&lt;/tr&gt;&quot;); for (var i = 0; i &lt; len; i++) { //console.log(&quot;i &quot;+i); table.append(&quot;&lt;tr&gt;&lt;td&gt;Title:&lt;/td&gt;&lt;td&gt;&quot; + response.data[i].newsHeading + &quot;&lt;/td&gt;&lt;/tr&gt;&quot;); } table.append(&quot;&lt;/table&gt;&quot;); $(&quot;#news&quot;).html(table); } }); }); &lt;/script&gt; </code></pre> <p>and:</p> <pre><code>//get all news [HttpGet] [Route(&quot;api/news/GetAllData&quot;)] public async Task&lt;IActionResult&gt; GetAllData() { using (SqlConnection connection = new SqlConnection(_configuration.Value)) { var param = new DynamicParameters(); // param.Add(&quot;@prodtype&quot;, prodtype); //return connection.QueryFirst(&quot; select * FROM News&quot;); string query = &quot;select * FROM News&quot;; IEnumerable&lt;News&gt; newslist; newslist = await connection.QueryAsync&lt;News&gt;(query, commandType: CommandType.Text); return Json(new { data = newslist }); } } </code></pre>
[]
[ { "body": "<p>In <code>GetAll</code>, the feedback you've already had seems pretty valid, to be honest; there is really no value in re-throwing an exception you've caught <em>directly</em>; if this is after some kind of processing, then <code>throw;</code> (without the exception instance) is a good way to re-throw the original exception without damaging it, but in your case the entire thing is redundant, so - just lose the <code>try</code>/<code>catch</code>/<code>finally</code> completely and let the <code>using</code> worry about the rest. Additionally, might as well keep the query &quot;inline&quot;, and using <code>AsList()</code> helps make it clear that we're materializing the objects <em>now</em> rather than later (which could cause a problem with deferred execution). This is the <em>same</em> as the defaults, so the <code>AsList()</code> here doesn't change the behavior - just makes it clearer to the reader:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using (var conn = new SqlConnection(_configuration.Value))\n{\n var newslist = (await conn.QueryAsync&lt;News&gt;(&quot;select * FROM News&quot;)).AsList();\n return Json(new { data = newslist });\n}\n</code></pre>\n<hr />\n<p>In <code>GetAllData</code> you aren't using <code>param</code>, so trimming - it becomes... huh, the same!</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using (SqlConnection connection = new SqlConnection(_configuration.Value))\n{\n var newslist = (await connection.QueryAsync&lt;News&gt;(&quot;select * FROM News&quot;)).AsList();\n return Json(new { data = newslist });\n}\n</code></pre>\n<hr />\n<p>Finally, in the jQuery callback, watch out for XSS - see <a href=\"https://stackoverflow.com/q/47219741/23354\">this post on SO</a> for a very similar example. The problem, to be explicit, is that <code>response.data[i].newsHeading</code> could be malicious - for example it could contain <code>&lt;script&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T11:20:37.113", "Id": "480778", "Score": "0", "body": "Appreciate your reply, I will wait for somemore time to see if someone else may point out something else, will mark it correct if you comments are received." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T11:05:36.187", "Id": "244871", "ParentId": "244869", "Score": "7" } }, { "body": "<p>Other minor points:</p>\n<h2>Imports</h2>\n<p>Sort your <code>using</code>s, and <a href=\"https://stackoverflow.com/questions/125319/should-using-directives-be-inside-or-outside-the-namespace\">move them to the inside of your <code>namespace</code></a>. Also consider using StyleCop, which would suggest this.</p>\n<h2>Underscored privates</h2>\n<p>Why do these</p>\n<pre><code> private readonly ApplicationDbContext _db;\n private readonly SqlConnectionConfiguration _configuration;\n</code></pre>\n<p>have underscores? Typically that's a Python convention. If you're worried about disambiguating them here:</p>\n<pre><code> public NewsController(ApplicationDbContext db, SqlConnectionConfiguration configuration)\n {\n _db = db;\n _configuration = configuration;\n }\n \n</code></pre>\n<p>then you can simply prefix the destination with <code>this.</code>.</p>\n<h2>Rethrow</h2>\n<p>This entire block should be deleted:</p>\n<pre><code> catch (Exception ex)\n {\n throw ex;\n }\n</code></pre>\n<p>You will still be able to keep your <code>finally</code>. However, you shouldn't have your <code>finally</code> in there either, because you already have <code>conn</code> in a <code>with</code>. Your explicit <code>close</code> duplicates the <code>close</code> that <code>IDisposable</code> imposes on that connection.</p>\n<h2>Combined declaration</h2>\n<pre><code> IEnumerable&lt;News&gt; newslist;\n newslist = await connection.QueryAsync&lt;News&gt;(query, commandType: CommandType.Text);\n</code></pre>\n<p>does not need to be two separate statements; you can do the assignment on the first.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T21:26:17.440", "Id": "480854", "Score": "6", "body": "FWIW, the ASP.NET Core team's style guide mentions `_camelCase` for private fields: https://github.com/dotnet/aspnetcore/wiki/Engineering-guidelines#coding-style-guidelines--general" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T15:37:23.563", "Id": "244885", "ParentId": "244869", "Score": "5" } } ]
{ "AcceptedAnswerId": "244871", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T10:29:09.850", "Id": "244869", "Score": "9", "Tags": [ "c#", "asp.net-core", "performance" ], "Title": "News site in ASP.NET Core" }
244869
<p>I'm trying to use both <a href="https://github.com/dosco/super-graph/" rel="nofollow noreferrer">SuperGraph as-a-library</a> and <a href="https://github.com/99designs/gqlgen" rel="nofollow noreferrer">GqlGen</a>.</p> <p>So I have two handlers:</p> <ol> <li><p>the first one is <strong>SuperGraph</strong>; this checks that it can carry out the operation</p> </li> <li><p>the second one is <strong>GqlGen</strong>; this checks that it can carry out the operation if the first one can't</p> </li> </ol> <p>The code I'm using is this:</p> <pre class="lang-golang prettyprint-override"><code>type reqBody struct { Query string `json:&quot;query&quot;` } func Handler(sg *core.SuperGraph, next http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { bodyBytes, _ := ioutil.ReadAll(r.Body) r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) var rBody reqBody err = json.NewDecoder(bytes.NewBuffer(bodyBytes)).Decode(&amp;rBody) ctx := context.WithValue(r.Context(), core.UserIDKey, &quot;user_id&quot;) res, err := sg.GraphQL(ctx, rBody.Query, nil) if err == nil { render.JSON(w, r, res) // go-chi &quot;render&quot; pkg } else { next.ServeHTTP(w, r) } } } func main() { r := chi.NewRouter() r.Group(func(r chi.Router) { r.Post(&quot;/graphql&quot;, Handler(supergraph, gqlgen)) }) } </code></pre> <h3>QUESTIONS</h3> <ol> <li><p>Can I avoid these lines at all?</p> <pre class="lang-golang prettyprint-override"><code> bodyBytes, _ := ioutil.ReadAll(r.Body) r.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes)) </code></pre> </li> <li><p>Is there a better way to handle all this?</p> </li> <li><p>I know I can use a GraphQL gateway to join multiple schemas under the same endpoint, but is it really worth it? <strong>Is my idea/code really bad?</strong></p> </li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T11:23:03.033", "Id": "244872", "Score": "1", "Tags": [ "go", "graphql" ], "Title": "Using two handlers for a GraphQL project; handle query with the second one if the first one is not capable of" }
244872
<p>I'm practicing some data-analysis and I'm currently checking the integrity of my data. The elements that do <strong>not</strong> follow my date-schema, should be funneled to a new separate list so I can work on strategies and suggestions on how to handle these exceptions.</p> <p>The following code checks the format successfully:</p> <pre><code>def datetime_check_format(col): tracker = [] false_dates = [] true_dates = [] counter = 0 for element in col: if not isinstance(pd.to_datetime(element, errors=&quot;ignore&quot;, format= &quot;%d-%m-%Y&quot;), date): counter += 1 true_dates.append(pd.to_datetime(element, errors=&quot;raise&quot;, format= &quot;%Y-%m-%d&quot;)) else: counter +=1 false_dates.append(element) tracker.append(counter) if len(tracker) == 0: return &quot;column is ok.&quot; else: return tracker, false_dates, true_dates </code></pre> <p>I was wondering if someone has an idea on how to make this code better. It seems to be based on some backwards bending mobius-ring kind of twisted logic.</p> <p>I used this one as guide, since it told me of error-handling: <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer">pandas.to_datetime</a></p> <p>best regards,</p> <p>Jacob Collstrup</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T18:42:32.217", "Id": "481272", "Score": "2", "body": "Can you give some example IO and explain what the code is doing? I understand your practicing some data science but that doesn't explain the code. Additionally [titles](/help/how-to-ask) should only consist of a description of your code." } ]
[ { "body": "<p>One of my friends on Discord helped me out. He didn't like me attempt either! =oP</p>\n<p>I created this function:</p>\n<pre><code>import datetime\n\ndef str2date(string):\n try:\n datetime_holder = datetime.datetime.strptime(string, &quot;%Y-%m-%d&quot;)\n return datetime_holder.date()\n except ValueError:\n return string\n except TypeError:\n return string\n</code></pre>\n<p>And looped over it like this:</p>\n<pre><code>def datetime_check_format(col):\ntracker = []\nfalse_dates = []\ntrue_dates = []\ncounter = -1\nfor element in col:\n counter +=1\n if isinstance(str2date(element), date):\n true_dates.append(str2date(element))\n else:\n tracker.append(counter)\n false_dates.append(str2date(element))\n\nreturn tracker, false_dates, true_dates\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T15:12:24.613", "Id": "244881", "ParentId": "244873", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T12:37:36.810", "Id": "244873", "Score": "1", "Tags": [ "python", "python-3.x", "datetime", "validation", "pandas" ], "Title": "Check that elements in list follow a specified date-format schema and are not null/na/nan" }
244873
<p>I programmed a Neural Network to do binary classification in python, and during the backpropagation step I used Newton-Raphson's method for optimization. Any kind of feedback would be appreciated, but mostly I'd like to know if all of the gradients and hessians were computed correctly - for the examples I ran, it seems to be working correctly, leading me to believe everything is ok. Another major help I needed is on how to make the code more efficient - the computational cost for creating the hessian matrices is really high as it is, I wish there was a faster way of doing it.</p> <p>An observation on the hessian: to guarantee that the update direction for the weights and biases is a descent direction, I used <code>aprox_pos_def()</code> function to approximate the hessian with a positive definite matrix; you can see the theory behind this transformation here <a href="http://www.optimization-online.org/DB_FILE/2003/12/800.pdf" rel="noreferrer">http://www.optimization-online.org/DB_FILE/2003/12/800.pdf</a>.</p> <p>For a better understanding of the Newton-Raphson method, these wikipedia articles are good enough:</p> <ul> <li><p><a href="https://en.wikipedia.org/wiki/Newton%27s_method" rel="noreferrer">https://en.wikipedia.org/wiki/Newton%27s_method</a></p> </li> <li><p><a href="https://en.wikipedia.org/wiki/Newton%27s_method_in_optimization" rel="noreferrer">https://en.wikipedia.org/wiki/Newton%27s_method_in_optimization</a></p> </li> </ul> <p>Here is the code:</p> <pre><code>#!/usr/bin/env python3 # Author: Erik Davino Vincent # Almost pure Newton-Raphson method implementation for a neural network import numpy as np import matplotlib.pyplot as plt # Fits for X and Y def model(X, Y, layerSizes, learningRate, max_iter = 100, plotN = 100): n_x, m = X.shape n_y = Y.shape[0] if m != Y.shape[1]: raise ValueError(&quot;Invalid vector sizes for X and Y -&gt; X size = &quot; + str(X.shape) + &quot; while Y size = &quot; + str(Y.shape) + &quot;.&quot;) weights = initializeWeights(n_x, n_y, layerSizes) numLayers = len(layerSizes) return newtonMethod(X, Y, weights, learningRate, numLayers, max_iter, plotN) # Sigmoid activation function def sigmoid(t): return 1/(1+np.exp(-t)) # Initializes weights for each layer def initializeWeights(n_x, n_y, layerSizes, scaler = 0.1, seed = None): np.random.seed(seed) weights = {} n_hPrev = n_x for i in range(len(layerSizes)): n_h = layerSizes[i] weights['W'+str(i+1)] = np.random.randn(n_h, n_hPrev)*scaler weights['b'+str(i+1)] = np.zeros((n_h,1)) n_hPrev = n_h weights['W'+str(len(layerSizes)+1)] = np.random.random((n_y, n_hPrev))*scaler weights['b'+str(len(layerSizes)+1)] = np.zeros((n_y,1)) np.random.seed(None) return weights # Creates a positive definite aproximation to a not positive definite matrix def aprox_pos_def(A): u, V = np.linalg.eig(A) U = np.absolute(np.diag(u)) B = np.dot(V, np.dot(U, V.T)) return B # Performs foward propagation def forwardPropagation(weights, X, numLayers): # Cache for A Avals = {} AiPrev = np.copy(X) for i in range(numLayers+1): Wi = weights['W'+str(i+1)] bi = weights['b'+str(i+1)] Zi = np.dot(Wi, AiPrev) + bi Ai = sigmoid(Zi) Avals['A'+str(i+1)] = Ai AiPrev = np.copy(Ai) return Avals # Newton method for training a neural network def newtonMethod(X, Y, weights, learningRate, numLayers, max_iter, plotN): # Cache for ploting cost cost = [] iteration = [] # Cache for minimum cost and best weights bestWeights = weights.copy() minCost = np.inf # Init break_code = 0 break_code = 0 for it in range(max_iter): # Forward propagation Avals = forwardPropagation(weights, X, numLayers) # Evaluates cost fucntion AL = np.copy(Avals['A'+str(numLayers+1)]) lossFunc = -(Y*np.log(AL) + (1-Y)*np.log(1-AL)) costFunc = np.mean(lossFunc) # Updates best weights if costFunc &lt; minCost: bestWeights = weights.copy() minCost = costFunc # Caches cost function every plotN iterations if it%plotN == 0: cost.append(costFunc) iteration.append(it) # &quot;Backward&quot; propagation (Newton-Raphson's Method) loop for i in range(numLayers+1, 0, -1): # Gets current layer weights Wi = np.copy(weights['W'+str(i)]) bi = np.copy(weights['b'+str(i)]) Ai = np.copy(Avals['A'+str(i)]) # If on the first layer, APrev = X; else APrev = Ai-1 if i == 1: APrev = np.copy(X) else: APrev = np.copy(Avals['A'+str(i-1)]) # If on the last layer, dZi = Ai - Y; else dZi = (Wi+1 . dZi+1) * (Ai*(1-Ai)) if i == numLayers+1: dZi = (Ai - Y) # /(Ai * (1 - Ai)) ??? else: dZi = np.dot(Wnxt.T, dZnxt) * Ai * (1 - Ai) # Calculates gradient vector (actually a matrix) of i-th layer m = APrev.shape[1] gradVecti = np.dot(APrev, dZi.T)/m gradbi = np.sum(dZi, axis = 1, keepdims = 1)/m gradVecti = np.append(gradVecti, gradbi.T, axis = 0) # Performs newton method on each node of i-th layer try: for j in range(len(Ai)): # Creates hessian matrix for node j in layer i hessMatxi = np.dot(np.array([Ai[j]]), (1-np.array([Ai[j]])).T) * np.dot(APrev, APrev.T)/m hessbipar = np.dot(np.array([Ai[j]]), (1-np.array([Ai[j]])).T) * np.dot(APrev, np.ones((APrev.shape[1],1)))/m hessbi = np.dot(np.array([Ai[j]]), (1-np.array([Ai[j]])).T)/m hessMatxi = np.concatenate((hessMatxi, hessbipar), axis = 1) hessbipar = np.concatenate((hessbipar, hessbi), axis = 0) hessMatxi = np.concatenate((hessMatxi, hessbipar.T), axis = 0) hessMatxi = aprox_pos_def(hessMatxi) # Creates descent direction for layer i if j == 0: deltai = np.linalg.solve(hessMatxi, np.array([gradVecti[:,j]]).T).T else: deltai = np.append(deltai, np.linalg.solve(hessMatxi, np.array([gradVecti[:,j]]).T).T, axis = 0) except: print(&quot;Singular matrix found when calculating descent direction; terminating computation.&quot;) break_code = 1 break # Descent step for weights and biases dWi = deltai[:,:-1] dbi = np.array([deltai[:,-1]]).T # Cache dZi, Wi, bi dZnxt = np.copy(dZi) Wnxt = np.copy(Wi) # Updates weights and biases Wi = Wi - learningRate*dWi bi = bi - learningRate*dbi weights['W'+str(i)] = Wi weights['b'+str(i)] = bi # Plot cost every plotN iterations if it % plotN == 0: plt.clf() plt.plot(iteration, cost, color = 'b') plt.xlabel(&quot;Iteration&quot;) plt.ylabel(&quot;Cost Function&quot;) plt.title(&quot;Newton-Raphson Descent for Cost Function&quot;) plt.pause(0.001) # End of backprop loop ================================================== # Early breaking condition met if break_code: AL = Avals['A'+str(numLayers+1)] lossFunc = -(Y*np.log(AL) + (1-Y)*np.log(1-AL)) costFunc = np.mean(lossFunc) cost.append(costFunc) iteration.append(it) break # Plots cost function over time plt.clf() plt.plot(iteration, cost, color = 'b') plt.xlabel(&quot;Iteration&quot;) plt.ylabel(&quot;Cost Function&quot;) plt.title(&quot;Newton-Raphson Descent for Cost Function&quot;) plt.show(block = 0) return bestWeights # Predicts if X vector tag is 1 or 0 def predict(weights, X, numLayers): A = forwardPropagation(weights, X, numLayers) A = A['A'+str(numLayers+1)] return (A &gt; 0.5) def example(): from sklearn.datasets import load_breast_cancer from sklearn.preprocessing import StandardScaler as StdScaler from sklearn.model_selection import train_test_split # Won't work without scalling data scaler = StdScaler() data = load_breast_cancer(return_X_y=True) X = data[0] scaler.fit(X) X = scaler.transform(X) y = data[1] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.30) X_train = X_train.T X_test = X_test.T y_train = np.array([y_train]) y_test = np.array([y_test]) layers = [5, 5, 5] weights = model(X_train, y_train, layers, 0.1, max_iter = 500, plotN = 10) pred = predict(weights, X_train, len(layers)) percnt = 0 for i in range(pred.shape[1]): if pred[0,i] == y_train[0,i]: percnt += 1 percnt /= pred.shape[1] print() print(&quot;Accuracy of&quot;, percnt*100 , &quot;% on training set&quot;) pred = predict(weights, X_test, len(layers)) percnt = 0 for i in range(pred.shape[1]): if pred[0,i] == y_test[0,i]: percnt += 1 percnt /= pred.shape[1] print() print(&quot;Accuracy of&quot;, percnt*100 , &quot;% on test set&quot;) example() </code></pre>
[]
[ { "body": "<h2>Consistent unpacking</h2>\n<p>Rather than sometimes using indexes, can you do</p>\n<pre><code>n_x, m_x = X.shape\nn_y, m_y = Y.shape\n</code></pre>\n<p>?</p>\n<h2>Interpolation</h2>\n<pre><code>&quot;Invalid vector sizes for X and Y -&gt; X size = &quot; + str(X.shape) + &quot; while Y size = &quot; + str(Y.shape) + &quot;.&quot;\n</code></pre>\n<p>can be</p>\n<pre><code>f'Invalid vector sizes for X and Y -&gt; X size = {X.shape} while Y size = {Y.shape}.'\n</code></pre>\n<p>This:</p>\n<pre><code>&quot;Accuracy of&quot;, percnt*100 , &quot;% on training set&quot;\n</code></pre>\n<p>should similarly use an f-string, and does not need to multiply by 100 if you use the built-in percent field type.</p>\n<h2>snake_case</h2>\n<p>By convention,</p>\n<pre><code>initializeWeights\n</code></pre>\n<p>should be</p>\n<pre><code>initialize_weights\n</code></pre>\n<p>and similar for your other functions and local variables. In particular <code>Avals</code> should be lower-case; otherwise it looks like class.</p>\n<h2>Expressions</h2>\n<p>Expressions such as</p>\n<pre><code>dZi = (Ai - Y)\nreturn (A &gt; 0.5)\n</code></pre>\n<p>do not need parens.</p>\n<h2>Bare <code>except:</code></h2>\n<p>This is dangerous and prevents user break (Ctrl+C) from working. Instead, <code>except Exception</code>, or ideally something more specific if you know what you expect to see.</p>\n<h2>In-place subtraction</h2>\n<pre><code>Wi = Wi - learningRate*dWi\nbi = bi - learningRate*dbi\n</code></pre>\n<p>can use <code>-=</code>. This will improve brevity and may marginally improve performance.</p>\n<h2>Equivalent equations</h2>\n<p>It's minor, but</p>\n<pre><code>-(Y*np.log(AL) + (1-Y)*np.log(1-AL))\n</code></pre>\n<p>is equivalent to</p>\n<pre><code>(Y - 1)*np.log(1 - AL) - Y*np.log(AL)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T16:01:14.557", "Id": "480816", "Score": "0", "body": "Thanks for the tips. I thought in-place operations didn't work for numpy arrays. Could you explain why should we use this snake_case convention (I don't know most of the conventions...)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T16:02:07.510", "Id": "480817", "Score": "2", "body": "https://www.python.org/dev/peps/pep-0008/#naming-conventions" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T15:16:26.203", "Id": "244882", "ParentId": "244876", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T13:05:35.643", "Id": "244876", "Score": "6", "Tags": [ "python", "performance", "python-3.x", "neural-network" ], "Title": "Using Newton Method in a Neural Network/" }
244876
<p>I am a rookie and I need help optimizing this <code>SelectionSort()</code> algorithm which I have tried using Python.</p> <pre class="lang-py prettyprint-override"><code>def selectionSort(arr,an): for lastUnsortedInteger in range(an-1,0,-1): largest = arr.index(max(arr[0:lastUnsortedInteger+1])) swap(arr,largest,lastUnsortedInteger) return arr def swap(arr,ai,aj): arr[ai],arr[aj] = arr[aj],arr[ai] if __name__ == '__main__': an = int(input()) arr = list(map(int,input().strip().split())) selectionSort(arr,an) print(&quot;Sorted using SelectionSort():\n&quot;) for ai in arr: print(arr) </code></pre>
[]
[ { "body": "<p>Seems like you already incorporated a few of the suggestions from back when this was on StackOverflow, e.g. changing the inner loop to <code>max</code>. However, you do so in a very inefficient way:</p>\n<ul>\n<li>you create a slice of the list, O(n) time and space</li>\n<li>you get the <code>max</code> of that slice, O(n) time</li>\n<li>you get the <code>index</code> of that element, O(n) time</li>\n</ul>\n<p>Instead, you can get the <code>max</code> of the <code>range</code> of indices, using a <code>key</code> function for comparing the actual values at those indices:</p>\n<pre><code>largest = max(range(0, lastUnsortedInteger+1), key=arr.__getitem__)\n</code></pre>\n<p>This way, this step has only O(n) time (for Python 3).</p>\n<p>Some other points:</p>\n<ul>\n<li>the <code>an</code> parameter (the length of the array/list) is not necessary, you can use <code>len</code></li>\n<li>in my opinion, it is a bit simpler looping from first to last index, and using <code>min</code> instead of <code>max</code> accordingly</li>\n<li>since the swap is a single line now and only used once, we could inline this directly into the sorting function</li>\n<li>the function modifies the list in-place, so no <code>return</code> is needed and might lead users to expect that the function does not modify the list but create a sorted copy instead</li>\n<li>technically, <code>arr</code> is not an array but a <code>list</code>, and you might prefer <code>snake_case</code> to <code>camelCase</code> (it's &quot;Python&quot; after all)</li>\n</ul>\n<p>My version:</p>\n<pre><code>def selection_sort(lst):\n for i in range(len(lst) - 1):\n k = min(range(i, len(lst)), key=lst.__getitem__)\n lst[i], lst[k] = lst[k], lst[i]\n</code></pre>\n<p>Needless to say, for all practical purposes you should just use <code>sorted</code> or <code>sort</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T13:34:37.510", "Id": "244878", "ParentId": "244877", "Score": "4" } } ]
{ "AcceptedAnswerId": "244878", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T13:07:32.590", "Id": "244877", "Score": "3", "Tags": [ "python", "algorithm", "sorting" ], "Title": "SelectionSort Algorithm using Python" }
244877
<p>I'm working through the Rust book, and it has the following example of how to use the <code>filter</code> method on <code>Iterator</code>s (<a href="https://doc.rust-lang.org/book/ch13-02-iterators.html#using-closures-that-capture-their-environment" rel="nofollow noreferrer">source</a>):</p> <pre><code>struct Shoe { size: u32, style: String, } fn shoes_in_my_size(shoes: Vec&lt;Shoe&gt;, shoe_size: u32) -&gt; Vec&lt;Shoe&gt; { shoes.into_iter().filter(|s| s.size == shoe_size).collect() } </code></pre> <p>I started thinking of how I could improve this function with the following objectives:</p> <ol> <li>Do not consume/take ownership the <code>shoes</code> vector, so the caller can still use it.</li> <li>Return a vector of just the <code>style</code>s, rather than of the whole <code>Shoe</code> struct.</li> </ol> <p>I came up with the following two possible solutions:</p> <pre><code>fn shoe_styles_in_my_size(shoes: &amp;[Shoe], shoe_size: u32) -&gt; Vec&lt;&amp;String&gt; { shoes .iter() .filter(|s| s.size == shoe_size) .map(|s| &amp;s.style) .collect() } </code></pre> <p>and:</p> <pre><code>fn shoe_styles_in_my_size(shoes: &amp;[Shoe], shoe_size: u32) -&gt; Vec&lt;&amp;str&gt; { shoes .iter() .filter(|s| s.size == shoe_size) .map(|s| &amp;s.style[..]) .collect() } </code></pre> <p>The difference being that the first example returns <code>Vec&lt;&amp;String&gt;</code> and the second returns <code>Vec&lt;&amp;str&gt;</code>.</p> <p>What criteria would I use to determine which of these two is &quot;better?&quot; I've been under the impression that using <code>str</code> is preferable to using <code>String</code> when possible, since it is more flexible (hopefully this is accurate?) Is there any overhead associated with the <code>[..]</code> operation? My understanding says no, but I'm not sure.</p>
[]
[ { "body": "<p>The <code>[..]</code> slicing operation isn't going to cost anything, but isn't very descriptive either. I'd want to call <code>s.style.as_str()</code> instead.</p>\n<p>As for the return type, I'd agree that <code>&amp;str</code> is more appropriate, since it is the more general type. The functionality of a <code>String</code> is a superset of what you can do with a <code>str</code>, so it's irrelevant when that extra functionality isn't useful to the caller</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T15:47:45.090", "Id": "245039", "ParentId": "244880", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T15:11:06.377", "Id": "244880", "Score": "2", "Tags": [ "strings", "rust", "vectors" ], "Title": "Filtering a Vec of structs and creating new vector of Strings or strs in Rust" }
244880
<p>I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <blockquote> <p>Given an array which consists of non-negative integers and an integer <code>m</code>, you can split the array into <code>m</code> non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these <code>m</code> subarrays.</p> <h3>Note:</h3> <p>If <code>n</code> is the length of array, assume the following constraints are satisfied:</p> <p><span class="math-container">$$ 1 \le n \le 1000 \\ 1 \le m \le \min(50, n) $$</span></p> <h3>Example:</h3> <p>Input: nums = [7,2,5,10,8] m = 2</p> <p>Output: 18</p> <p>Explanation: There are four ways to split nums into two subarrays. The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18.</p> </blockquote> <h3>Code</h3> <pre><code>#include &lt;vector&gt; class Solution { public: static int splitArray(const std::vector&lt;int&gt; &amp;nums, const int m) { size_t lo = 0; size_t hi = 0; for (int num : nums) { lo = std::max(lo, (size_t) num); hi += num; } while (lo &lt; hi) { size_t mid = lo + (hi - lo) / 2; if (partitioning_is_valid(nums, m - 1, mid)) { hi = mid; } else { lo = mid + 1; } } return lo; } private: static bool partitioning_is_valid(const std::vector&lt;int&gt; &amp;nums, int partitions, size_t partition_max_sum) { size_t accumulate_curr_partition = 0; for (int num : nums) { if (num &gt; partition_max_sum) { return false; } else if (accumulate_curr_partition + num &lt;= partition_max_sum) { accumulate_curr_partition += num; } else { partitions--; accumulate_curr_partition = num; if (partitions &lt; 0) { return false; } } } return true; } }; </code></pre> <h3>Reference</h3> <p>LeetCode has a template for answering questions. There is usually a class named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename. For this question, the template is:</p> <pre><code>class Solution { public: int splitArray(vector&lt;int&gt;&amp; nums, int m) { } }; </code></pre> <ul> <li><p><a href="https://leetcode.com/problems/split-array-largest-sum/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/split-array-largest-sum/solution/" rel="nofollow noreferrer">Solution</a></p> </li> <li><p><a href="https://leetcode.com/problems/split-array-largest-sum/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T07:13:15.640", "Id": "480889", "Score": "1", "body": "You can change the following lines in your source-code: `lo = *std ::max_element(nums.begin(), nums.end())` and `hi = std :: accumulate(nums.begin(), nums.end(), 0)` and remove the `for` loop. Do make sure that to use this functions you need to include `<algorithm>` header file which by default is included in the Leet-Code default template." } ]
[ { "body": "<h2>Function signatures</h2>\n<p>You've made the best out of a slightly silly situation. I think your function signatures, while abiding to the template, have improved since the last post of yours that I reviewed.</p>\n<p>I'm not sure whether this will break LeetCode compatibility, but if you want to enforce that no one can instantiate this class, try making a private default constructor.</p>\n<h2>Mean</h2>\n<p>A simpler way to express the arithmetic mean than</p>\n<pre><code> size_t mid = lo + (hi - lo) / 2;\n</code></pre>\n<p>is</p>\n<pre><code> size_t mid = (hi + lo) / 2;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T16:08:58.933", "Id": "480819", "Score": "1", "body": "_1 ≤ n ≤ 1000_ so overflow is not an issue here unless you're using an 8-bit type, which you are not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T16:11:06.563", "Id": "480820", "Score": "1", "body": "On second read they leave the range of the actual array entries ambiguous? So maybe it's safe to keep the overflow-conscious version." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T16:04:02.943", "Id": "244888", "ParentId": "244884", "Score": "1" } } ]
{ "AcceptedAnswerId": "244888", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T15:34:06.053", "Id": "244884", "Score": "1", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 410: Split Array Largest Sum" }
244884
<p>I come from a fairly strong background of C and thought that this project would be a good way to get a handle on Rust. Right now, I have everything in one file because I wasn't sure the best way to organize the code (at least not yet). Let me know if I should post anything else (the <code>.toml</code> for the project, things like that).</p> <pre><code>extern crate image; extern crate nalgebra; use image::{Rgb, RgbImage}; use nalgebra::base::{Unit, Vector3}; use nalgebra::geometry::Point3; trait Hittable { fn intersects(&amp;self, ray: &amp;Ray, tmin: f64, tmax: f64, record: &amp;mut HitRecord) -&gt; bool; } struct HitRecord { t: f64, // time of hit along ray n: Unit&lt;Vector3&lt;f64&gt;&gt;, // normal of surface at point p: Point3&lt;f64&gt;, // point of intersection } impl HitRecord { fn new(t: f64, n: Unit&lt;Vector3&lt;f64&gt;&gt;, p: Point3&lt;f64&gt;) -&gt; Self { Self {t, n, p } } } struct Ray { origin: Point3&lt;f64&gt;, dir: Vector3&lt;f64&gt;, } impl Ray { fn new(origin: Point3&lt;f64&gt;, dir: Vector3&lt;f64&gt;) -&gt; Self { Self { origin, dir } } fn at(&amp;self, t: f64) -&gt; Point3&lt;f64&gt; { self.origin + self.dir.scale(t) } } struct Sphere { center: Point3&lt;f64&gt;, r: f64, } impl Sphere { fn new(center: Point3&lt;f64&gt;, r: f64) -&gt; Self { Self { center, r } } } impl Hittable for Sphere { fn intersects(&amp;self, ray: &amp;Ray, tmin: f64, tmax: f64, hit_record: &amp;mut HitRecord) -&gt; bool { let diff: Vector3&lt;f64&gt; = ray.origin - self.center; // get quadratic equation, calculate discriminant let a = ray.dir.dot(&amp;ray.dir); let b = diff.dot(&amp;ray.dir); let c = diff.dot(&amp;diff) - self.r * self.r; let disc = b * b - a * c; if disc &lt; 0.0 { return false; // no need to fill data } let root = disc.sqrt(); let ans = (-b - root) / a; // try first solution to equation if ans &lt; tmax &amp;&amp; ans &gt; tmin { hit_record.t = ans; hit_record.p = ray.at(ans); hit_record.n = Unit::new_normalize(self.center - hit_record.p); return true; } else { // is putting this in an else block necessary? I tried without the else // and the compiler said 'if may be missing an else clause', and I'm // still not completely sure why that is. let ans = (-b + root) / a; if ans &lt; tmax &amp;&amp; ans &gt; tmin { hit_record.t = ans; hit_record.p = ray.at(ans); hit_record.n = Unit::new_normalize(self.center - hit_record.p); return true; } else { return false; } } } } fn main() { let image_width: u32 = 512; let aspect_ratio = 3.0 / 2.0; let image_height: u32 = ((image_width as f64) / aspect_ratio).round() as u32; let viewport_height = 2.0; let viewport_width = viewport_height * aspect_ratio; let focal_length = 1.0; let origin: Point3&lt;f64&gt; = Point3::origin(); let horizontal_offset: Vector3&lt;f64&gt; = Vector3::new(viewport_width, 0.0, 0.0); let vertical_offset: Vector3&lt;f64&gt; = Vector3::new(0.0, viewport_height, 0.0); // this is the point in world space that represents the bottom left corner of the plane that is being projected onto let bottom_left_corner: Point3&lt;f64&gt; = origin - horizontal_offset.scale(0.5) - vertical_offset.scale(0.5) - Vector3::new(0.0, 0.0, focal_length); let mut img = RgbImage::new(image_width, image_height); let sphere: Sphere = Sphere::new(Point3::new(0.0, 0.0, -1.0), 0.5); let sphere_array = [sphere]; let light: Point3&lt;f64&gt; = Point3::new(0.0, 0.0, 0.0); for i in 0u32..image_width { for j in 0u32..image_height { let u: f64 = (i as f64) / ((image_width - 1) as f64); let v: f64 = (j as f64) / ((image_height - 1) as f64); let to: Point3&lt;f64&gt; = bottom_left_corner + horizontal_offset.scale(u) + vertical_offset.scale(v); let dir: Vector3&lt;f64&gt; = to - origin; let ray = Ray::new(origin, dir); let color: Rgb&lt;u8&gt; = cast_ray(&amp;ray, &amp;sphere_array, &amp;light); img.put_pixel(i, j, color); } } img.save(&quot;test.png&quot;).unwrap(); } fn cast_ray(ray: &amp;Ray, array: &amp;[Sphere], light: &amp;Point3&lt;f64&gt;) -&gt; Rgb&lt;u8&gt; { // start time at -1 to see if it changes later let mut hit_record: HitRecord = HitRecord::new(-1.0, Unit::new_unchecked(Vector3::new(1.0, 0.0, 0.0)), Point3::new(0.0, 0.0, 0.0)); for sphere in array.iter() { if sphere.intersects(ray, 0.0, 10.0, &amp;mut hit_record) { break; // this won't work for multiple spheres (yet), need to find closest } } if hit_record.t &lt; 0.0 { // miss return Rgb([55, 155, 255]); } else { let hit: Point3&lt;f64&gt; = hit_record.p; let normal: Unit&lt;Vector3&lt;f64&gt;&gt; = hit_record.n; let light_dir: Unit&lt;Vector3&lt;f64&gt;&gt; = Unit::new_normalize(hit - light); let brightness: f64 = light_dir.dot(normal.as_ref()).max(0.0); return Rgb([((255 as f64) * brightness) as u8, 0, 0]); } } </code></pre> <p>A lot of this code feels kind of clunky. For example, in the <code>cast_ray</code> function at the bottom, is there a better way to initialize the <code>hit_record</code> variable that will later be overwritten? Normally in C, I would make those null, but I obviously can't do that and don't want to make them Optional.</p> <p>In general, I just would like to know if this is 'good' Rust code and follows the generally accepted practices. For example, I assume having an output variable isn't considered best practice, but what would be the alternative? Returning a tuple? Because then I worry that it wouldn't be as fast if I made a new <code>hit_record</code> inside each <code>intersects</code> method and return that.</p> <p>Finally, in case it's helpful, the libraries I'm using are <a href="https://docs.rs/image/0.23.6/image/" rel="noreferrer">image</a> to write to image files, and <a href="https://www.nalgebra.org/rustdoc/nalgebra/" rel="noreferrer">nalgebra</a> to handle a lot of the math for me.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:58:52.110", "Id": "480842", "Score": "0", "body": "Slightly off-topic, but there's a graphics programming [MeetUp](https://www.meetup.com/Graphics-Programming-Virtual-Meetup/) that was started last night, and a couple people (myself included) are implementing raytracers in Rust. Just posting it here for you to check out (if you're interested)!" } ]
[ { "body": "<p>I'm not particularly knowledgeable on Rust, so this will be a light review.</p>\n<p>I would suggest leaning on the Rust tooling quite a bit, especially when new to a language. I've heard nothing but praise for the format tool, compiler warnings, and linters.</p>\n<p>Running the code through rustfmt only moves newlines and comments around, so good job on having a clean starting point.</p>\n<hr />\n<p>Clippy (the linter) points out that there are unecessary explicit returns. You can remove the return keyword (and trailing semicolon) from lines at the end of functions like <code>return RGB(...);</code>. For example</p>\n<pre><code>if ans &lt; tmax &amp;&amp; ans &gt; tmin {\n hit_record.t = ans;\n hit_record.p = ray.at(ans);\n hit_record.n = Unit::new_normalize(self.center - hit_record.p);\n true\n} else {\n // is putting this in an else block necessary? I tried without the else\n // and the compiler said 'if may be missing an else clause', and I'm\n // still not completely sure why that is.\n let ans = (-b + root) / a;\n if ans &lt; tmax &amp;&amp; ans &gt; tmin {\n hit_record.t = ans;\n hit_record.p = ray.at(ans);\n hit_record.n = Unit::new_normalize(self.center - hit_record.p);\n true\n } else {\n false\n }\n}\n</code></pre>\n<p>If you don't like the implicit returns, you can write code with guard clauses instead of if/else (BTW I couldn't reproduce the compiler error you get removing the else block).</p>\n<pre><code>if ans &lt; tmax &amp;&amp; ans &gt; tmin {\n hit_record.t = ans;\n hit_record.p = ray.at(ans);\n hit_record.n = Unit::new_normalize(self.center - hit_record.p);\n return true;\n}\n\nif ans &lt; tmax &amp;&amp; ans &gt; tmin {\n hit_record.t = ans;\n hit_record.p = ray.at(ans);\n hit_record.n = Unit::new_normalize(self.center - hit_record.p);\n return true;\n}\nfalse\n</code></pre>\n<p>The final warning clippy gives is on the cast of a literal, it suggests changing <code>255 as f64</code> to <code>255_f64</code>, including the type directly in the literal.</p>\n<hr />\n<pre><code>// get quadratic equation, calculate discriminant\nlet a = ray.dir.dot(&amp;ray.dir);\nlet b = diff.dot(&amp;ray.dir);\nlet c = diff.dot(&amp;diff) - self.r * self.r;\nlet disc = b * b - a * c;\n</code></pre>\n<p>Do you have a link/diagram/short explanation for this? I don't know the derivation, so I don't know why the discriminant is not the usual <code>disc = b * b - 4 * a * c</code>. Where did the 4 go?</p>\n<hr />\n<pre><code>let ans = (-b - root) / a;\nif ans &lt; tmax &amp;&amp; ans &gt; tmin {\n // Block that involves ans\n}\n\nlet ans = (-b + root) / a;\nif ans &lt; tmax &amp;&amp; ans &gt; tmin {\n // Block that involves ans\n}\n</code></pre>\n<p>I can't tell if this suggestion is actually an improvement without profiling, but if most of the time these conditions fail, you could trade two divisions for two multiplications by scaling tmin and tmax, and only dividing if it passes the checks.</p>\n<pre><code>let a_tmin = a * tmin;\nlet a_tmax = a * tmax;\nlet scaled_ans = -b - root;\nif a_tmin &lt; scaled_ans &amp;&amp; scaled_ans &lt; a_tmax {\n let ans = scaled_ans / a;\n // Block that involves ans\n}\n\nlet scaled_ans = -b + root;\nif a_tmin &lt; scaled_ans &amp;&amp; scaled_ans &lt; a_tmax {\n let ans = scaled_ans / a;\n // Block that involves ans\n}\n</code></pre>\n<hr />\n<p>I think changing the intersects function to return an optional hit_record would solve two problems. It can save you from initialising a dummy hit_record, and also removes the output variable. I'm not sure if this code is exactly correct, but something along the lines of</p>\n<pre><code>trait Hittable {\n fn intersects(&amp;self, ray: &amp;Ray, tmin: f64, tmax: f64) -&gt; Option&lt;HitRecord&gt;;\n}\n\n...\n\nfn intersects(&amp;self, ray: &amp;Ray, tmin: f64, tmax: f64) -&gt; Option&lt;HitRecord&gt; {\n let diff: Vector3&lt;f64&gt; = ray.origin - self.center;\n // get quadratic equation, calculate discriminant\n let a = ray.dir.dot(&amp;ray.dir);\n let b = diff.dot(&amp;ray.dir);\n let c = diff.dot(&amp;diff) - self.r * self.r;\n let disc = b * b - a * c;\n if disc &lt; 0.0 {\n return None; // no need to fill data\n }\n let root = disc.sqrt();\n let ans = (-b - root) / a; // try first solution to equation\n if ans &lt; tmax &amp;&amp; ans &gt; tmin {\n let p = ray.at(ans);\n return Some(HitRecord {\n t: ans,\n p,\n n: Unit::new_normalize(self.center - p),\n });\n }\n\n let ans = (-b + root) / a;\n if ans &lt; tmax &amp;&amp; ans &gt; tmin {\n let p = ray.at(ans);\n return Some(HitRecord {\n t: ans,\n p,\n n: Unit::new_normalize(self.center - p),\n });\n }\n None\n}\n\n\n...\n\n\n for sphere in array.iter() {\n let result = sphere.intersects(ray, 0.0, 10.0);\n match result {\n Some(record) =&gt; {\n hit_record = record;\n break;\n }\n None =&gt; continue,\n }\n</code></pre>\n<p>This does highlight that there is repeated code for both potential roots, maybe a quick function to deduplicate would be appropriate here.</p>\n<p>This then means the pattern in cast_rays is now &quot;loop over an iterator until the first value is found&quot;, so we can turn to the standard library if we would like to. Usually deferring to the standard library is a good idea, the implementation will be well tested, and will require less maintenance on our behalf. I think find_map is the algorithm we want in this case. This is where my Rust knowledge fails me, I think the code would be something like</p>\n<pre><code>let hit_record = array\n .iter()\n .find_map(|sphere| sphere.intersects(ray, 0.0, 10.0))\n .unwrap(); // What should happen in there is no intersecting spheres?\n</code></pre>\n<p>But at this point I'm out of my depth.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:29:37.133", "Id": "244896", "ParentId": "244886", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T15:42:21.200", "Id": "244886", "Score": "6", "Tags": [ "rust", "graphics", "raytracing" ], "Title": "Basic raytracer written in Rust" }
244886
<p>I have been working on some code that produces a live graphic of a graph and blocks moving. It works in theory but does not look like how I want. The animation runs very slow when showing both the graph and the blocks together (a code of each alone works much better). How can I get them to work together smoothly?</p> <p>I am also open to any other advice regarding this code on how I can improve its readability, speed, and functionality.</p> <p>Thanks!</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import keyboard import pandas # ============================================================================= # Parameters # ============================================================================= time = 10 # maximum time for the simulation h = 0.05 # step size steps = int(time/h) # number of steps order = 4 # two second order equations ICs = [0, 0, 0, 1, 0] # intial conditions; t0, x1, x1dot, x2, x2dot m1 = 1.0 # kg; mass 1 m2 = 3*m1 # kg; mass 2 k = 3.0 # N/m; spring constant F = 2.8 # N; forcing force us = 0.5 # static friction coefficient uk = 0.3 #k inetic friction coefficient g = 9.81 # m/s^2; gravity side1 = m1 # side length of mass 1 side2 = m2 # side length of mass 2 parameters = {'m1':m1, 'm2':m2, 'k':k, 'F':F, 'us':us, 'uk':uk, 'g':g} units = {'m1':'kg', 'm2':'kg', 'k':'N/m', 'F':'N', 'us':'', 'uk':'', 'g':'m/s^2'} # For logging the data to a CSV All_Values = {'t':[], 'x1':[], 'v1':[], 'x2':[], 'v2':[]} # ============================================================================= # Intializing Arrays # ============================================================================= vars = np.empty(shape=(order,steps)) # each row is another var, i.e. x1,x2,... # Set initial conditions for each var for i in range(order): vars[i][0] = ICs[i+1] K = np.zeros(shape=(4,order)) # Each row is k1, k2, k3, k4 for each var t = np.empty(steps) t[0] = ICs[0] # ============================================================================= # Resets the arrays # ============================================================================= def setup(): global K # Initializing vars array vars = np.empty(shape=(order,steps)) # each row is another var, i.e. x1,x2,... # Set initial conditions for each var for i in range(order): vars[i][0] = ICs[i+1] K = np.zeros(shape=(4,order)) # Each row is k1, k2, k3, k4 for each var t = np.empty(steps) t[0] = ICs[0] # ============================================================================= # ODE function # ============================================================================= def ODE(t, var, varsprev): # variables are as defined in the 'parameters' dict m1 = parameters['m1'] m2 = parameters['m2'] k = parameters['k'] F = parameters['F'] us = parameters['us'] uk = parameters['uk'] g = parameters['g'] # spring force based on the initial and current length of the spring l_eq = vars[2][0] - vars[0][0] # equilibrium length l_current = var[2] - var[0] F_s = k*(l_current - l_eq) # static friction until it can no longer fight the spring force static = m1*g*us kinetic = m1*g*uk if F_s &lt;= static: F_f = F_s else: F_f = kinetic dx1dt = var[1] # v1 = x1dot # Adjust the sign of friction # c = 0, no friction; c = 1, friction left; c = -1, friction right c = 1 # assume friction left unless if-else below says otherwise # if the block is moving to the left, friction to the right if var[1] &lt; 0: c = -1 # if the block isn't moving, depends on direction of spring force elif var[1] == 0: # spring pushing left, friction to the right if F_s &lt; 0: c = -1 # no velocity nor spring force, no friction elif F_s == 0: c = 0 dv1dt = 1/m1 * (F_s - c*F_f) dx2dt = var[3] # v2 = x2dot # chose that mass 2 does _not_ experience friction dv2dt = 1/m2 * (-F_s + F) return(np.array([dx1dt, dv1dt, dx2dt, dv2dt])) # ============================================================================= # Plotting function # ============================================================================= plt.ion() # set interactive mode on fig, (graph, block) = plt.subplots(2, 1, figsize=(8,10)) fig.suptitle(f'Double Spring Mass with Partial Friction Using RK4 (stepsize: {h})', y=0.94) def Plotting(i): # GRAPH graph.cla() # clear what is currently graphed graph.plot(t[:i], vars[0,:i], label=f'x1') graph.plot(t[:i], vars[1,:i], label=f'v1') graph.plot(t[:i], vars[2,:i], label=f'x2') graph.plot(t[:i], vars[3,:i], label=f'v2') graph.annotate(f'time = {round(t[i],1)}s', xy=(0.5, 0.98), xycoords='axes fraction', ha='center', va='top') graph.set_title('Graph') graph.set_xlabel('time [s]') graph.set_ylabel('position [m]') graph.legend(loc=2) # upper left # ========================================================================= # BLOCKS block.cla() # clear what is currently graphed m1x = vars[0][i] m2x = vars[2][i] COM = (m1*(m1x-side1) + m2*(m2x+side2))/(m1 + m2) windowOffset = abs(max((m1x-side1) - COM, (m2x+side2) - COM, key = abs))+side2 block.set_xlim(-(COM+windowOffset),COM+windowOffset) # plt.ylim(0,1.5*side2) mass1 = patches.Rectangle((m1x-side1,0), side1, side1, facecolor='#1f77b4') mass2 = patches.Rectangle((m2x, 0), side2, side2, facecolor='#ff7f0e') # Spring color based on length from equilibrium l_eq = ICs[3] - ICs[1] # equilibrium length l_curr = m2x - m1x # current length of spring if (l_curr == l_eq): c = 'k' elif (l_curr &gt; l_eq): c = '#d62728' else: c = '#2ca02c' spring = patches.ConnectionPatch(xyA=(m1x,side1/2), coordsA = 'data', xyB=(m2x, side1/2),coordsB='data', linewidth = 2, color = c) block.add_patch(spring) block.add_patch(mass1) block.add_patch(mass2) block.axis('equal') block.annotate(f'time = {round(t[i],1)}s', xy=(0.5, 0.98), xycoords='axes fraction', ha='center', va='top') block.set_title('Block Animation') block.set_xlabel('Position [m]') # ============================================================================= # User parameter change # ============================================================================= def paramUpdate(i): update = True # print parameters and values def printParams(): print(&quot;\nCurrent parameters and values: &quot;) for j in parameters: print(j, '=', parameters[j], units[j]) changed = False # if a parameter is changed, this ensures plot resets while update==True: try: printParams() # ask for parameter to change key = input(&quot;Which parameter would you like to change? (or type \&quot;n\&quot; to resume plotting) &quot;) # if 'n', resume plotting from the current i if key == '' or key == 'n': return (-1 if changed else i) # check to see if the parameter exists (i.e. key exists) if key not in parameters.keys(): raise KeyError # if the value is not convertable to float, throws 'ValueError' value = float(input(&quot;What is the new value? &quot;)) parameters[key] = value # change the parameter value printParams() changed = True # a change has been made; plot will reset while True: resume = input(&quot;Would you like to continue changing parameters? [y/n] &quot;)[0].lower() if resume == '' or not resume in ['y', 'n']: print(&quot;Please answer with 'y' or 'n'. &quot;) else: update = True if resume == 'y' else False break # catching errors except KeyError: print(&quot;\nPlease enter a valid parameter.&quot;) except ValueError: print(&quot;\nPlease enter a valid value.&quot;) return -1 print('Press \&quot;z\&quot; to pause') print('Press \&quot;c\&quot; to resume') print('Press \&quot;x\&quot; to save and quit') print('Press \&quot;v\&quot; to adjust parameters') # ============================================================================= # main loop that calculates each var value using RK 4th order method # ============================================================================= pause = False i=0 while i&lt;(steps-1): if i == 0: setup() # calculates each k value K[0] = h * ODE(t[i], vars[:,i], vars[:,i-1]) K[1] = h * ODE(t[i] + h/2, vars[:,i] + K[0]/2, vars[:,i-1]) K[2] = h * ODE(t[i] + h/2, vars[:,i] + K[1]/2, vars[:,i-1]) K[3] = h * ODE(t[i] + h, vars[:,i] + K[2], vars[:,i-1]) # combines k values using RK4 method vars[:,i+1] = vars[:,i] + 1/6 * (K[0] + 2 * K[1] + 2 * K[2] + K[3]) # updates time t[i+1] = t[i] + h # Plotting every fourth calculation to speed up plotting if (i%4 == 0): Plotting(i) fig.canvas.draw() plt.pause(0.01) # exit if keyboard.is_pressed('x'): plt.pause(0.01) break # update parameters if keyboard.is_pressed('v'): i = paramUpdate(i) # pause and resume if keyboard.is_pressed('z'): pause = True while pause: if keyboard.is_pressed('c'): pause = False if keyboard.is_pressed('x'): plt.pause(0.01) break if keyboard.is_pressed('v'): i = paramUpdate(i) pause = False i+=1 print(&quot;Done&quot;) plt.show() # plt.close() # closes the plot at then end # Saving values to a CSV All_Values['t'] = t All_Values['x1'] = vars[0] All_Values['v1'] = vars[1] All_Values['x2'] = vars[2] All_Values['v2'] = vars[3] df = pandas.DataFrame(All_Values) df.to_csv('Value_Output.csv', index = False) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T18:27:00.343", "Id": "480829", "Score": "0", "body": "https://www.youtube.com/watch?v=7EmboKQH8lM Please watch this. Start from 18:54 to cut the irrelevant stuff." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T17:14:41.090", "Id": "244890", "Score": "2", "Tags": [ "python", "numpy", "matplotlib" ], "Title": "Getting Graph and Block Animation to Run Smoothly Together" }
244890
<p>During an interview I was given this interesting JavaScript task:</p> <blockquote> <p>Given the code:</p> <pre><code>const testStr = &quot;bar.baz.foo:111222&quot;, testObj = { bar: { baz: { foo: 333444, foo2: 674654 }, boo: { faa: 11 } }, fee: 333 }; function replaceInObj(obj, str) { // your code } </code></pre> <p>write the implementation of the <code>replaceInObj</code> function</p> </blockquote> <p>I was not allowed to use a 3rd-party library. I kinda solved the task, but I'm not satisfied with my solution and I'm struggling with my complex implementation. At the same time I cannot find another solution by myself.</p> <h2>My implementation of the <code>replaceInObj</code> function</h2> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const testStr = 'bar.baz.foo:111222'; const testObj = { bar: { baz: { foo: 333444, foo2: 674654, }, boo: { faa: 11, }, }, fee: 333, }; console.log('[before] testObj.bar.baz =', testObj.bar.baz); // run replaceInObj(testObj, testStr); console.log('[after] testObj.bar.baz =', testObj.bar.baz); function replaceInObj(obj, str) { const [path, valueToChange] = str.split(':'); path.split('.').reduce((acc, prop, index, arr) =&gt; { const isLastProp = arr.length === index + 1; if (isLastProp) { acc[prop] = valueToChange; } return acc[prop]; }, obj); }</code></pre> </div> </div> </p>
[]
[ { "body": "<p>I think I found solution much cleaner and simpler to understand:\n<a href=\"https://codereview.stackexchange.com/a/240907/227075\">https://codereview.stackexchange.com/a/240907/227075</a></p>\n<h2>That solution adjusted to my task</h2>\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 testStr = 'bar.baz.foo:111222';\nconst testObj = {\n bar: {\n baz: {\n foo: '333444',\n },\n },\n};\n\nconsole.log('[before] testObj.bar.baz =', testObj.bar.baz);\n\n// run\nreplaceInObj(testObj, testStr);\n\nconsole.log('[after] testObj.bar.baz =', testObj.bar.baz);\n\nfunction replaceInObj(obj, str) {\n const [path, valueToChange] = str.split(':');\n const properties = path.split('.');\n const lastProperty = properties.pop();\n const lastObject = properties.reduce((a, prop) =&gt; a[prop], obj);\n lastObject[lastProperty] = valueToChange;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T17:21:04.720", "Id": "480966", "Score": "0", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:28:06.280", "Id": "244895", "ParentId": "244893", "Score": "0" } }, { "body": "<p>Neither of your solutions handles the type of the replacement correctly. For instance <code>&quot;bar.baz.foo:111222&quot;</code> replaces <code>foo:333444</code> with <code>foo:&quot;111222&quot;</code> where I would expect it to result in <code>foo:111222</code>.</p>\n<p>Further they can handle if the replacement is an array, but not if it is an object due to the use of <code>split(':')</code>. You should use <code>str.indexOf(':')</code> together with <code>str.substr()</code> instead:</p>\n<pre><code>function replaceInObj(obj, str) {\n let splitIndex = str.indexOf(':');\n let [path, replacement] = [str.substr(0, splitIndex), str.substr(splitIndex + 1)];\n let sections = path.split('.');\n let sub = obj;\n for (var i = 0; i &lt; sections.length - 1; i++) {\n sub = sub[sections[i]];\n }\n\n sub[sections[i]] = JSON.parse(replacement);\n return obj;\n}\n</code></pre>\n<p>Here <code>JSON.parse()</code> is used to interpret the value to the correct type. I don't know if the <code>JSON</code> api is considered as &quot;third-party&quot; in this context.</p>\n<hr />\n<p>There is a more &quot;quick and dirty&quot; approach using <code>eval</code>:</p>\n<pre><code>function replaceInObj(obj, str) {\n let splitIndex = str.indexOf(':');\n let [path, replacement] = [str.substr(0, splitIndex), str.substr(splitIndex + 1)];\n eval(&quot;obj.&quot; + path + &quot;=&quot; + replacement);\n return obj;\n}\n</code></pre>\n<hr />\n<p>Some test cases:</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> let testObj = {\n bar: {\n baz: {\n foo: 333444,\n foo2: 674654\n },\n boo: {\n faa: 11\n }\n },\n fee: 333\n };\n\n let replacements = [\n \"bar.baz.foo:111222\",\n \"bar.baz.foo:\\\"05-31-2020\\\"\",\n \"bar.baz.foo:false\",\n \"bar.baz.foo:\\\"abcdefg\\\"\",\n \"bar.baz.foo:[111222, 21341234, 234243]\",\n \"bar.baz.foo:{ \\\"aaa\\\": 1234, \\\"bbb\\\": \\\"hello world\\\" }\"\n ];\n\n for (let replacement of replacements) {\n let result = replaceInObj(testObj, replacement);\n console.log(result.bar.baz.foo);\n }\n\n\nfunction replaceInObj(obj, str) {\n let splitIndex = str.indexOf(':');\n let [path, replacement] = [str.substr(0, splitIndex), str.substr(splitIndex + 1)];\n eval(\"obj.\" + path + \"=\" + replacement);\n return obj;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-09T21:28:26.953", "Id": "481583", "Score": "0", "body": "Liked your solution and explanation! How incredibly you handled those edge-cases with possibility to pass any JSON-valid string" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-09T21:34:01.097", "Id": "481584", "Score": "0", "body": "Great work! " } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T09:05:15.963", "Id": "244928", "ParentId": "244893", "Score": "5" } } ]
{ "AcceptedAnswerId": "244928", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:04:45.050", "Id": "244893", "Score": "4", "Tags": [ "javascript", "interview-questions" ], "Title": "Replace nested property for an interview" }
244893
<p>I did an exercise today on where the task is to write a function that returns the length of the longest subarray where the difference between the smallest and biggest value in the subarray is no more than 1. I had a solution that works but it's too slow to pass the tests that have big arrays. What is it about my solution that makes it very slow with huge arrays?</p> <pre><code>def longestSubarray(arr): longest = 0 arr_len = len(arr) for i in range(arr_len): for j in range(i, arr_len): sub = arr[i: j+1] if max(sub) - min(sub) &gt; 1: continue length = len(sub) if length &gt; longest: longest = length return longest </code></pre>
[]
[ { "body": "<p>Specific suggestions:</p>\n<ol>\n<li>In many situations it would probably be useful to return <code>sub</code> rather than <code>len(sub)</code>. This makes the code somewhat simpler and gives the caller more information. Depending on the context that may or may not be useful, but it simplifies the code, which makes it easier to focus on the core issue.</li>\n<li>The code iterates over all sub-lists, calculating <code>min</code> and <code>max</code> of <em>each</em> of them. This is a lot of duplicate work. You can instead iterate only once over the list (with some backtracking):\n<ol>\n<li>Set the longest sub-list to the empty list.</li>\n<li>Set the <em>working</em> sub-list to a list containing just the first item in the input list.</li>\n<li>Set working sub-list min and max to the first item in the working sub-list.</li>\n<li>Move along the input list, updating min and max as long as the difference between them ends up being less than one and adding the current item to the working sub-list.</li>\n<li>Once you encounter a number which makes the difference between min and max <em>more</em> than one (or the end of the list, at which point you'd terminate after this step), check if the working sub-list is longer than the longest sub-list and update the latter if so.</li>\n<li>Once you encounter a number which makes the difference between min and max more than one you can't simply start the new working sub-list from that list item, because valid sub-lists may overlap (for example, <code>[1, 1, 2, 3]</code> has valid sub-lists <code>[1, 1, 2]</code> and <code>[2, 3]</code>). At this point you need to set the new working sub-list to include all the items at the tail end of the previous working sub-list which make a valid sub-list with the new item (if any).</li>\n<li>Go to 3 until you reach the end of the list.</li>\n</ol>\n</li>\n</ol>\n<h2>Tool support</h2>\n<ol>\n<li><p><a href=\"https://github.com/ambv/black\" rel=\"noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic, for example adding spaces around infix mathematical operators like <code>+</code>.</p>\n</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"noreferrer\"><code>flake8</code></a> can give you more hints to write idiomatic Python beyond <code>black</code>:</p>\n<pre><code> [flake8]\n ignore = W503,E203\n</code></pre>\n</li>\n<li><p>I would then recommend validating your <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a> using a strict <a href=\"https://github.com/python/mypy\" rel=\"noreferrer\"><code>mypy</code></a> configuration:</p>\n<pre><code> [mypy]\n check_untyped_defs = true\n disallow_any_generics = true\n disallow_untyped_defs = true\n ignore_missing_imports = true\n no_implicit_optional = true\n warn_redundant_casts = true\n warn_return_any = true\n warn_unused_ignores = true\n</code></pre>\n<p>In your case it looks like the type of <code>arr</code> should be <code>Iterable[int]</code> and the output is <code>int</code>.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T20:43:58.847", "Id": "244904", "ParentId": "244894", "Score": "8" } }, { "body": "<p>The code is slow on larger arrays because of the nested <code>for</code> loops. The number of times the inner loop runs depends on the length of the array. The outer loop runs <code>arr_len</code> times and the inner loop runs <code>arr_len/2</code> times on average. As a result the code in the loop runs <code>arr_len**2 / 2</code>. If the size of the array doubles, the amount of work the code does quadruples. If the size goes up by a thousand, the work goes up by a million. You may see this described as O(n^2) time complexity.</p>\n<p>The trick is to find an algorithm than scans the array once (or maybe a few times). Here are some observations that might help:</p>\n<p>If the 1st element of a subarray is <code>x</code>, then a valid subarray is a sequence of <code>x</code>'s, a sequence of <code>x</code>'s and <code>x+1</code>'s or a sequence of <code>x</code>'s and <code>x-1</code>'s. For example, [2,2,2], [2,2,3,3,2,3], and [2,1,1,2,2,2,2,2] could be valid subarrays.</p>\n<p>Depending on the form of the subarray, <code>min, max</code> is either <code>(x,x)</code>, <code>(x, x+1)</code>, or <code>(x-1, x)</code>. And all the values in the valid subarray are <code>min</code> or <code>max</code>.</p>\n<p>Depending on the value that ends the current subarray, a new subarray can start where it changed between <code>min</code> to <code>max</code>, or the reverse. Or it could start with the new value. For example, [1,1,2,2,3,3] has overlapping subarrays [1,1,2,2] and [2,2,3,3]. But [1,1,2,2,0,0] doesn't: [1,1,2,2] and [0,0].</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T01:14:47.167", "Id": "244913", "ParentId": "244894", "Score": "6" } } ]
{ "AcceptedAnswerId": "244913", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:24:35.200", "Id": "244894", "Score": "8", "Tags": [ "python", "algorithm", "python-3.x", "array" ], "Title": "Optimize function that returns length of a subarray" }
244894
<p>As a hobbyist programmer, I gain knowledge where I can find it from google searches. I tend to write code that utilizes threads that have infinite loops using while loops, where the while condition slaves onto a <code>BooleanProperty</code> that when set false, causes the thread to interrupt the loop. I use a single class to keep track of the threads that are still looping and when they have all stopped, it can then exit the program.</p> <p>A specific example of how I use a thread like this is an app I wrote that keeps my One Time Passwords for two-factor authentication on various web sites. Those passwords change every 30 seconds at second 0 of a minute change and at second 30 within a minute. Within each 30-second time frame, I do things to the label that is showing the password for an account such as fade the color to red during the last 10 seconds, then fade opacity in the last second and the first second, and there is simply no possible way to make those changes event-driven, so I use a looping thread to determine when those events need to happen.</p> <p>However, it was brought to my attention that the way I am doing this might not be the best way, so I would like to share how I am doing this and see if anyone can suggest a better method.</p> <p>I took a few Java classes when I got my CIS degree, but nothing covering advanced topics in Java. So I admit my knowledge is far from where I want it to be where wielding the Java language is concerned. I'd consider myself a hack programmer, but I would like my knowledge to be more complete than hack-level, but I don't know what I don't know so It's difficult to determine what to study given what I do know... you know?</p> <p>Anyway, the way I have been typically handling this issue, is that I first start with a <code>ThreadRegister</code> class that is publicly static and it looks like this:</p> <pre><code>package ClassHelpers; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public class ThreadRegister { public static BooleanProperty keepRunning = new SimpleBooleanProperty(true); private static List&lt;Long&gt; threadIDList = new ArrayList&lt;&gt;(); private static long threadID = 0; public static long addThread() { threadID++; threadIDList.add(threadID); return threadID; } public static void removeThread(Long threadID) { threadIDList.remove(threadID); } public static void exitApp() { new Thread(() -&gt; { keepRunning.setValue(false); while (threadIDList.size() &gt; 0) { try {TimeUnit.MILLISECONDS.sleep(10);} catch (InterruptedException e) {e.printStackTrace();} } System.exit(0); }).start(); } } </code></pre> <p>The publicly static <code>BooleanProperty</code> is then bound to the same object type with the same name in any other class that has looping threads, and such a class would look like this:</p> <pre><code>package Tests; import ClassHelpers.ThreadRegister; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import java.util.concurrent.TimeUnit; public class MyClass { public MyClass() { this.keepRunning.bind(ThreadRegister.keepRunning); } private BooleanProperty keepRunning = new SimpleBooleanProperty(); private void myThread() { new Thread(()-&gt;{ long threadID = ThreadRegister.addThread(); while (keepRunning.getValue().equals(true)) { //Do necessary processing here then //Sleep for a short time to keep CPU consumption low try {TimeUnit.MILLISECONDS.sleep(50);} catch (InterruptedException e) {e.printStackTrace();} } ThreadRegister.removeThread(threadID); }).start(); } } </code></pre> <p>I always make sure that any loops within a threads' main <code>while</code> loop also depend on that <code>BooleanProperty</code> with sleep values in every loop sitting right around 50 milliseconds to make sure that when the app is closed, the threads stop quickly. And last, I set the JavaFX Stage <code>onCloseRequest</code> value to the <code>ThreadRegisters</code> <code>exitApp()</code> method like this:</p> <pre><code>this.stage.setOnCloseRequest(e-&gt;ThreadRegister.exitApp()); </code></pre> <p>Now, no matter how many of these threads I have running, when the stage is close requested, the <code>ThreadRegister</code> sets the <code>BooleanProperty</code> to false, then it waits for all of the threads to stop running before finally exiting the app.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-19T05:50:00.360", "Id": "502845", "Score": "0", "body": "How is this related to `JavaFX`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T14:27:57.383", "Id": "504269", "Score": "1", "body": "@Sedrick It's not, but if I connected this post to JavaFX, that was my mistake." } ]
[ { "body": "<p>Hello and welcome to code review! My main question is: How often do you write programs that have several threads running throughout the application lifecycle with identical exit condition? It is possible that this might negatively affect the way you design your applications and make you use practises that aren't quite optimal? For example, instead of starting and stopping a thread when needed, do you now have threads running forever and waiting for a specific start signal?</p>\n<p>Java already has quite powerful tools for managing concurrency, such as executors and parallel streams. I think you might benefit from studying those before rolling your own.</p>\n<p><strong>Code</strong></p>\n<p>The <code>ThreadRegister</code> has one glaring bug: even though it deals with threads and concurrency, it is not thread safe itself. Access to <code>threadIDList</code> and <code>threadID</code> should be synchronized.</p>\n<p>You should follow <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html\" rel=\"nofollow noreferrer\">Java naming conventions</a>. Mainly, packages should be in lower case.</p>\n<p>By using property-classes from the <a href=\"/questions/tagged/javafx\" class=\"post-tag\" title=\"show questions tagged &#39;javafx&#39;\" rel=\"tag\">javafx</a> package, you have created a dependency from a fairly generic looking utility to a full blown desktop application framework. This limits the usability of your utility a lot.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T07:06:53.673", "Id": "481192", "Score": "0", "body": "I was not aware that packages should be lower case, I always treated them like class names... what do yo mean by the threadIDList and threadID should be synchronized? I like the way properties from JavaFX work because you can easily communicate between class instances without having to pass the class itself onto another class ... and as far as the looping threads go, Often, they check for some event that has happened ... but sometimes they just continually \"do stuff\" like the thread I mentioned in my second paragraph..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T05:58:49.750", "Id": "244921", "ParentId": "244897", "Score": "4" } }, { "body": "<p>@TorbenPutkonen's <a href=\"https://codereview.stackexchange.com/a/244921/203649\">answer</a> includes all the important facts about your code, I want just to add some minor thoughts. When you works with java threads and you have some shared variables check if there is a thread safe alternative already implemented in the java library. So instead of <code>long</code> and <code>boolean</code> use the thread safe alternatives <code>AtomicLong</code> and <code>AtomicBoolean</code>, same approach for the list that must be synchronized.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T07:11:34.047", "Id": "481194", "Score": "0", "body": "I've seen atomic variables before in example code, but I've never looked into what they are or why they exist ... I will read up on them, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T07:18:29.300", "Id": "481196", "Score": "0", "body": "@MichaelSims You are welcome." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T07:42:28.433", "Id": "244925", "ParentId": "244897", "Score": "1" } }, { "body": "<p>As for a real review, see Torben's answer.</p>\n<p>Apart from that: have a look at the method <code>Thread.setDaemon()</code>. Setting your worker threads to daemon would probably solve your problem without any further code. (See this question in SO <a href=\"https://stackoverflow.com/questions/2213340/what-is-a-daemon-thread-in-java\">https://stackoverflow.com/questions/2213340/what-is-a-daemon-thread-in-java</a>)</p>\n<p>If you want to perform additional parallel tasks in JavaFX specifically, have a look at <code>Task</code>s and <code>Worker</code>s. For things like transitioning a color over time, have a look at JavaFX's &quot;animations&quot; and &quot;timeline animations&quot;.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T07:10:19.857", "Id": "481193", "Score": "0", "body": "I've worked with animations - specifically to make a slide-out menu drawer, but I've not seen how one can fade color using animations... but in this particular case, there is still the problem of determining when to start the fade and a thread is the only way I can think of to calculate when the number of seconds within a minute hits the 20 second mark and then again when it hits the 50 second mark as that would be when the color fade needs to start and it fades over 10 seconds each time it runs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T09:00:25.937", "Id": "481212", "Score": "0", "body": "Concerning the setDaemon method... after reading what you posted, would it be reasonable to say that if my thread is not performing any I/O operations, then I can just set it up as Daemon and not even bother with making sure it's shut down before a System.exit() is called?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T10:01:46.117", "Id": "481220", "Score": "0", "body": "Probably yes. But as usual, trying it out is better than discussing the theory." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T09:09:41.800", "Id": "244929", "ParentId": "244897", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:36:59.053", "Id": "244897", "Score": "5", "Tags": [ "java", "multithreading", "javafx" ], "Title": "Ensuring threads running infinite loops are terminated before exiting the program" }
244897
<p>I have a code to get riders from certain teams and calculate the number of riders in those teams in that category:</p> <pre><code>valid_clubs = [] with open(&quot;validclubs.txt&quot;) as f: for line in f: valid_clubs.append(line) disqualification_reasons = [&quot;WKG&quot;, &quot;UPG&quot;, &quot;ZP&quot;, &quot;HR&quot;, &quot;HEIGHT&quot;, &quot;ZRVG&quot;, &quot;new&quot;, &quot;AGE&quot;, &quot;DQ&quot;, &quot;MAP&quot;, &quot;20MINS&quot;, &quot;5MINS&quot;] with open(&quot;results.csv&quot;, 'rt', encoding='UTF-8',errors='ignore') as file: # open results file to get breakdown of results reader = csv.reader(file, skipinitialspace=True, escapechar='\\') # each variable is current number of riders in the category A = B = C = D = E = Q = W = 0 # setting all values to 0 so we can work out number of riders in each category for row in reader: try: category = row[0] if row[4] in valid_clubs: if row[7] == &quot;0&quot;: # if club is in valid_clubs.txt and gender = female W = W + 1 # each time this condition is met increase value of W by 1, where W is the amount of women if &quot;A&quot; == category: # if club is in valid_clubs.txt and category is A A = A + 1 # each time this condition is met increase value of A by 1 if &quot;B&quot; == category: # if club is in valid_clubs.txt and category is B B = B + 1 # each time this condition is met increase value of B by 1 if &quot;C&quot; == category: # if club is in valid_clubs.txt and category is C C = C + 1 # each time this condition is met increase value of C by 1 if &quot;D&quot; == category: # if club is in valid_clubs.txt and category is D D = D + 1 # each time this condition is met increase value of D by 1 if category in disqualification_reasons: # all the possible DQ reason Q = Q + 1 # each time this condition is met increase value of Q by 1, where Q is the number of riders DQ'ed if &quot;E&quot; == category: # if club is in valid_clubs.txt and category is E E = E + 1 # each time this condition is met increase value of E by 1 except IndexError: # ignore errors where row is empty pass total = str(A + B + C + D + E + Q) print(&quot;There were&quot;, total, &quot;riders&quot;, W, &quot; were women:&quot;, &quot;\nCat A:&quot;, A, &quot;\nCat B:&quot;, B, &quot;\nCat C:&quot;, C, &quot;\nCat D:&quot;, D, &quot;\nCat E:&quot;, E, &quot;\nDisqualified:&quot;, Q) </code></pre> <p>It is a really repetitive code and I'm sure could be cleaned up. I would appreciate some advice on how you would do this.</p> <p>Here is an example CSV:</p> <pre><code>Category.Position,Name,Time,Team,RandomInt1,RandomInt2,Male? A,1,Person 4,00:54:12.92,2281,343,4.4,1 A,2,Person 3,00:54:13.29,10195,310,4.2,1 A,3,Person 2,00:54:19.19,84,334,5.0,1 A,4,Person 1,00:54:19.33,7535,297,4.9,1 </code></pre> <p>Category would change as you go down the CSV</p> <p>The <code>Male?</code> column is 1 when the person is male and 0 when they are female, Validclubs is a list of the team numbers which I want to use, imported from a txt file, RandomInt1/RandomInt2 are irrelevant for now</p> <p>I would appreciate any advice on reducing the code so it is cleaner/shorter.</p> <p>I want to use built-in libraries so not pandas.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:55:26.370", "Id": "480838", "Score": "0", "body": "_not pandas_ - why not?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:56:43.250", "Id": "480839", "Score": "0", "body": "Please include your code that loads `valid_clubs`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T20:00:48.697", "Id": "480843", "Score": "0", "body": "@Reinderien I have added now, on Pandas I have never worked with them, I have no knowledge of them so if I put this in and I want to make changes to my code I would not fully understand what it is doing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T20:02:05.430", "Id": "480844", "Score": "0", "body": "It's a useful thing to learn :) For small projects and datasets stock Python is fine, but you'll quickly run into performance issues when you try to scale." } ]
[ { "body": "<h2>Set membership</h2>\n<pre><code>valid_clubs = []\nwith open(&quot;validclubs.txt&quot;) as f:\n for line in f:\n valid_clubs.append(line)\n</code></pre>\n<p>should be</p>\n<pre><code>with open(&quot;validclubs.txt&quot;) as f:\n valid_clubs = {line.strip() for line in f}\n</code></pre>\n<p>Lines coming back from a file handle in Python include their line ending, which you have to strip yourself; and you should be using a set, not a list. Set membership lookups will be much faster than list lookups.</p>\n<h2>Consider <code>DictReader</code></h2>\n<p>The <code>csv</code> module has a reader that gives you back a dictionary based on the headings, so that you do not have to write <code>row[0]</code>, but rather <code>row['Category']</code>.</p>\n<h2>Use <code>Counter</code></h2>\n<p>Your list of category <code>ifs</code> can be condensed to a one-liner; read about <a href=\"https://docs.python.org/3.8/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\">Counter</a>. This will be easier to use and perform better.</p>\n<h2>Empty rows</h2>\n<p>Based on <code># ignore errors where row is empty</code>, this should be done up-front. Rather than hitting your face on an <code>IndexError</code> and having to ignore it, simply check for an empty row:</p>\n<pre><code>if row:\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T20:12:09.093", "Id": "244902", "ParentId": "244898", "Score": "3" } } ]
{ "AcceptedAnswerId": "244902", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T19:37:04.507", "Id": "244898", "Score": "3", "Tags": [ "python", "csv" ], "Title": "Count the number of riders in each category" }
244898
<p>This is a simple and short &quot;Pretty Bytes&quot; javascript function using the SI Decimal System for quantifying bytes.</p> <p>The code does not use complex maths such as <code>Math.pow()</code> or <code>Math.log()</code> and mainly uses strings with an array.</p> <p>The function uses the SI system of decimals as shown below (1 kilo = 1,000, 1 M = 1,000,000, etc.).</p> <p><a href="https://i.stack.imgur.com/Hqb3v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hqb3v.png" alt="enter image description here" /></a></p> <p>The number of decimal places is defaulted to 2 (no rounding is necessary) but can be modified on calling the function to other values. The common most used display is the default 2 decimal place.</p> <p>The code is short and uses the method of <strong>Number String Triplets</strong> to first convert the input number (the integer) into a Number String Triplet, then into an array of triplets.</p> <p>The following one-line code is used for converting an integer into a Number String Triplet so that the resulting string will always be made of multiple of 3's by padding zero(s) to the left. It is the same concept used under this code review article: <a href="https://codereview.stackexchange.com/questions/223936/simple-number-to-words-using-a-single-loop-string-triplets-in-javascript">Simple Number to Words using a Single Loop String Triplets</a></p> <pre><code>Num = &quot;0&quot;.repeat((Num += &quot;&quot;).length * 2 % 3) + Num; // Make a Number String Triplet </code></pre> <p>The output is then made up of concatenating the first element of the array being the whole number and the 2nd element being the fraction (after chopping off for decimals) and adding the suffix letter.</p> <p>Numbers below 1000 do not require the functional code and are cleared out first.</p> <p>If there is a possibility that the input number may be a float, it should be converted to an integer first <code>Num = Math.floor(Num);</code> before passing it to the function.</p> <p>As the code is mainly for <strong>displaying size</strong>, no code is added for handling negative numbers or floats (<em>not sure if one would give a size as '3 and a half byte'</em>).</p> <p>I welcome your code review.</p> <p>Thanks</p> <p>Mohsen Alyafei</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 : numberPrettyBytesSI() * @purpose : Convert number bytes size to human readable format * using the SI Decimal System. * @version : 1.00 * @author : Mohsen Alyafei * @date : 01 July 2020 * @param : {num} [integer] Number to be converted * @param : {decimals} [integer] Deciaml places (defaul 2) * @returns : {String} Pretty Number **********************************************************************/ function numberPrettyBytesSI(Num=0, decimals=2){ if (Num &lt; 1000) return Num + " Bytes"; Num = "0".repeat((Num += "").length * 2 % 3) + Num; // Make a Number String Triplet Num = Num.match(/.{3}/g); // Make an Array of Triplets return Number(Num[0]) + // Whole Number withou leading zeros "." + // dot Num[1].substring(0, decimals) + " " + // Fractional part " kMGTPEZY"[Num.length] + "B"; // The SI suffix } //*********** tests *********************** console.log(numberPrettyBytesSI(0)); // 0 Bytes console.log(numberPrettyBytesSI(500)); // 500 Bytes console.log(numberPrettyBytesSI(1000)); // 1.00 kB console.log(numberPrettyBytesSI(15000)); // 15.00 kB console.log(numberPrettyBytesSI(12345)); // 12.34 Kb console.log(numberPrettyBytesSI(123456)); // 123.45 kb console.log(numberPrettyBytesSI(1234567)); // 1.23 MB console.log(numberPrettyBytesSI(12345678)); // 12.34 MB console.log(numberPrettyBytesSI(123456789)); // 123.45 MB console.log(numberPrettyBytesSI(1234567890)); // 1.23 GB console.log(numberPrettyBytesSI(1234567890,1)); // 1.2 GB console.log(numberPrettyBytesSI(1234567890,3)); // 1.234 GB</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T21:06:25.263", "Id": "480852", "Score": "1", "body": "@Emma Thanks. Done and updated the tags. Good idea, worth looking into." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T20:40:10.420", "Id": "244903", "Score": "4", "Tags": [ "javascript", "array", "regex", "number-systems" ], "Title": "Simple Pretty-Bytes Size (SI System)" }
244903
<p>I apologize in advance for my English.</p> <p>I have a user search method. It's parameters - <code>login</code> and <code>strict</code>. The last one determines, which method should have been used for search - <code>Equals</code> (strict is true) or <code>Contains</code> (strict is false). How should I implement it? I could do two different methods, but I think it would be code repeating.</p> <pre><code> public async Task&lt;List&lt;UserFindInfoDTO&gt;&gt; FindUserByLoginAsync(string login, bool strict) { var users = await context.Users .Where(u =&gt; u.Nickname.Equals(login)) // change on &quot;Contains&quot; if strict is false .Select(u =&gt; new UserFindInfoDTO { Status = u.Status, Id = u.Id, MiniAvatar = u.Image, Nickname = u.Nickname }) .ToListAsync(); ... return users; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T06:06:20.143", "Id": "480886", "Score": "4", "body": "If the code is unfinished, it's not ready for review. Please take a look at the [help/on-topic]." } ]
[ { "body": "<p>The lambda expression you pass to <code>Where()</code> is where you define the condition, so this is where it makes the most sense to put all the logic for this.</p>\n<pre><code>.Where(u =&gt; strict ? u.Nickname.Equals(login) : u.Nickname.Contains(login))\n</code></pre>\n<p>Or for higher performance you can conditionally pass a different lambda expression:</p>\n<pre><code>Func&lt;User,bool&gt; checker = strict\n ? (Func&lt;User,bool&gt;)((User u) =&gt; u.Nickname.Equals(login))\n : (Func&lt;User,bool&gt;)((User u) =&gt; u.Nickname.Contains(login));\n\n...\n\n.Where(checker)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T21:41:49.983", "Id": "480855", "Score": "0", "body": "I thought about it but I am afraid that the program will check this condition for every string. Or it will check once and choose the necessary method for all strings?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T21:55:45.967", "Id": "480858", "Score": "0", "body": "@ZOOMSMASH You can conditionally choose between lambda expressions, I added an example of it to my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T22:03:27.353", "Id": "480860", "Score": "0", "body": "Yeah I added one too many, removed it now. And you're welcome :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T22:07:43.103", "Id": "480861", "Score": "0", "body": "@ZOOMSMASH Also I just realized I assigned the type `bool` to the lambda input instead of the user object!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T22:08:49.580", "Id": "480863", "Score": "0", "body": "Yeah, and I don't want to be meticulous, but check brackets again :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T22:10:28.647", "Id": "480864", "Score": "0", "body": "lol I'm too tired for writing code... ok now everything should be in order" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T22:28:48.210", "Id": "480865", "Score": "0", "body": "@ZOOMSMASH oh wait... I found another mistake! jeez I'm sorry for messing around with you like that... It should be `Func`, not `Action` since it has a return value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T22:39:15.990", "Id": "480866", "Score": "0", "body": "it's okay, I understood the main idea, don't worry about little mistakes :)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T21:34:58.980", "Id": "244906", "ParentId": "244905", "Score": "1" } } ]
{ "AcceptedAnswerId": "244906", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T21:20:26.160", "Id": "244905", "Score": "0", "Tags": [ "c#" ], "Title": "Call method by condition" }
244905
<p>I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <blockquote> <p>A full binary tree is a binary tree where each node has exactly 0 or 2 children.</p> <p>Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree.</p> <p>Each node of each tree in the answer must have <code>node.val = 0</code>.</p> <p>You may return the final list of trees in any order.</p> <h3>Example 1:</h3> <p>Input: 7</p> <pre><code>Output: [ [0,0,0,null,null,0,0,null,null,0,0], [0,0,0,null,null,0,0,0,0], [0,0,0,0,0,0,0], [0,0,0,0,0,null,null,null,null,0,0], [0,0,0,0,0,null,null,0,0] ] </code></pre> <p><a href="https://i.stack.imgur.com/BEJ6M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BEJ6M.png" alt="enter image description here" /></a></p> <h3>Note:</h3> <p><code>1 &lt;= N &lt;= 20</code></p> </blockquote> <h3>Code</h3> <pre><code>#include &lt;vector&gt; class Solution { public: static TreeNode *clone_tree(const TreeNode *node) { TreeNode *root = new TreeNode(0); root-&gt;left = (node-&gt;left) ? clone_tree(node-&gt;left) : nullptr; root-&gt;right = (node-&gt;right) ? clone_tree(node-&gt;right) : nullptr; return root; } static std::vector&lt;TreeNode *&gt; allPossibleFBT(const size_t n) { std::vector&lt;TreeNode *&gt; full_binary_trees; if (n == 1) { // full_binary_trees.push_back(new TreeNode(0)); full_binary_trees.emplace_back(new TreeNode(0)); } else if (n &amp; 1) { for (size_t index = 2; index &lt;= n; index += 2) { const auto left = allPossibleFBT(index - 1); const auto right = allPossibleFBT(n - index); for (size_t left_index = 0; left_index &lt; left.size(); left_index++) { for (size_t right_index = 0; right_index &lt; right.size(); right_index++) { full_binary_trees.emplace_back(new TreeNode(0)); if (right_index == right.size() - 1) { full_binary_trees.back()-&gt;left = left[left_index]; } else { full_binary_trees.back()-&gt;left = clone_tree(left[left_index]); } if (left_index == left.size() - 1) { full_binary_trees.back()-&gt;right = right[right_index]; } else { full_binary_trees.back()-&gt;right = clone_tree(right[right_index]); } } } } } return full_binary_trees; } }; </code></pre> <ul> <li><p><a href="https://leetcode.com/problems/all-possible-full-binary-trees/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/all-possible-full-binary-trees/solution/" rel="nofollow noreferrer">Solution</a></p> </li> <li><p><a href="https://leetcode.com/problems/all-possible-full-binary-trees/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> </ul>
[]
[ { "body": "<h1>Make <code>clone_tree()</code> private</h1>\n<p>Make helper functions that are not part of the public API <code>private</code>.</p>\n<h1>Avoid unnecessary nesting of statements if possible</h1>\n<p>In <code>allPossibleFBT()</code> there's a lot of indentation. There's a risk of the code running off the right hand side of the screen, making it hard to read. Try to reduce nesting if possible (but only if it improves readability and maintainability). In this case, you can get rid of the outermost <code>if</code>-statements by doing an early return if <code>n</code> is even, and then unconditionally adding the single-node tree:</p>\n<pre><code>static std::vector&lt;TreeNode *&gt; allPossibleFBT(const size_t n) {\n // Exit early if n is even\n if ((n &amp; 1) == 0)\n return {};\n\n // Start with the one-node tree\n std::vector&lt;TreeNode *&gt; full_binary_trees{new TreeNode(0)};\n\n // Add more complex trees\n for (size_t index = 2; ...) {\n ...\n }\n\n return full_binary_trees;\n}\n</code></pre>\n<h1>Take a reference of an object if you are using it a lot</h1>\n<p>When we see a common expression being reused a lot, we can create a new variable holding the result of that expression. When the expression is actually an object, and we don't want to copy the object, we can still avoid repeating the expression by creating a reference to that object. So instead of explicitly writing <code>full_binary_trees.back()</code> many times, write:</p>\n<pre><code>auto &amp;root = full_binary_trees.emplace_back(new TreeNode(0));\n\nif (right_index == right_size() - 1) {\n root-&gt;left = ...\n</code></pre>\n<p>Since C++17, <code>emplace_back()</code> returns a reference to the emplaced element. In case you are writing code for older standards, you could write:</p>\n<pre><code>full_binary_trees.emplace_back(new TreeNode(0));\nauto &amp;root = full_binary_trees.back();\n...\n</code></pre>\n<p>But perhaps it would even be better to first created the new tree, and then append it to the vector at the end:</p>\n<pre><code>auto root = new TreeNode(0);\n\nif ...\n\nfull_binary_trees.emplace_back(root);\n</code></pre>\n<h1>Other possible improvements</h1>\n<p>It would be nice to get rid of the inner-most if-statements, which is possible if you don't care about memory leaks:</p>\n<pre><code>for (auto left: allPossibleFBT(index - 1)) {\n for (auto right: allPossibleFBT(n - index)) {\n auto root = new TreeNode(0);\n root-&gt;left = clone_tree(left);\n root-&gt;right = clone_tree(right);\n full_binary_trees.emplace_back(root);\n }\n}\n</code></pre>\n<p>In the context of this LeetCode problem, which doesn't state whether or not you are allowed to link a node into multiple trees, you might even get away with not calling clone_tree() at all, but just writing <code>root-&gt;left = left; root-&gt;right = right</code>.</p>\n<p>Also note that this problem might benefit from memoization.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T16:10:00.927", "Id": "244951", "ParentId": "244908", "Score": "2" } } ]
{ "AcceptedAnswerId": "244951", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T22:08:21.667", "Id": "244908", "Score": "4", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 894: All Possible Full Binary Trees" }
244908
<p>I wrote a function that finds the sum of all numeric palindromes lesser than N.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const sumOfPalindromes = (n) =&gt; { let x = 0; for (let i = 0; i &lt;= n; i++) { x += i == (''+i).split('').reverse().join('') ? i : 0; } return x; } console.log(sumOfPalindromes(10000)); console.log(sumOfPalindromes(24));</code></pre> </div> </div> </p> <p>Are there shorter, more-concise alternatives to the above approach (preferably without using a <code>for loop</code>)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T03:22:26.393", "Id": "480876", "Score": "0", "body": "Your implementation is 1 off for any `n` that is a palindrome because `i <= n` does not implement the \"lesser then n\" predicate, it implements \"lesser or equal\". Btw is `1.1` a numeric palindrome?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T11:21:48.077", "Id": "480912", "Score": "0", "body": "@slepic I completely missed that. Thanks for pointing that out. And no, floats are not included." } ]
[ { "body": "<p>The function you posted seems to me to be the best. Here is your function re-arranged slightly using short-circuiting as an alternative way:</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 sumOfPalindromes = n =&gt; {\n let x = 0;\n for (let i = 0; i &lt;= n; i++)\n i == (''+i).split('').reverse().join('') &amp;&amp; (x += i);\n return x };\n\nconsole.log(sumOfPalindromes(10000));\nconsole.log(sumOfPalindromes(24));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T00:09:39.000", "Id": "244911", "ParentId": "244909", "Score": "3" } }, { "body": "<p>This is not a proper review, but rather an extended comment.</p>\n<blockquote>\n<p>Are there shorter, more-concise alternatives to the above approach</p>\n</blockquote>\n<p>Yes. You should view it not as a programming problem, but as a recreational math exercise.</p>\n<p>Consider a simplest case of <code>N</code> being an even power of <code>10</code>, say <code>1000000</code>. For a moment, allow leading zeroes. Now, each 6-digit palindromic number <code>abccba</code> corresponds to a 3-digit number <code>abc</code>, and in fact is <code>1000*abc + cba</code>. Notice that if the sum of all 3-digit numbers is <code>X</code>, the sum of all 6-digit palindromic numbers is <code>1000*X + X = 1001*X</code>. As for <code>X</code>, recall the formula for the sum of an arithmetic progression <code>0 + 1 + 2 + ... + 999</code>.</p>\n<p>To deal with leading zeroes you must subtract the sum of those palindromic numbers which do have leading zeroes. Yet again, they are in form <code>abba0 = 1000*ab + 10*ba</code>. Yet again, use the arithmetic progression formula to get the result.</p>\n<p>No programming beyond a few arithmetic operations is required.</p>\n<p>I don't want to spell out the complete solution. I hope this is enough to get you started with the arbitrary N.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T00:37:17.770", "Id": "244912", "ParentId": "244909", "Score": "4" } }, { "body": "<p>&quot;numeric palindromes&quot; is rather unfortunate term. It is not clear if nonintegers are to be considered. The implementation only considers integers, in which case i would rather use term &quot;palindromic integers&quot;.</p>\n<p>It is also not explicitly stated, although assumed, that only base 10 representations are to be considered. Some numbers that are not palindromic in base 10 may be palindromic in different bases. I would actualy say that every nonnegative integer is palindromic in infinte amount of various bases. And so even a better term might be &quot;palindromic base 10 integers&quot;.</p>\n<blockquote>\n<p>preferably without using a for loop</p>\n</blockquote>\n<p>That is a silly requirement, you could do it with <code>reduce</code> but that would require to first create an array of all the numbers less then n. Which would increase the memory complexity of the implementation to <code>O(n)</code> for no real benefit. And it will probably be slower, although the big-O time complexity stays the same.</p>\n<p>To be complete the current memory complexity Is <code>O(log(n))</code>. And time complexity is <code>O(n * log(n))</code>, or more precisely <code>O(log(n!))</code>.</p>\n<p>Since you are not asking to improve performance, but rather to shorten the code (and that's perfectly fine if you dont pass large n's and dont call the function many times in a loop) , I would say you are pretty good with your current implementation.</p>\n<p>I would just replace the ternary with an <code>if</code> because adding zero is a useless operation.</p>\n<p>And there is a bug in your implementation where the result is by 1 greater then it should be if the input n is a palindrome. You should do <code>i &lt; n</code> instead of <code>i &lt;= n</code>.</p>\n<p>If you want to improve the time complexity, you need to do some maths as @vnp already suggested. Intuition tells me you might end up with time complexity <code>O(log(n))</code> and that will be a big improvement for bigger n's compared to your current <code>O(log(n!))</code> implementation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T04:50:35.307", "Id": "244917", "ParentId": "244909", "Score": "3" } } ]
{ "AcceptedAnswerId": "244912", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-02T23:25:51.327", "Id": "244909", "Score": "3", "Tags": [ "javascript" ], "Title": "Finding the sum of all numeric palindromes that are less than N" }
244909
<p>Follow up question <a href="https://codereview.stackexchange.com/questions/201672/image-processing-using-python-oop-library">Image processing using Python OOP library</a></p> <p>I want to use multiprocessing to analyze several images in parallel:</p> <pre><code>class SegmentationType(object): DISPLAY_NAME = &quot;invalid&quot; def __init__(self, filename, path): self.filename = filename self.path = path self.input_data = None self.output_data = None def read_image(self): self.input_data = cv2.imread(self.path + self.filename)[1] def write_image(self): cv2.imwrite(self.path + self.filename.split('.')[0] + '_' + self.DISPLAY_NAME + '.png', self.output_data) def process(self): # override in derived classes to perform an actual segmentation pass def start_pipeline(self): self.read_image() self.process() self.write_image() class HSV_Segmenter(SegmentationType): DISPLAY_NAME = 'HSV' def process(self): source = rgb_to_hsv(self.input_data) self.output_data = treshold_otsu(source) class LabSegmenter(SegmentationType): DISPLAY_NAME = 'LAB' def process(self): source = rgb_to_lab(self.input_data) self.output_data = global_threshold(source) segmenter_class = { 'hsv': HSV_Segmentation, 'lab': LAB_Segmenter }.get(procedure) if not segmenter_class: raise ArgumentError(&quot;Invalid segmentation method '{}'&quot;.format(procedure)) for img in images: os.chdir(img_dir) processor = = segmenter_class(img, img_dir, procedure) processor.start_pipeline() </code></pre> <p>What I tried so far:</p> <pre><code>image_lst = os.listdir(my_image_path) # We split the list into sublist with 5 elements because of 512 GB RAM limitation if len(image_lst) &gt; 4: nr_of_sublists = (int(len(image_lst)/2.5)) image_sub_lst =(np.array_split(image_lst, nr_of_sublists)) else: image_sub_lst = [image_lst] # We do the analysis for each sublist for sub_lst in image_sub_lst: print (sub_lst) pool = multiprocessing.Pool(8) # Call the processor processor = = segmenter_class(img, img_dir, procedure) processor.start_pipeline() # How to call map??? pool.map(?, sub_lst) pool.terminate() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T07:51:31.680", "Id": "480895", "Score": "1", "body": "Hello, I saw you used `opencv` tag and image processing in your previous post's title, these could be useful in this post too to increment odds of receiving detailed answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T18:33:48.127", "Id": "481139", "Score": "1", "body": "_What I tried so far_ - to be clear: from what you've tried so far, is the output correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T18:44:05.057", "Id": "481142", "Score": "1", "body": "Also, is this Python 2 or 3?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-10T19:35:25.167", "Id": "481691", "Score": "0", "body": "Hi snowflake. Unfortunately your question is currently off-topic. Questions must [include a description of what the code does](//codereview.meta.stackexchange.com/q/1226). Once you have fixed the issues with your post we'll be happy to review your code." } ]
[ { "body": "<h2>A warning on version</h2>\n<p>Many of the following suggestions assume that you are using Python 3.</p>\n<h2>Bare inheritance</h2>\n<pre><code>class SegmentationType(object):\n</code></pre>\n<p>can be</p>\n<pre><code>class SegmentationType:\n</code></pre>\n<h2>Abstract statics</h2>\n<pre><code>DISPLAY_NAME = &quot;invalid&quot;\n</code></pre>\n<p>should not really assign a value. Instead,</p>\n<pre><code>DISPLAY_NAME: str\n</code></pre>\n<h2>Unpacking <code>imread</code></h2>\n<p><a href=\"https://docs.opencv.org/master/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56\" rel=\"nofollow noreferrer\">The documentation</a> is deeply unhelpful: it says that <code>imread</code> returns &quot;retval&quot;. Given your usage it's obvious that reality is more complicated, because you're indexing into it. Try to unpack instead:</p>\n<pre><code>_, self.input_data = cv2.imread(self.path + self.filename)\n</code></pre>\n<h2>Abstract methods</h2>\n<p><code>process</code> should <code>raise NotImplementedError</code> in the base.</p>\n<h2>Factory</h2>\n<p>You have a factory dictionary that should be turned into a method, something like</p>\n<pre><code>def get_segmenter(name: str) -&gt; Type[SegmentationType]:\n return {\n t.DISPLAY_NAME: t\n for t in (HSVSegmenter, LABSegmenter)\n }[name]\n</code></pre>\n<h2>Outer parentheses</h2>\n<p>Neither of these:</p>\n<pre><code>nr_of_sublists = (int(len(image_lst)/2.5))\nimage_sub_lst =(np.array_split(image_lst, nr_of_sublists))\n</code></pre>\n<p>needs outer parentheses.</p>\n<h2>Syntax</h2>\n<p>Surely this is a typo? This will not run:</p>\n<pre><code>processor = = segmenter_class(img, img_dir, procedure)\n</code></pre>\n<p>nor will this:</p>\n<pre><code>pool.map(?, sub_lst)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T06:30:52.660", "Id": "481186", "Score": "0", "body": "Thank you very much for your suggestions and improvements. For the last two lines, I don't know how to call the segmenter_class in a multiprocessing way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T12:51:19.237", "Id": "481229", "Score": "0", "body": "That part of the question is off-topic. CodeReview only covers code that is complete and working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-08T08:24:54.787", "Id": "481435", "Score": "0", "body": "Ok I will ask at SO" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T18:57:33.880", "Id": "245044", "ParentId": "244920", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T05:42:04.410", "Id": "244920", "Score": "1", "Tags": [ "python", "object-oriented", "image", "opencv", "multiprocessing" ], "Title": "Parallel image segmentation" }
244920
<p>I've developed task solution following a learning program:</p> <pre><code>class CssSelectorBuilder { constructor() { this.selectors = [{ selectorName: '', selector: '' }]; this.order = ['', 'element', 'id', 'class', 'attr', 'pseudoClass', 'pseudoElement']; } element(value) { const it = new CssSelectorBuilder(); it.selectors = this.selectors.slice(); const prevSelector = it.selectors.pop(); if (prevSelector.selectorName === 'element') { throw new Error('Element, id and pseudo-element should not occur more then one time inside the selector'); } if (it.order.slice(2).includes(prevSelector.selectorName)) { throw new Error('Selector parts should be arranged in the following order: element, id, class, attribute, pseudo-class, pseudo-element'); } it.selectors.push({ selectorName: 'element', selector: value }); return it; } id(value) { const it = new CssSelectorBuilder(); it.selectors = this.selectors.slice(); const prevSelector = it.selectors.pop(); if (prevSelector.selectorName === 'id') { throw new Error('Element, id and pseudo-element should not occur more then one time inside the selector'); } if (it.order.slice(3).includes(prevSelector.selectorName)) { throw new Error('Selector parts should be arranged in the following order: element, id, class, attribute, pseudo-class, pseudo-element'); } it.selectors.push(prevSelector); it.selectors.push({ selectorName: 'id', selector: `#${value}` }); return it; } class(value) { const it = new CssSelectorBuilder(); it.selectors = this.selectors.slice(); const prevSelector = it.selectors.pop(); if (it.order.slice(4).includes(prevSelector.selectorName)) { throw new Error('Selector parts should be arranged in the following order: element, id, class, attribute, pseudo-class, pseudo-element'); } it.selectors.push(prevSelector); it.selectors.push({ selectorName: 'class', selector: `.${value}` }); return it; } attr(value) { const it = new CssSelectorBuilder(); it.selectors = this.selectors.slice(); const prevSelector = it.selectors.pop(); if (it.order.slice(5).includes(prevSelector.selectorName)) { throw new Error('Selector parts should be arranged in the following order: element, id, class, attribute, pseudo-class, pseudo-element'); } it.selectors.push(prevSelector); it.selectors.push({ selectorName: 'attr', selector: `[${value}]` }); return it; } pseudoClass(value) { const it = new CssSelectorBuilder(); it.selectors = this.selectors.slice(); const prevSelector = it.selectors.pop(); if (it.order.slice(6).includes(prevSelector.selectorName)) { throw new Error('Selector parts should be arranged in the following order: element, id, class, attribute, pseudo-class, pseudo-element'); } it.selectors.push(prevSelector); it.selectors.push({ selectorName: 'pseudoClass', selector: `:${value}` }); return it; } pseudoElement(value) { const it = new CssSelectorBuilder(); it.selectors = this.selectors.slice(); const prevSelector = it.selectors.pop(); if (prevSelector) { if (prevSelector.selectorName === 'pseudoElement') { throw new Error('Element, id and pseudo-element should not occur more then one time inside the selector'); } it.selectors.push(prevSelector); } it.selectors.push({ selectorName: 'pseudoElement', selector: `::${value}` }); return it; } // ... } </code></pre> <p>Considering that I've detected some parts have very close functionality. But aggregation of ones is not possible for me because of their view scope.</p> <p>In the code you could find a few differences</p> <pre><code> UNIQUE_METHOD_NAME UNIQUE_SELECTOR_NAME UNIQUE_ORDER_ID UNIQUE_SELECTOR_VALUE_FORMAT </code></pre> <p>in generally duplicated blocks (functions):</p> <pre><code> UNIQUE_METHOD_NAME(value) { const it = new CssSelectorBuilder(); it.selectors = this.selectors.slice(); const prevSelector = it.selectors.pop(); /// OPTIONAL PART if (prevSelector.selectorName === 'UNIQUE_SELECTOR_NAME') { throw new Error('Element, id and pseudo-element should not occur more then one time inside the selector'); } /// optional part END if (it.order.slice(UNIQUE_ORDER_ID).includes(prevSelector.selectorName)) { throw new Error('Selector parts should be arranged in the following order: element, id, class, attribute, pseudo-class, pseudo-element'); } it.selectors.push({ selectorName: 'UNIQUE_SELECTOR_NAME', selector: UNIQUE_SELECTOR_VALUE_FORMAT }); return it; } </code></pre> <h2>Question:</h2> <p>Any ideas on how to simplify this solution?</p> <h2>P.S.</h2> <p>I've tried to move it into separate function, but it appears a lot of <code>if</code> operators make the original view more readable than the refactored part.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T06:47:36.013", "Id": "480888", "Score": "5", "body": "Please describe in detail what your code is supposed to do and change the title to a brief description of that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T11:08:48.267", "Id": "480911", "Score": "0", "body": "@πάνταῥεῖ thanks, there was added tags also. NOTE: If you are not familiar with javascript I do not think you can figure out how to simplify it with function binding for example or other magic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T12:57:45.440", "Id": "480922", "Score": "1", "body": "Whether or not we know JavaScript is not the issue here, one of the requirements of posting on code review is to explain what the code does so that we can better understand the question and provide a better code review. Please see our [guidelines on asking a good question on Code Review](https://codereview.stackexchange.com/help/asking). There are currently 2 Votes to Close this question, it will be closed when there are 5 votes to close." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T06:43:23.600", "Id": "244923", "Score": "1", "Tags": [ "javascript", "object-oriented" ], "Title": "Custom CssSelectorBuilder object in JavaScript" }
244923
<p>This is just a very simple form that tells you the liquidity ratio, daily cost of running, and days cash on hand of a company, given their current assets, current liabilities, and total expense of the year.</p> <p>The output gives you a very simplistic of how a company might be doing financially. The required input numbers can usually be found from a company's annual report or financial report if you have access to it.</p> <p>I had been working for public organisations that publishes their annual financial report and had been doing these figures by hand to help myself to understand the financial state of the company. It merely helps myself as I don't have the financial background to really understand a financial report an accountant might.</p> <p>I have written this form to practice using reactjs, as I am learning reactjs for the first time.</p> <p>The codebase is relatively simple, all of the logic are stored just one file App.js:</p> <pre><code>import React, { useState, useEffect } from &quot;react&quot;; import &quot;./styles.css&quot;; const DefaultInstructionText = () =&gt; ( &lt;p&gt;The result will be displayed here once all the fields are filled out.&lt;/p&gt; ); const Result = ({ liquidityRatio, dailyCost, daysCashOnHand }) =&gt; { const format = (num, roundFunc) =&gt; { if (num &gt;= 1.0) { return parseFloat(roundFunc(num * 100) / 100).toFixed(2); } else { return num; } }; return ( &lt;&gt; &lt;p&gt;Liquidity ratio: {format(liquidityRatio, Math.floor)}&lt;/p&gt; &lt;p&gt;Daily cost of running: {format(dailyCost, Math.ceil)}&lt;/p&gt; &lt;p&gt;Days cash on hand: {format(daysCashOnHand, Math.floor)}&lt;/p&gt; &lt;/&gt; ); }; const NumberField = ({ label, value, changeHandler }) =&gt; { return ( &lt;label&gt; {label} &lt;br /&gt; &lt;input type=&quot;number&quot; required min={1} step=&quot;any&quot; value={value} onChange={changeHandler} /&gt; &lt;/label&gt; ); }; export default function App() { const [currentAsset, setCurrentAsset] = useState(&quot;&quot;); const [currentLiability, setCurrentLiability] = useState(&quot;&quot;); const [totalExpense, setTotalExpense] = useState(&quot;&quot;); const [showResult, setShowResult] = useState(false); const [liquidityRatio, setLiquidityRatio] = useState(null); const [dailyCost, setDailyCost] = useState(null); const [daysCashOnHand, setDaysCashOnHand] = useState(null); const validateNumber = num =&gt; { if (isNaN(num) || &quot;&quot; === num.trim() || num &lt; 0) { return false; } else { return true; } }; useEffect(() =&gt; { let newShowResult; if ( validateNumber(currentAsset) &amp;&amp; validateNumber(currentLiability) &amp;&amp; validateNumber(totalExpense) ) { newShowResult = true; } else { newShowResult = false; } // New result need to be computed if (newShowResult) { /** * Liquidity ratio: Total current (quick) assets / total current liabilities (rounded down) (&gt;= 1) * Daily cost of running: Total expenses / 365 (rounded up) * Days cash on hand: Total current asset / daily cost (rounded down) (&gt;=90 days) */ let newDailyCost = totalExpense / 365.0; setLiquidityRatio(currentAsset / currentLiability); setDailyCost(newDailyCost); setDaysCashOnHand(currentAsset / newDailyCost); } // Finally update showResult state setShowResult(newShowResult); }, [currentAsset, currentLiability, totalExpense]); return ( &lt;div className=&quot;App&quot;&gt; &lt;NumberField label=&quot;Current assets&quot; value={currentAsset} changeHandler={e =&gt; { setCurrentAsset(e.target.value); }} /&gt; &lt;NumberField label=&quot;Current liabilities&quot; value={currentLiability} changeHandler={e =&gt; { setCurrentLiability(e.target.value); }} /&gt; &lt;NumberField label=&quot;Total expenses&quot; value={totalExpense} changeHandler={e =&gt; { setTotalExpense(e.target.value); }} /&gt; &lt;hr /&gt; {showResult ? ( &lt;Result liquidityRatio={liquidityRatio} dailyCost={dailyCost} daysCashOnHand={daysCashOnHand} /&gt; ) : ( &lt;DefaultInstructionText /&gt; )} &lt;/div&gt; ); } </code></pre> <p>The entire working codebase is on code sandbox if you like to read it there instead. You can actually see and test out the web form too: <a href="https://codesandbox.io/s/gracious-aryabhata-2bjmk" rel="noreferrer">https://codesandbox.io/s/gracious-aryabhata-2bjmk</a></p> <p>I am trying to stick with functional components and hooks as they seem to be the standard going forward with reactjs. I like to learn reactjs properly so please let me know if this is not the right way of doing things and anything that can be done better. Thank you! :)</p>
[]
[ { "body": "<p>You don't need to use <code>useEffect</code> and result states: liquidityRatio, dailyCost. Just edit like this</p>\n<p><a href=\"https://i.stack.imgur.com/FXFmE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FXFmE.png\" alt=\"enter image description here\" /></a></p>\n<p>When you change your inputs, the render will be called and excecute from top to bottom. And result variables will be computed again.</p>\n<p><strong>Notes: That just basic answer for beginner in React.</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T14:41:28.497", "Id": "480933", "Score": "0", "body": "Ah sure, it does work without useEffect. So when would be a good use case for useEffect?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T16:24:27.707", "Id": "480956", "Score": "1", "body": "Basically when you want to call api. Hmm... If you learn React in the rightway you will know when you use it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-04T15:53:41.510", "Id": "481053", "Score": "1", "body": "We generally prefer code to be embedded in the question or answer rather than using an image. In a question the image of the code will get the question closed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T14:47:25.863", "Id": "481120", "Score": "0", "body": "Don't close the question please!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T12:40:03.373", "Id": "244939", "ParentId": "244932", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T09:48:22.900", "Id": "244932", "Score": "5", "Tags": [ "javascript", "beginner", "functional-programming", "react.js" ], "Title": "A simple reactjs form to calculate the liquidity ratio, daily cost of running, and days cash on hand" }
244932
<h2>Introduction</h2> <p>I'm new to python and made this code which computes the decay of sulphur dioxide (SO2) pollutant in a chemical reactor by ozone (O3) when it is hit by UV light.</p> <h2>Code description</h2> <p>Short explanation of the code: using the Cantera python package I define a set of properties for the gas (air + SO2 + O3) and the reactor. The reactions are stored in an external file (photolysis.cti) which I included after the code. Then the reactions are allowed to play out but at each time instant the rate of the reaction controlled by UV light is updated. This is done based on the instantaneous concentration of the species present and the UV light distribution. This can be modelled using several models I implemented. Some models (MPSS, MSSS) are more accurate but also more complex so the simulation will take longer if they are selected (~45s vs ~1s for the rest). After the simulation finished, a plot with the decay of SO2 with time is shown:</p> <p><img src="https://i.imgur.com/LASJdJu.png" alt="Text" /></p> <h2>Aim of this review</h2> <p>My aim is to improve both the python aspect (syntax, making it easier to read, more idiomatic, object oriented...) as well as the performance of the code. Also having the whole code in one single file feels not ideal. Any tips on how to structure the project are very welcome. I know the code is long but I tried to comment all functions to improve readability and made a very simple log to know what the code is doing.</p> <h2>Python code</h2> <p>The code I wrote is the following:</p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot; Code to compute a CSTR UV reactor with Cantera &quot;&quot;&quot; import re import time import pandas as pd import numpy as np import cantera as ct import discretize.CylMesh import matplotlib.pyplot as plt from scipy.constants import N_A, h, c def reactor_volume(L, r_outer, r_inner): &quot;&quot;&quot; Computes the volume of an annular reactor (hollow cylinder). Parameters [units] ------------------ L : int, float Length of the reactor/lamp [m] r_outer : int, float Outer radius [m] r_outer : int, float Inner radius [m] Returns [units] --------------- V_r : float The reactor volume [m**2] &quot;&quot;&quot; return np.pi*L*(r_outer**2-r_inner**2) def make_cyl_mesh(L, r, ncr, ncz): &quot;&quot;&quot; Makes a cylindrical mesh object with one cell in the azimuthal direction. Parameters [units] ------------------ L : int, float Length of the reactor/lamp [m] r : int, float Cylinder radius [m] ncr : int Number of cells in the radial direction ncz : int Number of cells in the axial direction Returns [units] --------------- mesh : obj The mesh cylinder object &quot;&quot;&quot; dr = r/ncr # cell width r dz = L/ncz # cell width z hr = dr*np.ones(ncr) hz = dz*np.ones(ncz) offset = [0, 0, -L/2] # offset to center z on half the lamp length return discretize.CylMesh([hr, 2*np.pi, hz], offset) def sigma_to_eps(sigma): &quot;&quot;&quot; Converts the molar absorbtion cross section of a gas to the molar absorbtion coefficient in S.I. units. Parameters [units] ------------------ sigma : int, float Absorbtion cross section (log base e) [cm**2] Returns [units] --------------- eps : float molar absorbtion coefficient (log base 10) [m**2 mol**-1] &quot;&quot;&quot; return (sigma*N_A)/(1e4*np.log(10)) def ppm_to_C(ppm): &quot;&quot;&quot; Converts ppm (parts per million) concentration of a gas to concentration in S.I. units. Parameters [units] ------------------ ppm : int, float ppm concentration of a gas [-] Returns [units] --------------- C : float concentration [mol m**-3] &quot;&quot;&quot; rho_air = 1.2 # [kg m**-3] Mr_air = 28.96 # [g mol**-1] Note: this is for DRY air Vm_air = molar_volume(rho_air, Mr_air) # [m**3 mol**-1] C = ppm/(Vm_air*1e6) return C def molar_volume(rho, Mr): &quot;&quot;&quot; Computes the molar volume of a gas. Parameters [units] ------------------ rho : int, float density [kg m**-3] Mr : int, float molar mass [g mol**-1] Returns [units] --------------- Vm : float molar volume [m**3 mol**-1] &quot;&quot;&quot; return (Mr/rho)*1e-3 def exp_medium_absorption(r, ppm=300): &quot;&quot;&quot; Computes the absorption of the medium considered in the fluence rate models. Initially, I will treat only SO2 as absorbing species. Parameters [units] ------------------ r : int, float, array Radial position (i.e. of a mesh element) [m] ppm : int, float ppm concentration of a gas [-] Returns [units] --------------- ema : int, float, array Exponential medium absorption [-] &quot;&quot;&quot; sigma = 1.551258e-19 # Value for SO2 [cm**2] sigma_air = sigma eps_air = sigma_to_eps(sigma_air) C_air = ppm_to_C(ppm) return np.exp(-np.log(10)*eps_air*C_air*r) def coord_ls(L, nls): &quot;&quot;&quot; Computes the coordinates of the number light source elements which have been chosen to model the UV lamp. Parameters [units] ------------------ L : int, float Length of the reactor/lamp [m] nls : int Number of light source elements Returns [units] --------------- coord_ls : array Coordinates of the number light source elements [m] &quot;&quot;&quot; d_ls = L/nls return np.arange(-L/2, L/2+d_ls, d_ls) def optimize_nls(case_variables, tol=1E-2): &quot;&quot;&quot; Computes the optimum number of light sources (nls) for which to model a UV lamp (for the MPSS or MSSS models). This optimum is the lowest nls that makes the fluence rate computed by the model (without medium absorbtion) match the fluence rate computed by the LSI model for a given tolerance. Based on Powell and Lawryshyn 2015. Note: this routine takes some time, proceed with caution. Parameters [units] ------------------ case_variables : array Array contining the following case variables: case_variables = [P, L, eff, r_outer, r_inner, ncr, ncz] P = lamp power [W] L = lamp length [m] eff = lamp efficiency at 254 nm wavelength r_outer = reactor radius [m] r_inner = quartz sleeve radius [m] ncr = number of mesh cells in r ncz = number of mesh cells in z tol : int, float Tolerance for the optimization routine Returns [units] --------------- nls : int (Optimum) number of light source elements &quot;&quot;&quot; P, eff, L, r_outer, r_inner, ncr, ncz = case_variables V_r = reactor_volume(L, r_outer, r_inner) mesh_outer = make_cyl_mesh(L, r_outer, ncr, ncz) mesh_inner = make_cyl_mesh(L, r_inner, ncr, ncz) err, nls = 100, 10 # Initialize error and smallest possible number of light sources # Compute reference LSI vafr I_LSI = compute_vafr(case_variables, model='LSI') # Loop to find the optimum value for the number of light sources while err &gt; tol*I_LSI: nls += 1 I_i_outer = per_cell_fluence_rate_MPSS( mesh_outer, P, eff, L, nls=nls, no_abs=True) I_i_inner = per_cell_fluence_rate_MPSS( mesh_inner, P, eff, L, nls=nls, no_abs=True) I_MPSS = volume_avg_fluence_rate( I_i_outer, mesh_outer, I_i_inner, mesh_inner, V_r) err = np.abs(I_MPSS-I_LSI) return nls def per_cell_fluence_rate_RAD(mesh, P, eff, L, no_abs=False, ppm=300): &quot;&quot;&quot; Computes the fluence rate for each cell in a given mesh following the RAD model (Coenen 2013). Parameters [units] ------------------ mesh : obj Mesh object P : int, float Lamp power [W] eff : float Lamp efficiency at 254 nm wavelength L : int, float Length of the reactor/lamp [m] no_abs : bool Flag to enable/disable medium absorption ppm : int, float ppm concentration of a gas [-] Returns [units] --------------- I_i : array Fluence rate for each cell in the mesh [W m**-2] &quot;&quot;&quot; R = mesh.gridCC[:, 0] if no_abs == True: I_i = ((P*eff)/(2*np.pi*R*L)) else: I_i = ((P*eff)/(2*np.pi*R*L))*exp_medium_absorption(R, ppm=ppm) return I_i def per_cell_fluence_rate_LSI(mesh, P, eff, L): &quot;&quot;&quot; Computes the fluence rate for each cell in a given mesh following the LSI model (Blatchley 1998). It assumes no medium absorption Parameters [units] ------------------ mesh : obj Mesh object P : int, float Lamp power [W] eff : float Lamp efficiency at 254 nm wavelength L : int, float Length of the reactor/lamp [m] Returns [units] --------------- I_i : array Fluence rate for each cell in the mesh [W m**-2] &quot;&quot;&quot; R = mesh.gridCC[:, 0] H = mesh.gridCC[:, 2] I_i = ((P*eff)/(4*np.pi*L*R))*(np.arctan((L/2+H)/R)+np.arctan((L/2-H)/R)) return I_i def per_cell_fluence_rate_RAD_LSI(mesh, P, eff, L): &quot;&quot;&quot; Computes the fluence rate for each cell in a given mesh following the RAD-LSI model (Liu 2004). It assumes no medium absorption Parameters [units] ------------------ mesh : obj Mesh object P : int, float Lamp power [W] eff : float Lamp efficiency at 254 nm wavelength L : int, float Length of the reactor/lamp [m] Returns [units] --------------- I_i : array Fluence rate for each cell in the mesh [W m**-2] &quot;&quot;&quot; R = mesh.gridCC[:, 0] H = mesh.gridCC[:, 2] I_i_LSI = ((P*eff)/(4*np.pi*L*R)) * \ (np.arctan((L/2+H)/R)+np.arctan((L/2-H)/R)) I_i_RAD = ((P*eff)/(2*np.pi*R*L)) I_i = np.minimum(I_i_RAD, I_i_LSI) return I_i def per_cell_fluence_rate_MPSS(mesh, P, eff, L, nls, no_abs=False, ppm=300): &quot;&quot;&quot; Computes the fluence rate for each cell in a given mesh following the MPSS model (Bolton 2000). Parameters [units] ------------------ mesh : obj Mesh object P : int, float Lamp power [W] eff : float Lamp efficiency at 254 nm wavelength L : int, float Length of the reactor/lamp [m] nls : int Number of light source elements no_abs : bool Flag to enable/disable medium absorption ppm : int, float ppm concentration of a gas [-] Returns [units] --------------- I_i : array Fluence rate for each cell in the mesh [W m**-2] &quot;&quot;&quot; x_ls = coord_ls(L, nls) R = mesh.gridCC[:, 0] H = mesh.gridCC[:, 2] I_i = np.zeros(len(R)) for i in range(len(R)): r = R[i]*np.ones(len(x_ls)) h = H[i]*np.ones(len(x_ls)) rho = np.sqrt(r**2+(h-x_ls)**2) if no_abs == True: I_ls = (((P*eff)/nls)/(4*np.pi*rho**2)) else: I_ls = (((P*eff)/nls)/(4*np.pi*rho**2)) * \ exp_medium_absorption(r, ppm) I_i[i] = sum(I_ls) return I_i def per_cell_fluence_rate_MSSS(mesh, P, eff, L, nls, no_abs=False, ppm=300): &quot;&quot;&quot; Computes the fluence rate for each cell in a given mesh following the MSSS model (Liu 2004). Parameters [units] ------------------ mesh : obj Mesh object P : int, float Lamp power [W] eff : float Lamp efficiency at 254 nm wavelength L : int, float Length of the reactor/lamp [m] nls : int Number of light source elements no_abs : bool Flag to enable/disable medium absorption ppm : int, float ppm concentration of a gas [-] Returns [units] --------------- I_i : array Fluence rate for each cell in the mesh [W m**-2] &quot;&quot;&quot; x_ls = coord_ls(L, nls) R = mesh.gridCC[:, 0] H = mesh.gridCC[:, 2] I_i = np.zeros(len(R)) for i in range(len(R)): r = R[i]*np.ones(len(x_ls)) h = H[i]*np.ones(len(x_ls)) rho = np.sqrt(r**2+(h-x_ls)**2) if no_abs == True: I_ls = (((P*eff)/nls)/(4*np.pi*rho**2)) else: I_ls = (((P*eff)/nls)/(4*np.pi*rho**2)) * \ exp_medium_absorption(r, ppm) I_ls = I_ls*np.cos(np.arctan(r/h)) I_i[i] = sum(I_ls) return I_i def per_cell_fluence_rate(mesh, P, eff, L, model='RAD', nls=40, ppm=300): &quot;&quot;&quot; Generic function that computes the fluence rate for each cell in a given mesh for various model. Parameters [units] ------------------ mesh : obj Mesh object P : int, float Lamp power [W] eff : float Lamp efficiency at 254 nm wavelength L : int, float Length of the reactor/lamp [m] model : str name of the model ('RAD', 'LSI', 'MPSS', 'MSSS' or 'RAD_LSI') nls : int Number of light source elements ppm : int, float ppm concentration of a gas [-] Returns [units] --------------- I_i : array Fluence rate for each cell in the mesh [W m**-2] &quot;&quot;&quot; if isinstance(model, str) == 0: raise TypeError(&quot;The variable 'model' has to be a string&quot;) if model == 'RAD': I_i = per_cell_fluence_rate_RAD(mesh, P, eff, L, ppm=ppm) elif model == 'LSI': I_i = per_cell_fluence_rate_LSI(mesh, P, eff, L) elif model == 'MPSS': I_i = per_cell_fluence_rate_MPSS(mesh, P, eff, L, nls=nls, ppm=ppm) elif model == 'MSSS': I_i = per_cell_fluence_rate_MSSS(mesh, P, eff, L, nls=nls, ppm=ppm) elif model == 'RAD_LSI': I_i = per_cell_fluence_rate_RAD_LSI(mesh, P, eff, L) else: raise ValueError( &quot;Only 'RAD', 'LSI', 'MPSS', 'MSSS' or 'RAD_LSI' models are implemented&quot;) return I_i def volume_avg_fluence_rate(I_i_outer, mesh_outer, I_i_inner, mesh_inner, V_r): &quot;&quot;&quot; Computes the volume averaged fluence rate (vafr) for the annular reactor (hollow cylinder) by subtracting the average of the small cylinder (_inner) from the large cylinder (_outer). Parameters [units] ------------------ I_i_outer : array Fluence rate for each cell in the outer cylinder mesh [W m**-2] mesh_outer : obj outer cylinder mesh object I_i_inner : array Fluence rate for each cell in the inner cylinder mesh [W m**-2] mesh_inner : obj Inner cylinder mesh object V_r : float The reactor volume [m**2] Returns [units] --------------- I_vol_avg : array Volume average fluence rate for the annular reactor [W m**-2] &quot;&quot;&quot; # volume averaged fluence rate (vafr) I_outer = np.sum(I_i_outer*mesh_outer.vol) I_inner = np.sum(I_i_inner*mesh_inner.vol) return (I_outer - I_inner)/V_r def compute_vafr(case_variables, model='RAD', nls=40, optimize=False, ppm=300): &quot;&quot;&quot; Generic function to compute the volume average fluence rate. Parameters [units] ------------------ case_variables : array Array contining the following case variables: case_variables = [P, L, eff, r_outer, r_inner, ncr, ncz] P = lamp power [W] L = lamp length [m] eff = lamp efficiency at 254 nm wavelength r_outer = reactor radius [m] r_inner = quartz sleeve radius [m] ncr = number of mesh cells in r ncz = number of mesh cells in z model : str name of the model ('RAD', 'LSI', 'MPSS', 'MSSS' or 'RAD_LSI') nls : int Number of light source elements no_abs : bool Flag to enable/disable nls optimization for the MPSS or MSSS models ppm : int, float ppm concentration of a gas [-] Returns [units] --------------- I_vol_avg : array Volume average fluence rate for the annular reactor [W m**-2] &quot;&quot;&quot; # Unpack the case variables P, eff, L, r_outer, r_inner, ncr, ncz = case_variables # Compute reactor volume V_r = reactor_volume(L, r_outer, r_inner) # Make the outer and inner mesh objects mesh_outer = make_cyl_mesh(L, r_outer, ncr, ncz) mesh_inner = make_cyl_mesh(L, r_inner, ncr, ncz) # Find optimum nls if required if (model == 'MPSS' or model == 'MSSS') and optimize == True: nls = optimize_nls(case_variables, tol=1E-2) # Calculate the per-cell fluence rate for the inner and outer meshes I_i_outer = per_cell_fluence_rate( mesh_outer, P, eff, L, model=model, nls=nls, ppm=ppm) I_i_inner = per_cell_fluence_rate( mesh_inner, P, eff, L, model=model, nls=nls, ppm=ppm) # Compute volume average LSI fluence rate I_vol_avg = volume_avg_fluence_rate( I_i_outer, mesh_outer, I_i_inner, mesh_inner, V_r) return I_vol_avg def set_gas(mechanism, T, P, C): &quot;&quot;&quot; Define the properties of the cantera gas object. Parameters [units] ------------------ mechanism : string Path to the CTI mechanism to be used T : int, float Temperature [K] P : int, float Pressure [in atm] C : dict Dictionary containing the concentrations of the different gas species [molar fraction] Returns [units] --------------- gas : obj cantera gas object &quot;&quot;&quot; gas = ct.Solution('data/photolysis.cti') gas.TPX = T, P, C return gas def set_reactor(gas, V_r, residence_t, p_valve_coeff): &quot;&quot;&quot; Set-up the reactor network using Cantera functions and syntax. Parameters [units] ------------------ gas : obj Cantera gas object V_r : float The reactor volume [m**2] residence_t : int, float Time that the gas will stay in the reactor [s] p_valve_coeff : int, float This is the &quot;conductance&quot; of the pressure valve and will determine its efficiency in holding the reactor pressure to the desired conditions. Set to 0.01 for default Returns [units] --------------- stirred_reactor : obj Cantera reactor object reactor_network : obj Cantera network object &quot;&quot;&quot; fuel_air_mixture_tank = ct.Reservoir(gas) exhaust = ct.Reservoir(gas) stirred_reactor = ct.IdealGasReactor(gas, energy='off', volume=V_r) mass_flow_controller = ct.MassFlowController( upstream=fuel_air_mixture_tank, downstream=stirred_reactor, mdot=stirred_reactor.mass/residence_t) pressure_regulator = ct.Valve( upstream=stirred_reactor, downstream=exhaust, K=p_valve_coeff) reactor_network = ct.ReactorNet([stirred_reactor]) return [stirred_reactor, reactor_network] def intialize_results(stirred_reactor): &quot;&quot;&quot; Initializes the DataFrame where results will be stored. Parameters [units] ------------------ stirred_reactor : obj Cantera reactor object Returns [units] --------------- time_history : DataFrame Pandas DataFrame to store time evolution of reasults. It includes the gas's mass, volume, temperature and species concentration &quot;&quot;&quot; column_names = [stirred_reactor.component_name( item) for item in range(stirred_reactor.n_vars)] time_history = pd.DataFrame(columns=column_names) return time_history def update_results(time_history, stirred_reactor, t): &quot;&quot;&quot; Updates the results at a given time instant. Parameters [units] ------------------ time_history : DataFrame Pandas DataFrame to store time evolution of reasults. It includes the gas's mass, volume, temperature and species concentration stirred_reactor : obj Cantera reactor object t : int, float Current simulation time [s] Returns [units] --------------- time_history : DataFrame Pandas DataFrame to store time evolution of reasults. It includes the gas's mass, volume, temperature and species concentration &quot;&quot;&quot; state = np.hstack([stirred_reactor.mass, stirred_reactor.volume, stirred_reactor.T, stirred_reactor.thermo.X]) time_history.loc[t] = state return time_history def uv_update_reactions(stirred_reactor, case_variables, model='RAD', nls=40): &quot;&quot;&quot; Modifies the rate constant of the photolysis reaction of ozone. This has to be done for each loop iteration as the concentrations of the different gas species are changing, which will affect the absorption of the medium. Parameters [units] ------------------ stirred_reactor : obj Cantera reactor object case_variables : array Array contining the following case variables: case_variables = [P, L, eff, r_outer, r_inner, ncr, ncz] P = lamp power [W] L = lamp length [m] eff = lamp efficiency at 254 nm wavelength r_outer = reactor radius [m] r_inner = quartz sleeve radius [m] ncr = number of mesh cells in r ncz = number of mesh cells in z model : str name of the model ('RAD', 'LSI', 'MPSS', 'MSSS' or 'RAD_LSI') nls : int Number of light source elements Returns [units] --------------- None &quot;&quot;&quot; ppm = stirred_reactor.thermo.X[stirred_reactor.component_index( 'SO2')-3]*1e6 k_uv = (0.9) * ((254E-9)/(N_A*h*c)) * (np.log(10)) * sigma_to_eps(1.132935E-17) * \ compute_vafr(case_variables, model=model, nls=nls, ppm=ppm) ID = np.size(gas.reactions())-1 reaction = gas.reactions()[ID] reaction.rate = ct.Arrhenius(A=k_uv, b=0, E=0) gas.modify_reaction(ID, reaction) return None def time_loop(reactor_network, stirred_reactor, case_variables, time_history, max_simulation_t, model='RAD'): &quot;&quot;&quot; Computes the time loop iterations for the chemical reactor until the maximum simulation time is reached. Parameters [units] ------------------ stirred_reactor : obj Cantera reactor object reactor_network : obj Cantera network object case_variables : array Array contining the following case variables: case_variables = [P, L, eff, r_outer, r_inner, ncr, ncz] P = lamp power [W] L = lamp length [m] eff = lamp efficiency at 254 nm wavelength r_outer = reactor radius [m] r_inner = quartz sleeve radius [m] ncr = number of mesh cells in r ncz = number of mesh cells in z time_history : DataFrame Pandas DataFrame to store time evolution of reasults. It includes the gas's mass, volume, temperature and species concentration max_simulation_t : int Maximum simulation time [s] model : str name of the model ('RAD', 'LSI', 'MPSS', 'MSSS' or 'RAD_LSI') Returns [units] --------------- time_history : DataFrame Pandas DataFrame to store time evolution of reasults. It includes the gas's mass, volume, temperature and species concentration &quot;&quot;&quot; counter, t = 1, 0 while t &lt; max_simulation_t: if (t == 0) or (counter % 10 == 0): # Update every 10 iterations if (model == 'MPSS') or (model == 'MSSS'): if t == 0: nls = optimize_nls(case_variables, tol=1E-2) uv_update_reactions( stirred_reactor, case_variables, model=model, nls=nls) else: uv_update_reactions(stirred_reactor, case_variables, model=model) time_history = update_results(time_history, stirred_reactor, t) t = reactor_network.step() counter += 1 return time_history def run_simulation(gas, V_r, residence_t, p_valve_coeff, case_variables, max_simulation_t, model='RAD'): &quot;&quot;&quot; Generic function to run the chemical reactor with UV light modeling. Parameters [units] ------------------ gas : obj Cantera gas object V_r : float The reactor volume [m**2] residence_t : int, float Time that the gas will stay in the reactor [s] p_valve_coeff : int, float This is the &quot;conductance&quot; of the pressure valve and will determine its efficiency in holding the reactor pressure to the desired conditions. Set to 0.01 for default case_variables : array Array contining the following case variables: case_variables = [P, L, eff, r_outer, r_inner, ncr, ncz] P = lamp power [W] L = lamp length [m] eff = lamp efficiency at 254 nm wavelength r_outer = reactor radius [m] r_inner = quartz sleeve radius [m] ncr = number of mesh cells in r ncz = number of mesh cells in z max_simulation_t : int Maximum simulation time [s] model : str name of the model ('RAD', 'LSI', 'MPSS', 'MSSS' or 'RAD_LSI') Returns [units] --------------- time_history : DataFrame Pandas DataFrame to store time evolution of reasults. It includes the gas's mass, volume, temperature and species concentration &quot;&quot;&quot; # Define the reactor object [stirred_reactor, reactor_network] = set_reactor( gas, V_r, residence_t, p_valve_coeff) # Initialize the results dataFrame time_history = intialize_results(stirred_reactor) # Run the time loop time_history = time_loop(reactor_network, stirred_reactor, case_variables, time_history, max_simulation_t, model=model) return time_history def plot_results(specie, log=False): &quot;&quot;&quot; Plots the results from the reactor simulation. Parameters [units] ------------------ specie : str Specie for which to plot the time evolution log : bool Flag to enable/disable the x axis as logarithmic Returns [units] --------------- None &quot;&quot;&quot; plt.style.use('ggplot') plt.style.use('seaborn-pastel') plt.rcParams['axes.labelsize'] = 18 plt.rcParams['xtick.labelsize'] = 14 plt.rcParams['ytick.labelsize'] = 14 plt.rcParams['figure.autolayout'] = True plt.figure() if log == True: plt.semilogx(time_history.index, time_history[specie]*1e6, '-') else: plt.plot(time_history.index, time_history[specie]*1e6, '-') plt.xlabel('Time (s)') plt.ylabel(re.sub(r&quot;([0-9]+(\.[0-9]+)?)&quot;, r&quot;_\1&quot;, '$'+specie+'$' + r' Mole Fraction : $ppmv$')) plt.show() return None if __name__ == &quot;__main__&quot;: start = time.time() print('Defining the gas properties') gas = set_gas('photolysis.cti', 295, ct.one_atm, {'N2': 0.78014, 'O2': 0.20946, 'O3': 0.0001, 'SO2': 0.0003, 'H2O': 0.01}) print('Defining the geometry variables') case_variables = P, eff, L, r_outer, r_inner, ncr, ncz = [ 17, 0.33, 0.28, 0.0425, 0.0115, 20, 20] V_r = reactor_volume(L, r_outer, r_inner) print('Defining the simulation variables') p_valve_coeff, max_p_rise, residence_t, max_simulation_t = 0.01, 0.01, 10, 100 print('Running the simulation') time_history = run_simulation(gas, V_r, residence_t, p_valve_coeff, case_variables, max_simulation_t, model='RAD') end = time.time() print('Plotting the simulation results') plot_results('SO2', log=True) print(f'Elapsed time: {end - start:.3f}s') </code></pre> <h2>Kinetic mechanism</h2> <p>If you wish to run the code you will require the kinetic mechanism. Save it as photolysis.cti:</p> <pre class="lang-py prettyprint-override"><code>&quot;&quot;&quot; -----------------------------------------------------------------------| | Photolysis mechanism | | -----------------------------------------------------------------------| &quot;&quot;&quot; units(length='cm', time='s', quantity='molec', act_energy='K') ideal_gas(name='gas', elements=&quot;O H N S&quot;, species=&quot;&quot;&quot;O O(1D) O2 O3 H2O HO2 OH N2 SO2 SO3 HSO3 H2SO4 H&quot;&quot;&quot;, reactions='all', initial_state=state(temperature=300.0, pressure=OneAtm)) #------------------------------------------------------------------------------- # Species data #------------------------------------------------------------------------------- species(name='O', atoms='O:1', thermo=(NASA([200.00, 1000.00], [ 2.94642900E+00, -1.63816600E-03, 2.42103200E-06, -1.60284300E-09, 3.89069600E-13, 2.91476400E+04, 2.96399500E+00]), NASA([1000.00, 5000.00], [ 2.54206000E+00, -2.75506200E-05, -3.10280300E-09, 4.55106700E-12, -4.36805200E-16, 2.92308000E+04, 4.92030800E+00])), note='120186') species(name='O(1D)', atoms='O:1', thermo=(NASA([200.00, 1000.00], [ 2.49993786E+00, 1.71935346E-07, -3.45215267E-10, 3.71342028E-13, -1.70964494E-16, 5.19965317E+04, 4.61684555E+00]), NASA([1000.00, 6000.00], [ 2.49368475E+00, 1.37617903E-05, -1.00401058E-08, 2.76012182E-12, -2.01597513E-16, 5.19986304E+04, 4.65050950E+00])), note='121286') species(name='O2', atoms='O:2', thermo=(NASA([200.00, 1000.00], [ 3.21293600E+00, 1.12748600E-03, -5.75615000E-07, 1.31387700E-09, -8.76855400E-13, -1.00524900E+03, 6.03473800E+00]), NASA([1000.00, 5000.00], [ 3.69757800E+00, 6.13519700E-04, -1.25884200E-07, 1.77528100E-11, -1.13643500E-15, -1.23393000E+03, 3.18916600E+00])), note='121386') species(name='O3', atoms='O:3', thermo=(NASA([200.00, 1000.00], [ 2.46260900E+00, 9.58278100E-03, -7.08735900E-06, 1.36336800E-09, 2.96964700E-13, 1.60615200E+04, 1.21418700E+01]), NASA([1000.00, 5000.00], [ 5.42937100E+00, 1.82038000E-03, -7.70560700E-07, 1.49929300E-10, -1.07556300E-14, 1.52352700E+04, -3.26638700E+00])), note='121286') species(name='H2O', atoms='H:2 O:1', thermo=(NASA([200.00, 1000.00], [ 3.38684200E+00, 3.47498200E-03, -6.35469600E-06, 6.96858100E-09, -2.50658800E-12, -3.02081100E+04, 2.59023300E+00]), NASA([1000.00, 5000.00], [ 2.67214600E+00, 3.05629300E-03, -8.73026000E-07, 1.20099600E-10, -6.39161800E-15, -2.98992100E+04, 6.86281700E+00])), note='20387') species(name='HO2', atoms='H:1 O:2', thermo=(NASA([200.00, 1000.00], [ 2.97996300E+00, 4.99669700E-03, -3.79099700E-06, 2.35419200E-09, -8.08902400E-13, 1.76227400E+02, 9.22272400E+00]), NASA([1000.00, 5000.00], [ 4.07219100E+00, 2.13129600E-03, -5.30814500E-07, 6.11226900E-11, -2.84116500E-15, -1.57972700E+02, 3.47602900E+00])), note='20387') species(name='OH', atoms='H:1 O:1', thermo=(NASA([200.00, 1000.00], [ 3.63726600E+00, 1.85091000E-04, -1.67616500E-06, 2.38720300E-09, -8.43144200E-13, 3.60678200E+03, 1.35886000E+00]), NASA([1000.00, 5000.00], [ 2.88273000E+00, 1.01397400E-03, -2.27687700E-07, 2.17468400E-11, -5.12630500E-16, 3.88688800E+03, 5.59571200E+00])), note='121286') species(name='N2', atoms='N:2', thermo=(NASA([100.00, 1000.00], [ 3.29867700E+00, 1.40824000E-03, -3.96322200E-06, 5.64151500E-09, -2.44485500E-12, -1.02090000E+03, 3.95037200E+00]), NASA([1000.00, 5000.00], [ 2.92664000E+00, 1.48797700E-03, -5.68476100E-07, 1.00970400E-10, -6.75335100E-15, -9.22797700E+02, 5.98052800E+00])), note='121286') species(name='SO2', atoms='O:2 S:1', thermo=(NASA([200.00, 1000.00], [ 2.91143900E+00, 8.10302200E-03, -6.90671000E-06, 3.32901600E-09, -8.77712100E-13, -3.68788200E+04, 1.11174000E+01]), NASA([1000.00, 5000.00], [ 5.25449800E+00, 1.97854500E-03, -8.20422600E-07, 1.57638300E-10, -1.12045100E-14, -3.75688600E+04, -1.14605600E+00])), note='121286') species(name='SO3', atoms='O:3 S:1', thermo=(NASA([200.00, 1000.00], [ 2.57528300E+00, 1.51509200E-02, -1.22987200E-05, 4.24025700E-09, -5.26681200E-13, -4.89441100E+04, 1.21951200E+01]), NASA([1000.00, 5000.00], [ 7.05066800E+00, 3.24656000E-03, -1.40889700E-06, 2.72153500E-10, -1.94236500E-14, -5.02066800E+04, -1.10644300E+01])), note='121286') species(name='HSO3', atoms='H:1 O:3 S:1', thermo=(NASA([200.00, 1000.00], [ 3.18471474E+00, 1.92277645E-02, -1.85975873E-05, 7.95502482E-09, -9.42254910E-13, -4.42156599E+04, 1.30496771E+01]), NASA([1000.00, 6000.00], [ 8.19420431E+00, 3.77828016E-03, -1.34903219E-06, 2.17197023E-10, -1.29874848E-14, -4.55013223E+04, -1.23824851E+01])), note='HO-SO2T10/10') species(name='H2SO4', atoms='H:2 O:4 S:1', thermo=(NASA([200.00, 1000.00], [ 4.53388173E+00, 3.10347679E-02, -4.10421795E-05, 2.95752341E-08, -8.81459071E-12, -9.05459072E+04, 3.93961412E+00]), NASA([1000.00, 6000.00], [ 1.13355392E+01, 5.60829109E-03, -1.94574192E-06, 3.07136054E-10, -1.81109544E-14, -9.21087435E+04, -2.96094003E+01])), note='T8/03') species(name='H', atoms='H:1', thermo=(NASA([200.00, 1000.00], [ 2.50000000E+00, 0.00000000E+00, 0.00000000E+00, 0.00000000E+00, 0.00000000E+00, 2.54716300E+04, -4.60117600E-01]), NASA([1000.00, 5000.00], [ 2.50000000E+00, 0.00000000E+00, 0.00000000E+00, 0.00000000E+00, 0.00000000E+00, 2.54716300E+04, -4.60117600E-01])), note='120186') #------------------------------------------------------------------------------- # Reaction data #------------------------------------------------------------------------------- # Reaction 1 reaction('O + O3 =&gt; 2 O2', [8.000000e+12, 0.0, 2060.0]) # Reaction 2 reaction('O(1D) + H2O =&gt; 2 OH', [1.630000e+10, 0.0, 65.0]) # Reaction 3 reaction('O + OH =&gt; O2 + H', [2.400000e+11, 0.0, 110.0]) # Reaction 4 reaction('O + HO2 =&gt; OH + O2', [2.700000e+11, 0.0, 224.0]) # Reaction 5 three_body_reaction('H + O2 + M =&gt; HO2 + M', [2.170000e+29, 1.1, 0.0]) # Reaction 6 reaction('OH + O3 =&gt; HO2 + O2', [1.700000e+12, 0.0, 940.0]) # Reaction 7 reaction('OH + HO2 =&gt; H2O + O2', [4.800000e+11, 0.0, 250.0]) # Reaction 8 reaction('OH + SO2 =&gt; HSO3', [7.070000e+11, 0.7, 0.0]) # Reaction 9 three_body_reaction('O + SO2 + M =&gt; SO3 + M', [4.000000e+32, 0.0, 1000.0]) # Reaction 10 reaction('SO3 + H2O =&gt; H2SO4', [1.200000e+15, 0.0, 0.0]) # Reaction 11 reaction('HSO3 + O2 =&gt; HO2 + SO3', [1.300000e+12, 0.0, 330.0]) #------------------------------------------------------------------------------- # Photolysis reaction #------------------------------------------------------------------------------- # Reaction 12 reaction('O3 =&gt; O(1D) + O2', [1.000000e+00, 0.0, 0.0]) </code></pre>
[]
[ { "body": "<h2>Overall</h2>\n<p>This code is fairly well-structured and very well-documented. Excellent job.</p>\n<h2>Type hints</h2>\n<p>It's good that you specified types here:</p>\n<pre><code> L : int, float\n Length of the reactor/lamp [m]\n r_outer : int, float\n Outer radius [m]\n r_outer : int, float\n</code></pre>\n<p>Better would be to codify these in type hints:</p>\n<pre><code>def reactor_volume(\n L: Union[int, float], \n r_outer: Union[int, float], \n r_inner: Union[int, float],\n) -&gt; float:\n</code></pre>\n<p>Some alternatives to the union are explained here:</p>\n<p><a href=\"https://stackoverflow.com/questions/50928592/mypy-type-hint-unionfloat-int-is-there-a-number-type\">https://stackoverflow.com/questions/50928592/mypy-type-hint-unionfloat-int-is-there-a-number-type</a></p>\n<h2>Order of operations</h2>\n<pre><code>(sigma*N_A)/(1e4*np.log(10))\n</code></pre>\n<p>can be</p>\n<pre><code>sigma * N_A * 1e-4 / np.log(10)\n</code></pre>\n<h2>Simplification</h2>\n<p>The <code>exp</code> will cancel out the <code>log</code> here:</p>\n<pre><code>np.exp(-np.log(10)*eps_air*C_air*r)\n</code></pre>\n<p>to become</p>\n<pre><code>np.power(10, -eps_air*C_air*r)\n</code></pre>\n<h2>Boolean comparison</h2>\n<p><code>if no_abs == True</code> should simply be <code>if no_abs</code>.</p>\n<h2>Enums</h2>\n<p><code>model</code> should capture <code>RAD</code>, <code>LSI</code> etc. in an <code>Enum</code>.</p>\n<h2><code>set_reactor</code> return value</h2>\n<p>You're forming a list, which is a little odd. Typically, multi-return values are implicit tuples, i.e.</p>\n<pre><code>return stirred_reactor, reactor_network\n</code></pre>\n<h2>Spelling</h2>\n<p><code>reasults</code> -&gt; <code>results</code></p>\n<h2>Redundant return</h2>\n<pre><code>return None\n</code></pre>\n<p>can be deleted; that's what happens by default.</p>\n<h2>Dictionary update</h2>\n<pre><code>plt.rcParams['axes.labelsize'] = 18\nplt.rcParams['xtick.labelsize'] = 14\nplt.rcParams['ytick.labelsize'] = 14\nplt.rcParams['figure.autolayout'] = True\n</code></pre>\n<p>should use</p>\n<pre><code>plt.rcParams.update({ ...\n</code></pre>\n<h2>Graph bounds</h2>\n<p>The lower bound for your time axis should be 1e-3 or maybe 1e-2. Remove the long, flat part to focus on the interesting bits.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T08:41:41.260", "Id": "481208", "Score": "0", "body": "Thanks got the feedback! I'll apply all the changes but I just wanted some clarification on the Enums. You are suggesting to make a model a class and then use the Enum package to define the different models within the class, right? I don't have much experience with OOP programming, could you give me a pointer to a good resource that I can use as an example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-06T12:54:08.973", "Id": "481231", "Score": "0", "body": "https://docs.python.org/3/library/enum.html has good examples and is the only \"authoritative source\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T13:54:19.343", "Id": "245036", "ParentId": "244935", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T10:52:05.943", "Id": "244935", "Score": "6", "Tags": [ "python", "performance", "beginner", "object-oriented" ], "Title": "Chemical reactor with UV light project in python" }
244935
<p>The code below solves the following task</p> <blockquote> <p>Find the maximum price change over any 1 to 5 day rolling window, over a 1000 day period.</p> </blockquote> <p>To be clear &quot;any 1 to 5 day rolling window&quot; means <code>t[i:i + j]</code> where <code>j</code> can range from 1 to 5. Rather than <code>t[i:i + 5]</code> if it were just &quot;any 5 day rolling window&quot;.</p> <p>I used NumPy native functions to do this. But I've used a for-loop for the inner iteration.</p> <pre><code>import numpy as np import numpy.random as npr prices = npr.random([1000,1])*1000 max_array = np.zeros([(prices.size-5),1]) for index, elem in np.ndenumerate(prices[:-5,:]): local_max = 0.0 for i in range(1,6,1): price_return = prices[(index[0] + i),0] / elem local_max = max(local_max, price_return) max_array[index[0]] = local_max global_max = np.amax(max_array) </code></pre> <p>Can I somehow eliminate the inner for loop and use NumPy vectorization instead?</p> <p>I also don't particularly like using &quot;index[0]&quot; to extract the actual index of the current loop from the tuple object that is returned into the variable &quot;index&quot; via the call:</p> <blockquote> <pre><code>for index, elem in np.ndenumerate(prices[:-5,:]): </code></pre> </blockquote>
[]
[ { "body": "<p>A first pass will see (as Vishesh suggests) collapsing one dimension, and properly unpacking the index tuple:</p>\n<pre><code>import numpy as np\n\n# Window size\nW = 5\n\nprices = np.arange(1, 10) # npr.random([1000,1])*1000\n\nmax_array = np.zeros(prices.size-W)\nfor (index,), elem in np.ndenumerate(prices[:-W]):\n local_max = 0\n for i in range(1, W+1):\n price_return = prices[index + i] / elem\n local_max = max(local_max, price_return)\n max_array[index] = local_max\nglobal_max = np.amax(max_array)\n</code></pre>\n<p>I've also replaced your random array with a simple one so that this is repeatable and verifiable. You should make your window size parametric or at least configurable via constant.</p>\n<p>Unfortunately, none of the native Numpy options are great. Your best bet is to use Pandas:</p>\n<pre><code>import numpy as np\nimport pandas as pd\n\n# Window size\nW = 5\n\nrolled = (\n pd.Series(prices)\n .rolling(window=W)\n .min()\n .to_numpy()\n)\nmax_array = prices[1-W:] / rolled[W-1:-1]\n</code></pre>\n<p>I have tested this to be equivalent. Note that you need to start with a rolling <em>minimum</em> in the denominator to get a maximum numerator.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T17:03:05.177", "Id": "481131", "Score": "0", "body": "Thank you so much for the input. I've found your answer very useful, in addition to the answer given by Peilonrayz. Specifically, I like how you unpack the tuple instead of using index[0]. You are correct that Pandas would be very suitable for this task. It's good to have all these options." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T16:07:21.180", "Id": "244950", "ParentId": "244936", "Score": "5" } }, { "body": "<p><strong>This line is equivalent to your code which you were likely trying to make and using 2d array for</strong></p>\n<pre><code> np.max(\n prices[np.arange(0, len(prices) - 5).reshape(-1, 1) + np.arange(1, 6)].squeeze()\n / prices[np.arange(0, len(prices) - 5)]\n)\n</code></pre>\n<p>Hmm, it's not easy to understand. Let's break it into chunks.</p>\n<pre><code>np.arange(0, len(prices) - 5).reshape(-1, 1) \n</code></pre>\n<p>gives</p>\n<pre><code>array([[ 0],\n [ 1],\n [ 2],\n [ 3],\n .....\n .....\n [ 994]])\n</code></pre>\n<p>Next, here, something called as &quot;broadcasting&quot; is taking place.</p>\n<pre><code>np.arange(0, len(prices) - 5).reshape(-1, 1) + np.arange(1, 6)\n</code></pre>\n<p>gives</p>\n<pre><code>array([[ 1, 2, 3, 4, 5],\n [ 2, 3, 4, 5, 6],\n [ 3, 4, 5, 6, 7],\n ...,\n [993, 994, 995, 996, 997],\n [994, 995, 996, 997, 998],\n [995, 996, 997, 998, 999]])\n</code></pre>\n<p>After getting the right index we take the prices at those indices, but it will return a 3d matrix. Therefore we use &quot;squeeze&quot; to remove one of the dimensions.</p>\n<pre><code>prices[np.arange(0, len(prices) - 5).reshape(-1, 1) + np.arange(1, 6)].squeeze()\n</code></pre>\n<p>Finally we use vector division and return the maximum of the matrix.</p>\n<p><strong>Alternate method:</strong>\nWell numpy is good but this broadcasting and some stuff is often unclear to me and always keeps me in the dilemma if my matrices are being multiplied right.Sure I can use assert but there's a Python package &quot;Numba&quot; which optimizes your Python code.You should definitely check it out.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T16:58:37.900", "Id": "480958", "Score": "1", "body": "Thanks for the question. I refreshed my numpy skills after a long time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T17:43:27.290", "Id": "480974", "Score": "0", "body": "Your formatting is not great, your for loop isn't inline with anything, and your code seems to not follow PEP 8 or any other style guide at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T17:45:00.373", "Id": "480976", "Score": "0", "body": "sorry,I had used jupyter notebook for this. Editing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T17:46:12.390", "Id": "480977", "Score": "0", "body": "Additionally this doesn't vectorize the larger loop." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T16:52:17.130", "Id": "244953", "ParentId": "244936", "Score": "2" } }, { "body": "<ol>\n<li>Put this in a function.</li>\n<li>Make the input a 1d array.</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def maximum(prices):\n max_array = np.zeros(prices.size - 5)\n for index, elem in np.ndenumerate(prices[:-5]):\n local_max = 0.0\n for i in range(1,6,1):\n price_return = prices[index[0] + i] / elem\n local_max = max(local_max, price_return)\n max_array[index] = local_max\n return np.amax(max_array)\n</code></pre>\n<ol start=\"3\">\n<li>Flip the enumeration around.</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def maximum(prices):\n max_array = np.zeros(5)\n for i in range(1, 6):\n local_max = 0.0\n for index, elem in np.ndenumerate(prices[:-5]):\n price_return = prices[index[0] + i] / elem\n local_max = max(local_max, price_return)\n max_array[i - 1,] = local_max\n return np.amax(max_array)\n</code></pre>\n<ol start=\"4\">\n<li>Use numpy to slice the array. And then use <code>.max</code>.</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def maximum(prices):\n size, = prices.shape\n size -= 4\n max_array = np.zeros(5)\n for i in range(5):\n max_array[i,] = (prices[i:size + i] / prices[:size]).max()\n return np.amax(max_array)\n</code></pre>\n<ol start=\"5\">\n<li>Use <code>max</code> and a comprehension.</li>\n</ol>\n<p>Now the inner loop is vectorized and it's a lot easier to see what it's doing.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def maximum(prices, windows=5):\n size, = prices.shape\n size -= windows - 1\n return max(\n (prices[i:size + i] / prices[:size]).max()\n for i in range(windows)\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T17:01:37.243", "Id": "481130", "Score": "0", "body": "Those are some pretty epic refinements. Obviously, there is a steep learning curve to go through to reach that level of brevity in Python coding. Thank you so much for your inputs!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T17:37:04.843", "Id": "244963", "ParentId": "244936", "Score": "3" } } ]
{ "AcceptedAnswerId": "244963", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T11:17:41.493", "Id": "244936", "Score": "7", "Tags": [ "python", "numpy" ], "Title": "Find the maximum price change over any 1 to 5 day rolling window" }
244936
<h1>JsonStatus</h1> <p>(as in status file)</p> <h2>Goal</h2> <p>A simple and fast JSON writer in C++ (JSON output only). When you need something so small that you're not sure you even <em>need</em> a JSON library and you don't feel like adding lots of code into your project but you also want something to take care of the commas, colons and braces for you.</p> <h2>Properties</h2> <p>Minimum verification and assumes that data is added in-order.</p> <p>Doesn't protect against duplicate keys and values can't be modified, only written once.</p> <p>Writes directly to a file.</p> <h2>Code</h2> <h3>Usage example</h3> <pre><code> JsonStatus jst; jst.setFileName(&quot;aaa.json&quot;); jst.initArray(); jst.pushVal(1); jst.pushVal(2); jst.objectInArray(); jst.pushKeyArray(&quot;arr&quot;); jst.pushVal(3); jst.pushVal(4); jst.close(); // pops all nested //Output: [1, 2, {&quot;arr&quot; : [3, 4]}] jst.setFileName(&quot;bbb.json&quot;); jst.initObject(); jst.pushKeyArray(&quot;arr&quot;); jst.pushVal(1); jst.pushVal(2); jst.popNested(); // End arr jst.pushKeyVal(&quot;keyA&quot;, 3); jst.pushKeyObject(&quot;othertypes&quot;); jst.pushKeyVal(&quot;keyB&quot;, 4.001); jst.pushKeyObject(&quot;strings&quot;); jst.pushKeyVal(&quot;keyC&quot;, &quot;5&quot;); jst.pushKeyVal(&quot;keyD&quot;, std::string(&quot;5&quot;) + &quot;+1&quot;); jst.popNested(); // End strings jst.pushKeyVal(&quot;keyE&quot;, 'E'); jst.close(); // pops all nested //Output: {&quot;arr&quot; : [1, 2], &quot;keyA&quot; : 3, &quot;othertypes&quot; : {&quot;keyB&quot; : 4.001, &quot;strings&quot; : {&quot;keyC&quot; : &quot;5&quot;, &quot;keyD&quot; : &quot;5+1&quot;}, &quot;keyE&quot; : &quot;E&quot;}} </code></pre> <h3>Header file</h3> <pre><code>#ifndef JSONSTATUS_H_ #define JSONSTATUS_H_ #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;stack&gt; #include &lt;stdexcept&gt; class JsonStatus { public: void setFileName(const std::string&amp; fileName); void initObject(); void initArray(); void close(); void pushKeyVal(const std::string&amp; key, const std::string&amp; val); void pushKeyVal(const std::string&amp; key, const char* val); void pushKeyVal(const std::string&amp; key, char val); template &lt;class T&gt; void pushKeyVal(const std::string&amp; key, const T&amp; val) { pushKey(key); jsonString &lt;&lt; val; } // adding elements to a JSON array void pushVal(const std::string&amp; val); void pushVal(const char* val); void pushVal(char val); template &lt;class T&gt; void pushVal(const T&amp; val) { arrayState(); jsonString &lt;&lt; val; } // Nested arrays and objects void objectInArray(); void pushKeyArray(const std::string&amp;); void pushKeyObject(const std::string&amp;); void popNested(); void popAllNested(); private: void pushKey(const std::string&amp; key); void arrayState(); void writeStringInQuotes(const char* str); void writeCharInQuotes(char c); enum class Nested { Object, Array }; std::string fileName; std::ofstream jsonString; struct level { Nested nested; int count = 0; }; std::stack&lt;level&gt; currentLevel; }; #endif /* JSONSTATUS_H_ */ </code></pre> <h3>Implementation file</h3> <pre><code> #include &quot;JsonStatus.h&quot; void JsonStatus::setFileName(const std::string&amp; fileNameArg) { fileName = fileNameArg; } void JsonStatus::pushKeyVal(const std::string &amp;key, const std::string &amp;val) { pushKeyVal(key, val.c_str()); } void JsonStatus::pushKeyVal(const std::string &amp;key, const char *val) { pushKey(key); writeStringInQuotes(val); } void JsonStatus::pushKeyVal(const std::string&amp; key, char val) { pushKey(key); writeCharInQuotes(val); } void JsonStatus::pushVal(const std::string&amp; val) { pushVal(val.c_str()); } void JsonStatus::pushVal(const char* val) { arrayState(); writeStringInQuotes(val); } void JsonStatus::pushVal(char val) { arrayState(); writeCharInQuotes(val); } void JsonStatus::objectInArray() { arrayState(); jsonString &lt;&lt; '{'; currentLevel.push(level{ Nested::Object }); } void JsonStatus::pushKey(const std::string &amp;key) { if (currentLevel.empty()) throw std::runtime_error(&quot;JsonStatus was not initialized&quot;); if (currentLevel.top().nested != Nested::Object) throw std::runtime_error(&quot;Pushed a key to an array&quot;); if (currentLevel.top().count) jsonString &lt;&lt; &quot;, &quot;; writeStringInQuotes(key.c_str()); jsonString &lt;&lt; &quot; : &quot;; ++currentLevel.top().count; } void JsonStatus::arrayState() { if (currentLevel.empty()) throw std::runtime_error(&quot;JsonStatus was not initialized&quot;); if (currentLevel.top().nested != Nested::Array) throw std::runtime_error(&quot;Pushed a value without key to an object&quot;); if (currentLevel.top().count) jsonString &lt;&lt; &quot;, &quot;; ++currentLevel.top().count; } void JsonStatus::pushKeyArray(const std::string &amp;key) { pushKey(key); jsonString &lt;&lt; '['; currentLevel.push(level{ Nested::Array }); } void JsonStatus::pushKeyObject(const std::string &amp;key) { pushKey(key); jsonString &lt;&lt; '{'; currentLevel.push(level{ Nested::Object }); } void JsonStatus::popNested() { if (currentLevel.empty()) throw std::runtime_error(&quot;JsonStatus was not initialized&quot;); if (currentLevel.top().nested == Nested::Array) jsonString &lt;&lt; ']'; else if (currentLevel.top().nested == Nested::Object) jsonString &lt;&lt; '}'; currentLevel.pop(); } void JsonStatus::initObject() { jsonString.open(fileName); if (jsonString.is_open() == false || jsonString.good() == false) throw std::runtime_error(&quot;Could not open JSON path for writing&quot;); while (!currentLevel.empty()) currentLevel.pop(); jsonString &lt;&lt; '{'; currentLevel.push(level{ Nested::Object }); } void JsonStatus::initArray() { jsonString.open(fileName); if (jsonString.is_open() == false || jsonString.good() == false) throw std::runtime_error(&quot;Could not open JSON path for writing&quot;); while (!currentLevel.empty()) currentLevel.pop(); jsonString &lt;&lt; '['; currentLevel.push(level{ Nested::Array }); } void JsonStatus::popAllNested() { while (!currentLevel.empty()) popNested(); } void JsonStatus::close() { popAllNested(); jsonString.close(); } void JsonStatus::writeStringInQuotes(const char* str) { // if you're feeling fancy, escape special characters, not doing it for now. jsonString &lt;&lt; '&quot;'; jsonString &lt;&lt; str; jsonString &lt;&lt; '&quot;'; } void JsonStatus::writeCharInQuotes(char c) { char str[] = { c,'\0' }; writeStringInQuotes(str); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T11:52:17.033", "Id": "244937", "Score": "4", "Tags": [ "c++", "json" ], "Title": "JsonStatus - A tiny C++ JSON writer" }
244937
<p>I'm trying to build a simple (yet effective) brute-force protection for my App-API.</p> <p>The client requests an identity - the server supplies a random string (called <code>seed</code>, which it remembers via PHP session) and a security level.</p> <p>If the client wants to login it needs to supply a suffix for the <code>seed</code> which results in a <code>SHA512</code> hash with leading zero-bytes (security level times).</p> <p><strong>Java (generation):</strong></p> <pre class="lang-java prettyprint-override"><code>import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class HashCash { private final static String HASH_ALGORITHM = &quot;SHA-256&quot;; private final MessageDigest hashGenerator; /** * Creates a new HashCash generator using the SHA-256 algorithm * @throws NoSuchAlgorithmException If the &quot;SHA-256&quot; algorithm is not available */ public HashCash() throws NoSuchAlgorithmException { hashGenerator = MessageDigest.getInstance(HASH_ALGORITHM); } /** * Generates a HashCash for the specified level * @param seed A seed for the HashCash * @param targetLevel The target level for the HashCash * @return The generated HashCash */ public long generateHashCash(final String seed, final int targetLevel) { // Variation counter (and final result) long counter = 0; while(true) { // Check if the current hashCash reaches the desired security level if(getSecurityLevel(seed + counter) &gt;= targetLevel) return counter; // Increase hash counter counter++; } } /** * Computes the security level of the given value * @param value The value to compute the level of * @return The security level of the value */ private final int getSecurityLevel(final String value) { hashGenerator.update(value.getBytes()); final byte[] hash = hashGenerator.digest(); int level = 0; for(final byte b: hash) { if(b != 0) break; level++; } return level; } } </code></pre> <p><strong>PHP (verification):</strong></p> <pre class="lang-php prettyprint-override"><code>const HASH_CASH_SEC_LEVEL = 8; /** * Verifies a HashCash suffix (by checking it's security level) * @param string $seed The seed of the identity * @param string $suffix The HashCash suffix * @return bool Whether the given HashCash suffix is valid */ function verifyHashCash(string $seed, string $suffix): bool { $hash = hash('sha256', $seed.$suffix, true); $level = 0; $length = strlen($hash); for($b = 0; $b &lt; $length; $b++) { if(ord($hash[$b]) !== 0) break; $level++; } return $level &gt;= HASH_CASH_SEC_LEVEL; } </code></pre> <ul> <li>Are there any security related issues?</li> <li>Are there performance optimizations for the Java code?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T23:43:27.757", "Id": "481002", "Score": "0", "body": "Do you want to put the `return $level >= HASH_CASH_SEC_LEVEL;` logic into your loop to provide a potential early return? Then after the loop just return false?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T23:48:53.857", "Id": "481004", "Score": "0", "body": "@mickmackusa It's a possiblity, but I prefer it this way, since i am not concerned with PHP performance and this seems more readable to me. (Plus, on the performence side, the loop usually breaks very early). Thanks anyways!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-04T03:14:31.237", "Id": "481010", "Score": "0", "body": "So shall we remove the php tag so that php reviewers are not attracted to this page?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-04T07:52:39.653", "Id": "481019", "Score": "0", "body": "@mickmackusa I am primarily concerned with security, since this is my first proof-of-work implementation. I additionally asked for \"performance optimizations for the Java code\", since the generating device needs to run these functions a lot (~millions of times), while the verification is a simple check, where I prefer maintainability. I also don't want the client code to be (much) less optimised, than the code of a potential attacker." } ]
[ { "body": "<pre><code>public HashCash() throws NoSuchAlgorithmException {\n</code></pre>\n<p>SHA-256 is a requirement for any Java SE environment. Instead of throwing you should be catching and converting to a <code>RuntimeException</code> (or <code>IllegalStateException</code>) with this particular exception as cause.</p>\n<pre><code>public long generateHashCash(final String seed, final int targetLevel) {\n...\nprivate final int getSecurityLevel(final String value) {\n</code></pre>\n<p>If you're going to design for performance you should <strong>not</strong> be using <code>String</code> types. The seed should be a byte array from the start. And you could use e.g. <code>ByteBuffer</code> to write an integer to an existing array that already starts with the <code>seed</code>.</p>\n<p>Note that SHA-256 is a Merkle-Damgard hash function that handles input block-by-block. That means that if you start off with a large enough seed (512 bits or larger) you might as well pre-hash it. Of course this means mucking about <strong>within</strong> the hash implementation.</p>\n<pre><code>if(b != 0)\n break;\nlevel++;\n</code></pre>\n<p>Generally the level calculation is performed on bits or even values (where the hash value, when seen as a unsigned number, is below a certain value).</p>\n<p>As for performance: you can stop comparing whenever you encounter a number that <em>doesn't have</em> the right level. It won't matter much when compared the time required to perform SHA-256 in all probability, but it is still wasteful.</p>\n<p>I don't expect <code>getSecurityLevel</code> to perform the actual hash calculation. A getter is generally not expected to perform any work at all.</p>\n<p>The PHP code doesn't seem to reflect the structure of the Java application. If you have one <code>getSecurityLevel</code> method I would expect the same in the verification application, whichever language is used.</p>\n<hr />\n<p>Otherwise, yes, it is a very simple proof of work. I'd rather require a <em>few</em> hashes instead of one, to average out the amount of work performed. With just one hash there will be a lot of luck involved, and the actual work will therefore vary rather wildly.</p>\n<p>In the unlikely case that you've invented yet another popular PoW: I'd use 128 bits rather than a 64 bit long. It's pretty easy to make a counter that operates on bytes directly, so you would not even have to convert to the binary values required for the hashing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T10:59:11.367", "Id": "485563", "Score": "0", "body": "Wow, you make great points! I've already switched to bit instead of byte \"resolution\" (but didn't update the post yet) - still using a loop to check though. Your explanations are very clear, but one recommendation I do not understand is the 128bit counter. I mean 64bit is already fairly large, so what's up with that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T11:12:22.973", "Id": "485564", "Score": "1", "body": "Sure but the current bitcoin is using 68 THps (!). So yeah, if you just need it for your personal scheme then this proof of work can do with 64 bits; a general computer won't ever count to that I suppose. Cryptographers just don't like anything below 2^128 ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T12:09:52.190", "Id": "485568", "Score": "1", "body": "@Minding you must not update your post after receiving a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T12:36:17.583", "Id": "485572", "Score": "0", "body": "@mickmackusa Thanks for the info! Is it a hard rule I can read somewhere or more of a behaviour that is expected by the community?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T12:41:14.663", "Id": "485575", "Score": "1", "body": "https://codereview.meta.stackexchange.com/q/1763/141885" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T10:09:10.830", "Id": "247940", "ParentId": "244940", "Score": "1" } } ]
{ "AcceptedAnswerId": "247940", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T14:01:59.087", "Id": "244940", "Score": "2", "Tags": [ "java", "php", "security" ], "Title": "Simple proof-of-work (based on HashCash)" }
244940