body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>The code below is a program I'm writing to help myself budget. </p> <p>I am still new to programming and was wondering what you all thought about the code, or what I could improve at and what is good. </p> <p>This works by gathering data and information from the income and bills to help show you your budget. My end goal with this is to have a good visual program that could show you your finances better. </p> <pre><code>def mainmenu(): print("Welcome to the main menu.\n" "below is a list of options for you to choose from.\n" "In the help menu you, can see the proper steps and instructions to follow.\n\n"'' "Enter 'menu' for the main menu\n" "Enter 'help' for the help menu\n" "Enter 'income' to find your income\n" "Enter 'bills' to enter bills\n" "Enter 'budget to find the budget for your salary\n" "Enter 'quit' to quit the program") print("!!THIS IS A ROUGH ESTIMATE, TAXES ARE NOT ACCOUNTED FOR") #bring up menu asking to choose sections bring up income expenses and budgeting find a way to clear screen when new menu is brought up mainmenu() #switch to new algorithim def BasicIncome(Weekly_income): print("|weekly_income monthly income monthly hours worked bimonthly_pay quarterly salary yearly_salary\n" "|-------------------------------------------------------------------------------------------------------------\n" + "|" + str(Weekly_income)+" " + str(monthly_income)+" " + str(monthly_hours_worked)+" " + str(bimonthly_pay)+" " + str(quarterly_salary)+" " + str(yearly_salary)+ "\n\n") return Weekly_income, monthly_income, monthly_hours_worked, bimonthly_pay, quarterly_salary, yearly_salary #Enter basic bill summary #this is all a basic idea and can be broken down in a different section. This is just a brief income summary print("\n\nNow that we have a brief summary of your income we will look over your expenses") #compare bills to budget and income def bills(monthly_income, expense_one, total_monthly_expense, bimonthly_expenses, quarterly_expenses, yearly_expenses): print("Your bi-monthly expense cost is ${}".format(bimonthly_expenses)) print("Your quartley expense cost is ${}".format(quarterly_expenses)) print("Your yearly expense cost is ${}".format(yearly_expenses)) return (monthly_income, expense_one, total_monthly_expense) def budget(FPR, TPR, TIPS): print("50% of your monthly budget is ${}".format(FPR)) print("30% of your monthly budget is ${}".format(TPR)) print("20% of your monthly budget is ${}\n\n\n\n".format(TIPS)) print("After your bills your monthly expense budget is ${}".format(float(FPR - expense_one))) print("Your weekly spending budget is ${}".format(float(TIPS / 4))) print("After two months of saving you will have saved ${}".format(float(TPR * 2))) print("Every week you will save ${}" .format(float(TPR / 4))) def expenses(expense_one, totaly_monthly_expenses, monthly_income, bimonthly_expenses, quarterly_expenses, yearly_expenses): print( "|income after expenses/ bi-monthly quarterly yearly\n" "|----------------------------------------------------------------\n" + "|\n" + "| " + "" + "-" + str(bimonthly_expenses) + " " + "-" + str( quarterly_expenses) + " " + "-" + str(yearly_expenses) + "\n\n") return expense_one, totaly_monthly_expenses, monthly_income, expense_one, bimonthly_expenses, quarterly_expenses, yearly_expenses while True: UserInput = input("{}Enter a command:\n&gt; " .format("\n\n")) if UserInput.upper() == "HELP": #make help menu pass elif UserInput.upper() == "MENU": mainmenu() elif UserInput.upper() == "INCOME": Weekly_income = float(input("Enter your weekly income:\n&gt; ")) monthly_income = float(Weekly_income * 4) bimonthly_pay = float(Weekly_income * 8) monthly_hours_worked = float(40 * 4) quarterly_salary = float(Weekly_income * 16) yearly_salary = float(Weekly_income * 52) BasicIncome(Weekly_income) # need call to function elif UserInput.upper() == "BILLS": expense_one = float(input("Enter the amount of the bill you have in total\n&gt;$")) total_monthly_expense = float(monthly_income - expense_one) bimonthly_expenses = float(expense_one * 2) quarterly_expenses = float(expense_one * 4) yearly_expenses = float(expense_one * 12) bills(monthly_income, expense_one, total_monthly_expense, bimonthly_expenses, quarterly_expenses,yearly_expenses) elif UserInput.upper() == "BUDGET": FPR = float(monthly_income / 2) TPR = float(monthly_income / 3.33) TIPS = float(monthly_income / 5) budget(FPR, TPR, TIPS) else: UserInput.upper() == "QUIT" quit() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T02:44:11.240", "Id": "455054", "Score": "0", "body": "I'm not an expert in Python so I'll stick to a +1 for clean code. Some positives that I noticed are: concise but descriptive variable names, broken out `print` statements instead of new lining to death on a single line, and of course, comments." } ]
[ { "body": "<p>OK so a few points to neaten things up:</p>\n\n<ul>\n<li>Multiline strings are available in Python like so:</li>\n</ul>\n\n<pre><code>s = \"\"\"\nLine 1\nLine 2\n\"\"\"\n</code></pre>\n\n<p>Use these where possible to avoid all the <code>'\\n'</code> characters and needless speech marks when printing multiline blocks.</p>\n\n<ul>\n<li><p>Generally speaking, lay out your code with all function definitions at the top and the body of the program below. Currently, you have one <code>print</code> statement and a call to <code>mainmenu()</code> in the middle of the functions getting lost.</p></li>\n<li><p><code>BasicIncome</code> shouldn't really be using <code>monthly_income</code>, <code>monthly_hours</code> etc. from the global scope. (Off the top of my head I'm not even sure if it will work like that!) Pass them as arguments to the function if you really need them.</p></li>\n<li><p>Your function names could be more informative. Take <code>bills</code> and <code>budget</code> for example: a good way to name them put the name into a sentence \"The role of this function is to {{function_name}}\". <code>printBills</code> and <code>printBudget</code> would probably be more appropriate here.</p></li>\n<li><p>In <code>bills</code> and <code>expenses</code>, there is no need to return all of the arguments to the functions at the end. You haven't modified them in any way therefore anything that called the function will actually already have access to them!</p></li>\n<li><p>Try and stick to strict naming conventions. You have mixed PascalCase (e.g. <code>UserInput</code>) and snake_case (e.g. expense_one) variables.</p></li>\n<li><p>You might want to do some input validation. Consider what would happen if somebody enters \"none\" as their income.</p></li>\n<li><p>I think at the bottom of your program, you might want <code>elif UserInput.upper() == \"QUIT\":</code>. Currently a typo will quit your program</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T03:06:59.453", "Id": "232924", "ParentId": "232918", "Score": "1" } }, { "body": "<p>It is easy to read which is a good point. It is much easier to debug code that you can read easily. You can avoid having to break each line by using 3 single quotes at the start and end of the text.</p>\n\n<pre><code>def mainmenu():\n print('''\n Welcome to the main menu.\n below is a list of options for you to choose from.\n In the help menu you, can see the proper steps and instructions to follow.\n Enter 'menu' for the main menu\n Enter 'help' for the help menu\n Enter 'income' to find your income\n Enter 'bills' to enter bills\n Enter 'budget to find the budget for your salary\n Enter 'quit' to quit the program\n ''')\n</code></pre>\n\n<p>I would consider using classes to capture information because they are very easy to work with.</p>\n\n<pre><code>class Person:\n def __init__(self, name, money_in, money_out):\n self.name = name\n self.money_in = money_in\n self.money_out = money_out\n\n def __str__(self):\n return '''\n | Money in | Money out | Name |\n\n {} {} {}\n\n '''.format(self.money_in, self.money_out, self.name)\n\nuser = Person('Johnny', 1200, 800)\nprint(user)\n</code></pre>\n\n<p>When this is returned you get:</p>\n\n<pre><code>| Money in | Money out | Name | \n\n 1200 800 Johnny\n</code></pre>\n\n<p>In your while loop you are calculating the users input. You can use functions to handle that:</p>\n\n<pre><code>def main():\n option = input('enter name:&gt; ')\n user.name = option\n print('\\t\\t, ', user)\n\nwhile True:\n choice = input(':&gt; ')\n if choice.lower() == 'main': # .lower() converts any input into lowercase\n main()\n\n\netc...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T10:56:23.663", "Id": "232936", "ParentId": "232918", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T00:46:45.733", "Id": "232918", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "New budgeting Program" }
232918
<p>Each client application would send a filepath and search term to the server. The server then takes that file path reads the file and returns any lines that contain the search term, the server then watches the file for any size increase and if the new lines contain wanted information it gets transmitted.</p> <p>The first <code>for</code> loop is echoing the initial message to make sure that it is correct it also validates that the file path is a file.</p> <p>There are some odd bits that are mostly for if a log gets rotated while a connection is active.</p> <p>My planned upgrades will include better exception handling, I know there are a couple places where if something goes wrong, it'll just throw you into an infinite while loop. There is some other stuff I'll need to fix but you know I'm here for your perspective, not the other way.</p> <pre><code>import asyncio, socket, os HOST = "127.0.0.1" PORT = 65432 async def log_transmit(reader, writer): try: print('new connect') data, datval, fpath = '', '', '' #ensuring communication of filepath and search term while 1: data = (await reader.read(128)) print(f'{fpath} {datval}') if data.decode('utf-8').strip() == 'recv' and os.path.isfile(fpath): break else: datval = data.decode('utf-8').strip() l = datval.split() if len(l) == 2: fpath, datval = [x for x in l] writer.write(data) await writer.drain() file = open(fpath, 'r') line = file.readline() # reading to the end of the file while line != '': if datval in line: line += ' ' * (256 - len(line.encode())) writer.write(line.encode()) await writer.drain() line = file.readline() size = os.path.getsize(fpath) # looking for new file entries while 1: await asyncio.sleep(0.1) try: newsize = os.path.getsize(fpath) # handling log rotation except FileNotFoundError: while os.path.isfile(fpath) == False: pass file = open(fpath, 'r') if newsize &gt; size: # new entries need to be examined file.seek(size) line = file.readline() while line != '': size += len(line) if datval in line: line = line.strip() line += ' ' * (256 - len(line)) writer.write(line.encode()) await writer.drain() file.seek(size) line = file.readline() elif newsize &lt; size: # more log rotation handling await asyncio.sleep(2) file = open(fpath, 'r') size = newsize # else file hasn't changed nothing to be done except ConnectionResetError: print('client disconnected') file.close() writer.close() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.create_task(asyncio.start_server(log_transmit, HOST, PORT)) loop.run_forever() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T02:44:46.533", "Id": "232922", "Score": "2", "Tags": [ "python", "python-3.x", "multithreading", "socket" ], "Title": "Log tailing socket server" }
232922
<p>I have this code, and the point is I want to dynamically change the mongo connecter to change between ssl, not ssl and with and without username in the same connecter function.</p> <pre class="lang-py prettyprint-override"><code>if auth_required: if config.getboolean(component, 'ssl', fallback=False): client = MongoClient( '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']), ssl=True, ssl_ca_certs=config.get(component, 'ssl_path'), serverSelectionTimeoutMS=timeout, username=username, password=password, authSource=auth_source, authMechanism=auth_mechanism ) else: client = MongoClient( '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']), serverSelectionTimeoutMS=timeout, username=username, password=password, authSource=auth_source, authMechanism=auth_mechanism ) else: if config.getboolean(component, 'ssl', fallback=False): client = MongoClient( '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']), ssl=True, ssl_ca_certs=config.get(component, 'ssl_path'), serverSelectionTimeoutMS=timeout ) else: client = MongoClient( '{host}:{port}'.format(host=config[component]['host'], port=config[component]['port']), serverSelectionTimeoutMS=timeout ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T09:46:31.363", "Id": "455075", "Score": "0", "body": "So, it doesn't do what it should, right? Please take a look at the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T09:47:54.010", "Id": "455076", "Score": "0", "body": "@Mast: It seems to do what they want, just not in the most readable way. You could argue that it needs more context, since quite a few things are undefined, but IMO it is sufficient (well, I managed to answer it, maybe even correctly)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T09:51:13.090", "Id": "455077", "Score": "2", "body": "The title could be more representative of what your code achieves, and not what you want out of a review. Everyone here wants their code reviewed, so that would make for very boring titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T09:53:48.207", "Id": "455078", "Score": "1", "body": "@Graipher That you're guessing at the correctness of your answer is an indication of the state of the question. I'm not convinced it's either within or outside our scope, but for now, I'll leave it be and wait for reaction. Do note that if your answer turns out to be incorrect due to assumptions, the code in the question can't be changed unless the answer is removed due to our invalidation rules. I just hope you're right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T09:58:15.700", "Id": "455079", "Score": "0", "body": "@Mast Agreed. I'm more than willing to delete my answer in that case." } ]
[ { "body": "<p>If you build a dictionary of keyword arguments (customarily called <code>kwargs</code>), you can address the two options separately and consolidate everything into one call to <code>MongoClient</code>. This has the advantage that if you update e.g. the SSL part, you only need to change it in one place instead of remembering to change it twice:</p>\n\n<pre><code>host = '{host}:{port}'.format(**config[component])\nkwargs = {\"serverSelectionTimeoutMS\": timeout}\n\nif config.getboolean(component, 'ssl', fallback=False):\n kwargs[\"ssl\"] = True\n kwargs[\"ssl_ca_certs\"] = config.get(component, 'ssl_path')\n\nif auth_required:\n kwargs.update({\"username\": username, \"password\": password,\n \"authSource\": auth_source, \"authMechanism\": auth_mechanism})\n\nclient = MongoClient(host, **kwargs)\n</code></pre>\n\n<p>I also used the fact that <code>config[component]</code> seems to be a dictionary, so you can unpack it in the <code>format</code> and the <code>host</code> and <code>port</code> keys will be used.</p>\n\n<p>I used two different ways to change the values in the dictionary so you can choose, depending on which one is easier to read. Using both is also fine, as I did here. For the SSL part there is few values, so using <code>dict.update</code> would make it more cluttered, but for the auth part there are enough values that typing <code>kwargs[...] = ...</code> would get tedious.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T07:03:35.480", "Id": "455212", "Score": "0", "body": "Thanks a lot for reviewing my code, thats what i searching for :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T09:46:38.867", "Id": "232934", "ParentId": "232931", "Score": "3" } } ]
{ "AcceptedAnswerId": "232934", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T09:12:25.150", "Id": "232931", "Score": "2", "Tags": [ "python", "pymongo" ], "Title": "How to think smarter when you need diff args in functions" }
232931
<p>I am a beginner with regards to C; I'm used to using high-level languages (Java, Python, JS, etc) and this is my first project in a lower-level language. I wrote a simple Brainfuck interpreter, given that my Python implementation was super slow.</p> <p>Here's the code:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; unsigned char mem[30000] = {0}; unsigned char* ptr = mem; void goToLoopEnd(char** ip) { int searching = 1; while (searching &gt; 0) { (*ip)++; switch (**ip) { case '[': searching++; break; case ']': searching--; break; default: break; } } } void goToLoopStart(char** ip) { int searching = 1; while (searching &gt; 0) { (*ip)--; switch (**ip) { case ']': searching++; break; case '[': searching--; break; default: break; } } } void interpret(char* code) { char* ip; for (ip = code; *ip != '\0'; ip++) { switch (*ip) { case '&gt;': ptr++; break; case '&lt;': ptr--; break; case '+': (*ptr)++; break; case '-': (*ptr)--; break; case '.': putchar(*ptr); break; case ',': *ptr = getchar(); break; case '[': if (*ptr == 0) { goToLoopEnd(&amp;ip); } break; case ']': if (*ptr != 0) { goToLoopStart(&amp;ip); } break; default: break; } } } int main() { // Set to interpret a mandelbrot set fractal viewer in brainfuck written by Erik Bosman. interpret("+++++++++++++[-&gt;++&gt;&gt;&gt;+++++&gt;++&gt;+&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;++++++&gt;---&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+++++++++++++++[[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]+[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-]+[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-]&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-]+&lt;&lt;&lt;&lt;&lt;&lt;&lt;+++++[-[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-]+[&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-]&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-]+&lt;&lt;&lt;&lt;&lt;&lt;++++[-[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;+++++++[-[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[[-]&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;+&lt;&lt;&lt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;+&lt;&lt;&lt;+&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;+&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+++++++++++++++[[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]+&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-]+[&gt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;-&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;[-&lt;&lt;+&gt;&gt;]&lt;&lt;[-&gt;&gt;+&gt;&gt;+&lt;&lt;&lt;&lt;]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-]&lt;-&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;[&lt;-&gt;-&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;-&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;[-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&gt;+&lt;&lt;&lt;&lt;]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-]&lt;-&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;[&lt;-&gt;-&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+++++++++++++++[[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;[-&lt;&lt;&lt;-&gt;&gt;&gt;]+&lt;&lt;&lt;[-&gt;&gt;&gt;-&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;+&lt;]]+&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;-&lt;[-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;[-]+&lt;]]+&gt;[-&lt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;+&gt;&gt;&gt;-&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;++++++++++++++++++++++++++&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;[-]&lt;&lt;]&gt;&gt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&lt;[-&lt;+&gt;&gt;&gt;&gt;+&lt;&lt;[-]]&gt;[-&lt;&lt;[-&gt;+&gt;&gt;&gt;-&lt;&lt;&lt;&lt;]&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;[-]&gt;[-]&gt;[-]&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-]&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+++++++++++++++[[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]+&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-]+[&gt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;-&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;[-&lt;&lt;+&gt;&gt;]&lt;&lt;[-&gt;&gt;+&gt;+&lt;&lt;&lt;]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-]&lt;-&gt;&gt;&gt;[-&lt;&lt;&lt;+&gt;[&lt;-&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;]&lt;&lt;[-&gt;&gt;+&lt;&lt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;-&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;[-&lt;&lt;+&gt;&gt;]&lt;&lt;[-&gt;&gt;+&gt;&gt;+&lt;&lt;&lt;&lt;]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-]&lt;-&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;[&lt;-&gt;-&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+++++++++++++++[[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-]+[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;[-]&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;+&gt;[-&lt;-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;]&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;++&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;]&lt;-&gt;+&gt;]&lt;[-&gt;+&lt;]&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;[-]&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;-&gt;&gt;&gt;&gt;&gt;[&gt;&gt;[-&lt;&lt;-&gt;&gt;]+&lt;&lt;[-&gt;&gt;-&gt;[-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;+&lt;]]+&gt;&gt;&gt;[-&lt;&lt;&lt;-&gt;&gt;&gt;]+&lt;&lt;&lt;[-&gt;&gt;&gt;-&lt;[-&lt;&lt;+&gt;&gt;]&lt;&lt;[-&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;[-]+&lt;]]+&gt;[-&lt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&gt;&gt;&gt;&gt;&gt;[&gt;+&gt;&gt;[-&lt;&lt;-&gt;&gt;]&lt;&lt;[-&gt;&gt;+&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&lt;[&gt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&lt;]&gt;[-&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;]&gt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;[-&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;]&gt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-]&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&gt;&gt;&gt;&gt;&gt;&gt;[&gt;+&gt;[-&lt;-&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&lt;[&gt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;[-&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;]&gt;]&lt;[-&gt;&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;]&gt;&gt;[-&gt;&gt;&gt;+&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;]&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&lt;]&gt;[-&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;]&gt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;[-&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;]&gt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;[-]&gt;&gt;[-]&gt;[-]&gt;&gt;&gt;&gt;&gt;[&gt;&gt;[-]&gt;[-]&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+++++++++++++++[[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]+&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-]+[&gt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;-&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;[-&lt;&lt;+&gt;&gt;]&lt;&lt;[-&gt;&gt;+&gt;+&lt;&lt;&lt;]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-]&lt;-&gt;&gt;&gt;[-&lt;&lt;&lt;+&gt;[&lt;-&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;]&lt;&lt;[-&gt;&gt;+&lt;&lt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;[-]&gt;&gt;&gt;&gt;+++++++++++++++[[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-]+[&gt;&gt;&gt;[-&lt;&lt;&lt;-&gt;&gt;&gt;]+&lt;&lt;&lt;[-&gt;&gt;&gt;-&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;+&lt;]]+&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;-&lt;[-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;[-]+&lt;]]+&gt;[-&lt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&gt;&gt;&gt;&gt;&gt;&gt;[&gt;+&gt;&gt;&gt;[-&lt;&lt;&lt;-&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&lt;[&gt;[-&gt;+&gt;[-&lt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;+&gt;&gt;]&lt;]&gt;[-&lt;&lt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;]&gt;&gt;[-&lt;+&gt;&gt;[-&lt;&lt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;]&gt;[-&lt;&lt;+&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&gt;&gt;&gt;&gt;&gt;[&gt;+&gt;&gt;[-&lt;&lt;-&gt;&gt;]&lt;&lt;[-&gt;&gt;+&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&lt;[&gt;[-&gt;+&gt;&gt;[-&lt;&lt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;+&gt;]&gt;]&lt;[-&lt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;]&gt;&gt;&gt;[-&lt;&lt;+&gt;[-&lt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;]&lt;[-&lt;+&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;[-]&gt;[-]&gt;[-]&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-]&gt;[-]&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;+&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;+&gt;[-&lt;-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;]&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;++&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;]&lt;-&gt;+&gt;&gt;]&lt;&lt;[-&gt;&gt;+&lt;&lt;]&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;]+&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;-&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;[-&lt;&lt;&lt;-&gt;&gt;&gt;]+&lt;&lt;&lt;[-&gt;&gt;&gt;-&lt;[-&lt;&lt;+&gt;&gt;]&lt;&lt;[-&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;+&lt;]]+&gt;&gt;[-&lt;&lt;-&gt;&gt;]+&lt;&lt;[-&gt;&gt;-&gt;[-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;[-]+&lt;]]+&gt;[-&lt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&gt;&gt;&gt;&gt;&gt;&gt;[&gt;+&gt;[-&lt;-&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&lt;[&gt;[-&gt;&gt;&gt;&gt;+&lt;&lt;[-&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&gt;]&lt;[-&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;]&gt;&gt;[-&gt;&gt;+&lt;&lt;&lt;[-&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;]&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;[-]&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;+&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&gt;&gt;&gt;&gt;&gt;[&gt;+&gt;&gt;[-&lt;&lt;-&gt;&gt;]&lt;&lt;[-&gt;&gt;+&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&lt;[&gt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;[-&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&gt;&gt;+&lt;&lt;]&lt;]&gt;[-&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;]&gt;[-&gt;&gt;&gt;+&lt;&lt;[-&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;]&gt;[-&gt;&gt;+&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;[-]&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&gt;[-]&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;+&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;[-&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&gt;&gt;+&lt;&lt;]&lt;]&gt;[-&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;]&gt;[-&gt;&gt;&gt;+&lt;&lt;[-&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;]&gt;[-&gt;&gt;+&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;[-]&gt;[-]&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-]&gt;[-]&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;+&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+++++++++++++++[[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]+&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-]+[&gt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;-&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;[-&lt;&lt;+&gt;&gt;]&lt;&lt;[-&gt;&gt;+&gt;&gt;+&lt;&lt;&lt;&lt;]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-]&lt;-&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;[&lt;-&gt;-&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;-&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;[-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&gt;+&lt;&lt;&lt;&lt;]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-]&lt;-&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;[&lt;-&gt;-&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+++++++++++++++[[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;[-&lt;&lt;&lt;-&gt;&gt;&gt;]+&lt;&lt;&lt;[-&gt;&gt;&gt;-&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;+&lt;]]+&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;-&lt;[-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;&lt;&lt;[-&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;[-]+&lt;]]+&gt;[-&lt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;-&gt;&gt;[-&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;[-]&lt;&lt;]&gt;&gt;]&lt;&lt;+&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;.&gt;&gt;]&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;.&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;&gt;&gt;[&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;[-]&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;[-]&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;+++++++++++[-[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;+[-]&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-]+&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&gt;&gt;[&gt;+&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;&gt;&gt;&gt;&gt;[-&gt;&gt;+&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-]&lt;-&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;[&lt;-&gt;-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;-&lt;&lt;&lt;&lt;[-]+&lt;&lt;&lt;]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;-&gt;&gt;[&gt;&gt;&gt;&gt;&gt;[-&gt;&gt;+&lt;&lt;]&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-]&lt;-&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;[&lt;-&gt;-&lt;&lt;&lt;+&gt;&gt;&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;+++++[-[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;-&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;+&lt;]]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;-&lt;&lt;[-&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;[-]+&lt;]]+&gt;[-&lt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-]&lt;&lt;&lt;+++++[-[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;]&lt;&lt;&lt;&lt;.&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;[-]&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;++++++++++[-[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+[-]&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-]+&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&gt;[&gt;+&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;&gt;&gt;&gt;&gt;&gt;[-&gt;&gt;+&lt;&lt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-]&lt;-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;[&lt;-&gt;-&lt;&lt;+&gt;&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;[-]+&lt;&lt;&lt;]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-&gt;[&gt;&gt;&gt;&gt;&gt;&gt;[-&gt;&gt;+&lt;&lt;]&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&gt;[-]&lt;-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;[&lt;-&gt;-&lt;&lt;+&gt;&gt;]&lt;[-&gt;+&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&lt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;+++++[-[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;-&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;+&lt;]]+&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;[-&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-&lt;&lt;[-&lt;&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;[-]+&gt;&gt;&gt;&gt;&gt;&gt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;[-]+&lt;]]+&gt;[-&lt;[&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;[-]&lt;&lt;&lt;+++++[-[-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;]&gt;&gt;&gt;&gt;&gt;-&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;-&lt;&lt;&lt;&lt;&lt;&lt;[&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;]]&gt;&gt;&gt;]"); return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:36:16.423", "Id": "455269", "Score": "2", "body": "I'm looking forward to your posts when you have become an experienced C programmer! :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T09:13:20.013", "Id": "455372", "Score": "0", "body": "For loops: wouldn't it better to put loop start position in stack on each `[` encountered, and on `]` check top address of the stack (and on 0 in cell pop the stack)? IMO that will reduce number of traversings in `goToLoop` functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T15:17:06.003", "Id": "455433", "Score": "1", "body": "This is pretty good! One recommendation: Wrap your memory and instruction pointer into a \"BrainFuckVM\" struct. That will tidy that code up, and allow you to use some stronger types signatures on your functions. Plus from there you can get fancy and add snapshotting to save/restore vm state, you can add an \"undo\" to go back in time in the processing, etc.!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T15:54:32.480", "Id": "455580", "Score": "0", "body": "You lucky... I asked about mine a while back and I had to have a bounty put on it to get anything." } ]
[ { "body": "<p>Here are some things that may help you improve your program. In all, it seems to be nice, straightforward code that does what it needs to do. Good start!</p>\n\n<h2>Use only required <code>#include</code>s</h2>\n\n<p>The code has <code>#include &lt;stdbool.h&gt;</code> but doesn't use booleans. It also appears that nothing from <code>&lt;stdlib.h&gt;</code> is used either. Only include files that are actually needed.</p>\n\n<h2>Avoid the use of global variables</h2>\n\n<p>I see that <code>ptr</code> and indirectly, <code>mem</code> are used only within <code>interpret()</code> but they are declared as global variables. It's generally better to explicitly pass variables your function will need or declare them within the appropriately smallest possible scope rather than using the vague implicit linkage of a global variable. In this case, both <code>mem</code> and <code>ptr</code> could be local variables within <code>interpret()</code>. Use <code>memset</code> if you need to zero the contents.</p>\n\n<h2>Use const where practical</h2>\n\n<p>The <code>interpret()</code> function does not modify the contents of the <code>code</code> pointer it is passed, so it should be declared <code>const</code>:</p>\n\n<pre><code>void interpret(const char* code) { /*...*/ }\n</code></pre>\n\n<p>This also means that <code>ip</code> can be <code>const</code> and then also that the arguments to the other functions can be, too.</p>\n\n<h2>Declare local routines <code>static</code></h2>\n\n<p>If you declare <code>goToLoopEnd</code> and <code>goToLoopStart</code> as <code>static</code>, the compiler will know that they can never be called outside this one file. With that information, much more optimization might be done, such as inlining the code. </p>\n\n<h2>Let the compiler generate code</h2>\n\n<p>When a C program reaches the end of <code>main</code> the compiler will automatically generate code to return 0, so it is not necessary to write <code>return 0;</code> explicitly at the end of <code>main</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T19:26:32.357", "Id": "455154", "Score": "39", "body": "I agree with all of these suggestions except for the last one. I prefer the return value to be explicit. main is the only function where omitting the return value is allowed (except for void functions), so including it there as well makes the code more consistent. I do not see explicit guidance on this in the C++ core guidelines though, so it seems to be a matter of preference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T19:42:04.360", "Id": "455158", "Score": "1", "body": "`mem` being inside `interpret` might be a stretch. Probably would be easier to dynamically-allocate `ptr`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T20:13:09.520", "Id": "455165", "Score": "2", "body": "@MitchLindgren it is solely a matter of preference, but it is good to know about that aspect of the standard either way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T02:41:27.877", "Id": "455204", "Score": "3", "body": "@JL2210: Most efficient but still good style: `static unsigned char mem[30000] = {0};` *inside `interpret`*. If you know how much zeroed memory you want, you might as well statically allocate it in the BSS instead of dynamically with `calloc`. Although for practical purposes, using a big `calloc` might put it farther from anything else and give more protection against out-of-bounds writes (simple segfault instead of maybe corrupting `.data` or other BSS objects). In C terms a malformed BF program can cause UB in this interpreter either way; in mainstream implementations the details matter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T20:50:44.410", "Id": "455323", "Score": "2", "body": "If you don't include `stdbool.h`, replace `unsigned char mem[30000] = {0};` by `static unsigned char mem[30000];`, prototype by `int main(void)`, and **don't** follow that last suggestion, then your code is now compatible with `C89`, and many more compliers are open to you." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T13:35:19.740", "Id": "232942", "ParentId": "232935", "Score": "27" } }, { "body": "<p>This is a pretty reasonable start on a simple interpreter. Edward's suggestions are all good; a few additional suggestions:</p>\n\n<hr>\n\n<pre><code>interpret(\"+++++++++++++[-&gt;....\n</code></pre>\n\n<p>Please break up that long line. C allows you to break up literal strings</p>\n\n<pre><code>\"like \"\n\"this.\"\n</code></pre>\n\n<hr>\n\n<pre><code>void goToLoopEnd(char** ip) {\n...\nvoid goToLoopStart(char** ip) {\n...\n</code></pre>\n\n<p>If you wrote these instead as</p>\n\n<pre><code>char * findLoopEnd(char* ip) {\n...\nchar * findLoopStart(char* ip) { \n...\n</code></pre>\n\n<p>then you have functions that are just as useful, but <em>do not modify the input and are therefore testable with an independent unit test</em>.</p>\n\n<p>This also eliminates a double pointer; double pointers are hard to reason about, so if there is a cheap and easy way to get rid of them, go for it.</p>\n\n<p>This also enables you to improve the contract of these methods; for example, you could return null if there is no matching bracket. Which then brings up...</p>\n\n<hr>\n\n<p>Aside from that, my biggest problem with your interpreter is that it has undefined behaviours all over the place if the program is not valid. What happens if there is an unmatched <code>[</code>? What happens if the pointer goes <em>before</em> available memory? Bad stuff, that's what. <strong>A good interpreter is safe no matter what its input, and gives good diagnostics to the user when the input is bad.</strong> Always structure an interpreter so that it detects bad inputs, because it <em>will</em> get bad inputs.</p>\n\n<p>In particular, note that Brainfuck does not specify what happens when the tape pointer becomes negative; does the tape \"wrap around?\", is it an error, is there supposed to be an infinite tape in both directions? The conservative thing to do is to make it an error, but you haven't even done that; you just do something undefined.</p>\n\n<hr>\n\n<p>Once you have the undefined behaviours under control, consider the cost of doing a linear search for matching brackets all the time. It is almost always more efficient to scan the source code <em>once</em>, make a note of the locations of all matching pairs of brackets, and then when you hit a bracket you just do a lookup of the destination rather than a linear search for it. Yes, a linear search is fast if the program is small, but the program might not be small.</p>\n\n<p>This step works to support the previous issue; if you record matching brackets before you run the program, you guarantee that every bracket is matched!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T19:49:47.080", "Id": "455160", "Score": "3", "body": "Strangely, there are no standard diagnostics requirements for Brainfuck interpreters. Your note about checking for bad input is an important one!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T22:07:46.993", "Id": "455172", "Score": "1", "body": "I agree with your logic about undefined behavior but I find it ironic we are complaining about it on a question written in C. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T22:18:51.727", "Id": "455175", "Score": "14", "body": "@CaptainMan: That is somewhat ironic, yes. The given implementation turns undefined behaviour in the BF language into undefined behaviour in the C language! The better approach is to define the behaviour in the BF language, and then implement that so that there is no UB in the C implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T02:50:24.877", "Id": "455206", "Score": "3", "body": "+1, was about to write an answer about using an O(1) map / dictionary data structure to find branch targets (possibly as simple as an array of `char*` or `unsigned` indexed by offset within the BF program), but you already mentioned that. Also that `depth` or `nest_depth` might be a clearer var name than `searching`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T09:45:45.147", "Id": "455225", "Score": "1", "body": "I wanted to store the bracket locations (as I did in my Python implementation) but I couldn't figure out how I would go about doing that in C. I used a dictionary in Python but isn't implementing a hash map a bit overkill for a project of this size?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T09:59:32.450", "Id": "455227", "Score": "0", "body": "Nvm, a friend helped me. I'll use an array of \"matching brackets\" structs, then binary search it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T15:30:12.503", "Id": "455275", "Score": "7", "body": "@Ghost: Whether any choice is \"over engineering\" depends entirely on the requirements of the client *who is you*. You moved to C from Python, you say, because the performance was not good enough; you're the only person who knows if the performance is *still* not good enough. I imagine that you also chose C because it's a language you wish to learn, and *implementing simple data structures like hash maps is a great way to learn a new language*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T05:59:58.680", "Id": "455498", "Score": "0", "body": "@Ghost: See my earlier comment: the very simplest form of this (and efficient if it fits in your CPU's L1d or at least L2 cache) is an array of `unsigned` offsets, or of `char*`, indexed by offset within the BF program. Or with your size fixed at 30k, you can save space by making the bracket-match table `static unsigned short matching_bracket[30000];`. Having half the cache footprint is worth it; most CPU architectures have relatively efficient narrow loads that zero-extend a short to int or pointer-width. This is certainly true on x86, which you probably care most about optimizing for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T06:00:31.763", "Id": "455499", "Score": "0", "body": "For small BF programs, only the first `n` elements of that array will get used, so the actual \"hot\" footprint is nice and small." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T11:46:42.047", "Id": "457624", "Score": "1", "body": "@Peter I think you confused the code segment size (unlimited) with the data segment size (min 30000). For what you intend to express, it's also more precise to use `uint16_t` than `unsigned short`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:05:18.300", "Id": "457644", "Score": "0", "body": "@RolandIllig: oh yes, right. I was thinking for some reason there was also an upper limit on program length, or just got mixed up. >.< `unsigned short` was on purpose though; you don't need the program to fail to run on systems without the optional `uint16_t` fixed-width type, and it has a minimum size of 16-bit so it is safe if the program upper limit was that small. (I think all modern systems do have `uint16_t`, though, so no real problem with using that, except maybe on a 24-bit word-addressable DSP where CHAR_BIT = 24.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T13:13:53.150", "Id": "457645", "Score": "0", "body": "@Peter Ah, yes, thanks for the DSP reminder." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T18:44:12.477", "Id": "232960", "ParentId": "232935", "Score": "47" } }, { "body": "<p>Expanding on Edward's point with \"const\": It's good practice to properly qualify all constant data, not so much for optimization (see <a href=\"http://www.gotw.ca/gotw/081.htm\" rel=\"nofollow noreferrer\">http://www.gotw.ca/gotw/081.htm</a>) as for displaying the author's intent, and for preventing errors. <code>const</code> is infectious, so you'll have to change all function signatures and pointer declarations operating on the constant brainfuck code.</p>\n\n<p>That you can initialize a <code>char *</code> with a literal at all is pure legacy: K&amp;R C did not have <code>const</code> (which reflected the fact that one could (I think) write anywhere in memory on then-typical machines like the PDP11). So there was already a lot of code out there which would break, and even after 1989 a lot of people didn't use const.</p>\n\n<p>Back to your program: I do not know brainfuck; a brainfuck program could well be self-modifying like a Turing machine. That it doesn't do that can be expressed in C, preventing <em>accidental</em> write attempts as well. </p>\n\n<p>Incidentally this change makes your program valid C++, another thing I find good practice, even if <a href=\"https://stackoverflow.com/users/560648/lightness-races-with-monica\">Lightness Races with Monica</a> will probably disagree: So cast your <code>malloc</code>s if you have any (even if <a href=\"https://stackoverflow.com/a/605858/3150802\">unwind disagrees</a>), cast assignments to enums if you have any, and const your consts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T00:05:38.483", "Id": "455339", "Score": "1", "body": "BF programs are, thank goodness, not self-modifying. A BF program acts like a Turing Machine with two tapes, a finite, read-only tape for the program, and a writable, infinite tape for the data. Since BF is Turing Complete, you can of course write a simulation of a TM in BF; that's left as an exercise. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T06:08:21.980", "Id": "455500", "Score": "0", "body": "Making code be also valid C++ is generally good, but not when it means casting `malloc` IMO. Re: writeable strings: some PDP-11 models do have memory protection ([wikipedia](https://en.wikipedia.org/wiki/PDP-11#Models)). Early Unix was developed on PDP-11; perhaps it didn't enforce read-only pages, or toolchains put string literals in the `.data` section. Note that `char *p = \"hello\"` is not problematic if you never actually write through the pointer. But yes, that will segfault on modern Unix systems, unless you compiled with a compiler like GCC3 or older with `gcc -fwriteable-strings`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:17:25.433", "Id": "455505", "Score": "0", "body": "@PeterCordes Ah, interesting! (Both the PDP11 and gcc info)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-14T17:34:01.780", "Id": "457663", "Score": "1", "body": "@EricLippert you haven't than seen \"fukyorbrain\" yet, two BF programs that have \"multiple\" threads and modify each other :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T15:42:41.917", "Id": "233003", "ParentId": "232935", "Score": "2" } }, { "body": "<p>Adding to the other answers: These function declarations</p>\n\n<pre><code>int foo();\nint bar() { }\n</code></pre>\n\n<p>do <em>not</em> declare a prototype for foo respectively bar. In consequence, this is a legal implementation of foo:</p>\n\n<pre><code>int foo(int a) { }\n</code></pre>\n\n<p>And this is a likely illegal call to bar, however the compiler can't warn:</p>\n\n<pre><code>bar(42);\n</code></pre>\n\n<p>To provide a prototype, add void inside the parenthesis to make it a parameter-list (instead of the C89 identifier list) and all of the above would yield compile time errors:</p>\n\n<pre><code>int foo(void);\nint bar(void) {}\n</code></pre>\n\n<p>This is due to Cs history of K&amp;R style function declarations and definitions:</p>\n\n<pre><code>int foo();\n\nint foo(a)\nint a;\n{\n /* do something */\n}\n</code></pre>\n\n<p>Compatibility is great, but I don't think you should go lower than C99 if not explicitly needed, especially if it lessens the likelihood of severe bugs ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T09:36:55.947", "Id": "233854", "ParentId": "232935", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T10:08:28.490", "Id": "232935", "Score": "40", "Tags": [ "beginner", "c", "interpreter", "brainfuck" ], "Title": "Brainfuck interpreter written in C" }
232935
<p>Syntax Checker is a very common question of c++ programming using the data structure stack. However, this is the advanced level base on this question I found in a reference book. Here is the question:</p> <p>Base on the question checking the string parentheses balance, the output is to print “Success” if all the brackets [] {} () are matched. Otherwise, print "fail"</p> <pre><code>Sample Input: {[()]()}[] //Output:Success {}([[] //Output:3 {}([[]}] //Output:7 {}{(]} //Output:5 {}{](} //Output:4 ( [43]( i++ ; ) ) { lol = 3 ; } //Output:Success </code></pre> <p>My code as follow:</p> <pre><code>#include&lt;iostream&gt; #include&lt;stack&gt; #include&lt;string&gt; bool arePair(char start, char end) { if (start == '(' &amp;&amp; end == ')') return true; else if (start == '{' &amp;&amp; end == '}') return true; else if (start == '[' &amp;&amp; end == ']') return true; return false; } bool areParanthesesBalanced(std::string exp) { std::stack&lt;char&gt; S; for (int i = 0; i &lt; exp.size(); i++) { char c = exp.at(i); if (c == '(' || c == '{' || c == '[') S.push(exp.at(i)); else if (c == ')' || c == '}' || c == ']') { if (S.empty()|| !arePair(S.top(), c)) { return false; } else { S.pop(); } } } return S.empty() ? true : false; } int main(){ std::string input; while (std::getline(std::cin, input)) { if (areParanthesesBalanced(input)) std::cout &lt;&lt; "Success"&lt;&lt; std::endl; else std::cout &lt;&lt; "Fail" &lt;&lt; std::endl; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T12:19:35.673", "Id": "455088", "Score": "0", "body": "Welcome to CodeReview. Looking forward to a review of this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T14:33:02.763", "Id": "455104", "Score": "4", "body": "The comment in the code `//I dont know how to implement this part, so I just randomly output fail` indicates that this question is off-topic for the code review website." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T02:48:53.350", "Id": "455205", "Score": "0", "body": "edited. It's my bad to add that but then I am actually looking for some reviews..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T11:11:51.357", "Id": "455233", "Score": "0", "body": "Just removing the comment doesn't make the code less broken." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T12:37:12.543", "Id": "455241", "Score": "0", "body": "@Mast, they also changed the spec so that the code is now performing correctly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T12:41:24.557", "Id": "455242", "Score": "0", "body": "@pacmaninbw *sigh* fine." } ]
[ { "body": "<p>Ok, first things first, there are a couple of formatting points that would make your code a little nicer to read:</p>\n\n<ul>\n<li>Be consistent with your curly braces <code>{}</code>. In a couple of places, you have the opening brace on the same line as the thing before it whereas you don't in others.</li>\n<li>Be consistent with your naming too. I would name your stack <code>s</code> because it fits better with the camelCase used elsewhere.</li>\n<li>Spaces on your <code>#include &lt;header&gt;</code>s too please. It's just nitpicking but it's what most other programmers will be doing / used to.</li>\n</ul>\n\n<p>That aside, lets get into the body of the code itself:</p>\n\n<ul>\n<li><code>bool arePair(char, char)</code> is very verbose in it's definition. You could turn the entire function into a single boolean expression of the form:</li>\n</ul>\n\n<pre><code>return (start == '(' &amp;&amp; end == ')')\n || (start == '{' &amp;&amp; end == '}')\n || (start == '[' &amp;&amp; end == ']');\n</code></pre>\n\n<p>An alternative would be to use a switch statement:</p>\n\n<pre><code>switch (start) {\n\ncase '(': return end == ')';\ncase '{': return end == '}';\ncase '[': return end == ']';\n\ndefault:\n return false;\n}\n</code></pre>\n\n<p>What you choose is a matter of preference. I would probably go for the switch approach, however, because to me it is clearer what is intended.</p>\n\n<ul>\n<li><p><code>areParanthesesBalanced</code> is badly named. There is a typo in \"parentheses\" and parentheses refers specifically to () not {}, [] or &lt;>. <code>areBracketsBalanced</code> would be more appropriate.</p></li>\n<li><p>One idea would be to pass <code>const std::string&amp; exp</code> to the function rather than <code>std::string</code>. This prevents the program having to make a copy of the entire string in case you modify it.</p></li>\n<li><p>Your for loop <code>for (int i = 0; i &lt; exp.size(); i++) { ... }</code> never actually makes use of the value of <code>i</code>. Instead you could use a range for like this <code>for (char c : exp)</code> which just gives you each character in turn.</p></li>\n<li><p>Your <code>else</code> is unnecessary because you've already returned execution from the function at that point.</p></li>\n<li><p>The line <code>return s.empty() ? true : false;</code> is bad because <code>stack&lt;&gt;::empty()</code> returns a boolean! Therefore, just use <code>return s.empty();</code>.</p></li>\n</ul>\n\n<p>Overall this gives:</p>\n\n<pre><code>bool arePair(char start, char end)\n{\n switch (start) {\n\n case '(': return end == ')';\n case '{': return end == '}';\n case '[': return end == ']';\n\n default:\n return false;\n }\n}\n\nbool areBracketsBalanced(const std::string&amp; exp)\n{\n std::stack&lt;char&gt; s;\n for (char c : exp)\n {\n if (c == '(' || c == '{' || c == '[')\n s.push(c);\n else if (c == ')' || c == '}' || c == ']')\n {\n if (s.empty() || !arePair(s.top(), c))\n return false;\n s.pop();\n }\n }\n return s.empty();\n}\n</code></pre>\n\n<h2>But...</h2>\n\n<p>That covers a lot of smaller points but having constants defining your pairs of brackets in multiple places seems messy. Here's one possible solution but there might well be a nicer one I haven't thought of:</p>\n\n<pre><code>int isBracket(char c)\n{\n switch (c) {\n\n case '(': return 1;\n case ')': return -1;\n\n case '{': return 2;\n case '}': return -2;\n\n case '[': return 3;\n case ']': return -3;\n\n default:\n return 0;\n }\n}\n\nbool areBracketsBalanced(const std::string&amp; exp)\n{\n std::stack&lt;char&gt; s;\n for (char c : exp)\n {\n if (isBracket(c) &gt; 0) // Opening brackets\n s.push(c);\n else if (isBracket(c) &lt; 0) // Closing brackets\n {\n if (s.empty() || isBracket(s.top()) + isBracket(c))\n return false;\n s.pop();\n }\n }\n return s.empty();\n}\n</code></pre>\n\n<h2>Instead of printing fail...</h2>\n\n<p>You want to know the position of the failing bracket? Try changing the return type of <code>areBracketsBalanced</code> to <code>int</code>. You're already determining at what position it fails implicitly by returning false.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T12:53:33.250", "Id": "455243", "Score": "0", "body": "The case statement in the alternative arePair never returns true." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T14:32:05.487", "Id": "232946", "ParentId": "232937", "Score": "2" } } ]
{ "AcceptedAnswerId": "232946", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T10:59:25.387", "Id": "232937", "Score": "1", "Tags": [ "c++", "stack" ], "Title": "Syntax Checker C++ Data Structure - Stack" }
232937
<p><a href="https://projecteuler.net/problem=18" rel="noreferrer">Project Euler 18</a><br> <a href="https://projecteuler.net/problem=67" rel="noreferrer">Project Euler 67</a> </p> <p>As problem 67 is harder, I'll go with that one:</p> <blockquote> <p>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.</p> <pre><code> 3 7 4 2 4 6 8 5 9 3 </code></pre> <p>That is, 3 + 7 + 4 + 9 = 23.</p> <p>Find the maximum total from top to bottom in <a href="https://projecteuler.net/project/resources/p067_triangle.txt" rel="noreferrer">triangle.txt</a> (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.</p> <p>NOTE: This is a much more difficult version of Problem 18. It is not possible to try every route to solve this problem, as there are 2^99 altogether! If you could check one trillion (10^12) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)</p> </blockquote> <p>I solved this using dynamic programming. Here's my code:</p> <pre class="lang-py prettyprint-override"><code>def max_triangle_sum(triangle, height): if height == 1: return triangle[0][0] dp = [[-1] * row_index for row_index in range(1, height + 1)] dp[0][0] = triangle[0][0] for i in range(1, height): dp[i][0] = dp[i-1][0] + triangle[i][0] dp[i][i] = dp[i-1][i-1] + triangle[i][-1] for j in range(1, i): dp[i][j] = max(dp[i - 1][j - 1], dp[i - 1][j]) + triangle[i][j] return max(dp[-1]) if __name__ == '__main__': height = None while True: try: height = int(input('Please enter height of the triangle: ')) if height &lt;= 0: raise Exception('Height cannot be negative or 0') break except Exception as e: print(f'Error occurred: {e}') print() triangle = [] for row_index in range(1, height + 1): while True: try: row = list(map(int, input(f'Please enter {row_index} space seperated integer(s): ').split())) if len(row) != row_index: raise Exception(f'Exactly {row_index} numbers required') if any(number &lt; 0 for number in row): raise Exception(f'Numbers cannot be negative') triangle.append(row) break except Exception as e: print(f'Error occurred: {e}') print() print('The maximum triangle sum is: ') print(max_triangle_sum(triangle, height)) </code></pre> <p>This runs quite fast, considering it would actually take 20 billion years (<strong>If your computer can compute 10^12 operations in 1 second</strong>) to solve using brute force. But still, it doesn't look that good</p> <p>How do I improve this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T14:53:21.733", "Id": "455108", "Score": "3", "body": "Possibly helpful: [Project Euler # 67 Maximum path sum II (Bottom up) in Python](https://codereview.stackexchange.com/q/225248/35991)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T14:54:59.450", "Id": "455109", "Score": "0", "body": "@MartinR Yes, very much. Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T13:40:26.820", "Id": "455252", "Score": "0", "body": "I managed to solve this problem in reasonable time with a [Djikstra algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T13:43:43.857", "Id": "455254", "Score": "0", "body": "Yes, I know about Dijkstra's algorithm! Amazing idea! Can you please share you solution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T13:45:20.837", "Id": "455255", "Score": "0", "body": "@Srivaths I'll be happy to share it as soon as I can. It is on a computer that's currently being repaired..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T13:57:14.457", "Id": "455258", "Score": "0", "body": "@OlivierRoche Sure, No problem" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:21:08.103", "Id": "455262", "Score": "0", "body": "@Srivaths Meanwhile, I remembered that I did it as below, starting from the bottom of the triangle and computing maximum sum of heirs at each floor until I reached the top. Sorry for the loss of time..." } ]
[ { "body": "<h1>Don't raise generic exceptions</h1>\n\n<p>Avoid raising a generic Exception. To catch it, you'll have to catch all other more specific exceptions that subclass it.</p>\n\n<p>Instead of raising <code>Exception</code> directly when the user inputs a bad height, consider raising a <code>RuntimeError</code>, or in a larger codebase, a custom subclass. Then, explicitly list all of the exceptions you expect to be raised in your <code>except</code> clause, e.g. <code>TyperError</code> and <code>RuntimeError</code>.</p>\n\n<h1>Local variable names</h1>\n\n<p>The name <code>dp</code> isn't terribly informative as to what the list contains. Consider refactoring to something more descriptive.</p>\n\n<h1>Using globals in time-senstive code</h1>\n\n<p>Project Euler problems tend to require some fairly intensive computations. It may be advisable to try extract as much performance as possible inside of critical portions of you code, such as within nested loops.</p>\n\n<p>In your solution, all of the variables used after <code>if __name__ == '__main__'</code> are in fact <em>global variables</em>, which are <a href=\"https://stackoverflow.com/questions/11241523/why-does-python-code-run-faster-in-a-function?noredirect=1&amp;lq=1\">slower than local variables</a>. For a mild performance boost, consider refactoring all of this code into a <code>main</code> function, which you may then call after the <code>__main__</code> guard:</p>\n\n<pre><code>def main():\n height = None\n ...\n print('The maximum triangle sum is: ')\n print(max_triangle_sum(triangle, height))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<h1>Dummy values</h1>\n\n<p>You initially assign <code>height = None</code>, but there is no branch where <code>height</code> keeps that value. Therefore, it isn't <em>necessary</em> to initialize <code>height</code> at this time, since it is guaranteed to be given a value by the branches that follow. </p>\n\n<p>Some organization encourage initializing variables early on with dummy values so that developers can immediately see what variables will be in play in the code that follows. Others <em>discourage</em> this practice, since it can give developers a false sense of what values a variable is expected to take on (e.g. will height be <code>None</code> later?). Whether you choice to initialize variables early with dummy values largely comes down to stylistic preferences.</p>\n\n<h1>Documentation</h1>\n\n<p>You don't have any comments or docstrings in your code. These forms of documentation are extremely helpful for people who must read your code, which include both other developers as well you when you return to your code after working on another project for two months. Some basic conventions for writing docstrings are laid out in <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T15:27:05.017", "Id": "232950", "ParentId": "232944", "Score": "4" } }, { "body": "<h3>General</h3>\n\n<p>Since the problem gives the triangle as a text file, your program should probably be able to read that file. It would be quite a lot of work to input them manually, and when using the file like in <code>python triangle.py &lt; triangle.txt</code> a first row with the number of lines needs to be added. This reading function can be quite simple:</p>\n\n<pre><code>def read_triangle(file_name):\n with open(file_name) as f:\n return [list(map(int, line.split())) for line in f]\n</code></pre>\n\n<h3>Algorithm</h3>\n\n<p>As for the actual algorithm, I'm not quite sure what yours does. Which means that it is not very readable :). Not having any documentation, like a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\"><code>docstring</code></a> does not help either.</p>\n\n<p>The easiest algorithm for this is a bottom up approach that reduces each line into the maximum sum reachable from the line above it.</p>\n\n<pre><code>def reduce_rows(row, row_below):\n \"\"\"Reduces two consecutive rows to the maximum reachable sum from the top row.\"\"\"\n return [max(row_below[i], row_below[i+1]) + row[i] for i in range(len(row))]\n\ndef max_sum(triangle):\n \"\"\"Find the maximum sum reachable in the triangle.\"\"\"\n row_below = triangle.pop()\n for row in reversed(triangle):\n row_below = reduce_rows(row, row_below)\n # print(row_below)\n return row_below[0]\n\nif __name__ == \"__main__\":\n triangle = read_triangle(\"triangle.txt\")\n print(max_sum(triangle))\n</code></pre>\n\n<h3>Style</h3>\n\n<p>It's a good thing that you are already using a <code>if __name__ == \"__main__\":</code> guard. You also seem to be mostly following Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>. The only thing you could improve on that part is to reduce the number of blank lines. While some help the readability, parts that are logically connected should be in one block:</p>\n\n<pre><code>height = None\nwhile True:\n try:\n height = int(input('Please enter height of the triangle: '))\n if height &lt;= 0:\n raise Exception('Height cannot be negative or 0')\n break\n except Exception as e:\n print(f'Error occurred: {e}\\n')\n\ntriangle = []\nfor row_index in range(1, height + 1):\n while True:\n try:\n row = list(map(int, input(f'Please enter {row_index} space seperated integer(s): ').split()))\n if len(row) != row_index:\n raise Exception(f'Exactly {row_index} numbers required')\n elif any(number &lt; 0 for number in row):\n raise Exception(f'Numbers cannot be negative')\n else:\n triangle.append(row)\n break\n except Exception as e:\n print(f'Error occurred: {e}\\n')\n</code></pre>\n\n<p>I also put the separate exceptions and the happy path into an <code>if..elif..else</code> structure. This is not really needed (the other cases are never reachable if an exception is raised), but IMO it helps with readability. It also make it easier if at some point you decide that those should just print a message directly, instead of raising an exception that is immediately caught only to be printed. You could make those <code>print</code> statements directly, which would allow you to be more specific about the exception you expect. This makes it so that all other exceptions stop the program (as they should):</p>\n\n<pre><code>while True:\n try:\n height = int(input('Please enter height of the triangle: '))\n except ValueError as e:\n print(f'Error occurred: {e}\\n')\n if height &gt; 0:\n break\n else:\n print('Error occurred: Height cannot be negative or 0')\n\ntriangle = []\nfor row_index in range(1, height + 1):\n while True:\n try:\n row = list(map(int, input(f'Please enter {row_index} space separated integer(s): ').split()))\n except ValueError as e:\n print(f'Error occurred: {e}\\n')\n if len(row) != row_index:\n print(f'Error occurred: Exactly {row_index} numbers required')\n elif any(number &lt; 0 for number in row):\n print(f'Error occurred: Numbers cannot be negative')\n else:\n triangle.append(row)\n break\n</code></pre>\n\n<h3>Better user input</h3>\n\n<p>This is actually a good place to implement a function asking for user input and validating it. We need type validation and input validation here, so this should suffice:</p>\n\n<pre><code>def ask_user(message, type_=str, validate=None, non_valid_msg=\"\"):\n while True:\n try:\n user_input = type_(input(message))\n except ValueError as e:\n print(f\"Expected {type_}\")\n continue\n if validate is not None:\n if validate(user_input):\n return user_input\n else:\n print(non_valid_msg)\n else:\n return user_input\n</code></pre>\n\n<p>Which makes your code a lot easier:</p>\n\n<pre><code>def list_of_int(s):\n return list(map(int, s.split()))\n\nif __name__ == \"__main__\":\n height = ask_user(\"Please enter height of the triangle: \", int,\n lambda h: h &gt; 0, \"Height must be positive\")\n triangle = [ask_user(f\"Please enter {n} space separated integer(s): \", list_of_int,\n lambda l: len(l) == n, f\"Exactly {n} numbers required\")\n for n in range(1, height + 1)]\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T15:28:04.397", "Id": "232951", "ParentId": "232944", "Score": "6" } }, { "body": "<h2>Minor Cleanup</h2>\n\n<p>Contrary to @Graipher's opinion, I find your <code>max_triangle_sum</code> implementation is reasonably clear. Although, I'm not sure I'd refer to it as dynamic programming; it is simply computing top-down the maximum sums for each row.</p>\n\n<pre><code>dp = [[-1] * row_index for row_index in range(1, height + 1)]\n</code></pre>\n\n<p>What does <code>row_index</code> mean? It doesn't convey any meaning other than the index number of the row. <code>[-1] * row_index</code> is ... mysterious. <code>row_length</code> conveys meaning: it is length of the row, and <code>[-1] * row_length</code> tells the reader you have a row of <code>-1</code> values of a certain length.</p>\n\n<p>What is the <code>-1</code> mean? Where is it used? This statement creates a triangular data structure, with <code>-1</code> at each cell, but only to allocate the structure. The actual <code>-1</code> value is not used; it is unconditionally overwritten in the following code. If you have a mistake in the following code, it might use this <code>-1</code> value, and quietly produce erroneous results. If you used <code>None</code> instead of <code>-1</code>, if you ever accidentally used the value in a cell before it has been assigned, Python would raise an exception.</p>\n\n<pre><code>dp = [[None] * row_length for row_length in range(1, height + 1)]\n</code></pre>\n\n<p>Avoid negative indexing.</p>\n\n<pre><code> dp[i][i] = dp[i-1][i-1] + triangle[i][-1]\n</code></pre>\n\n<p>Here, <code>triangle[i][-1]</code> is referring to the last cell on the ith row. But the cells on the ith row from from <code>0</code> to <code>i</code>, so <code>triangle[i][-1]</code> simply means <code>triangle[i][i]</code>. You are already assigning to <code>dp[i][i]</code>, so this gives the statement a nice symmetry:</p>\n\n<pre><code> dp[i][i] = dp[i-1][i-1] + triangle[i][i]\n</code></pre>\n\n<p>You don't really need to pass <code>height</code> to <code>max_triangle_sum</code>: it can easily be computed as:</p>\n\n<pre><code> height = len(triangle)\n</code></pre>\n\n<h2>Space</h2>\n\n<p>Because you are allocating <code>dp</code> to hold the values of sum of the paths to each cell of each row of the triangle, your solution takes <span class=\"math-container\">\\$O(N^2)\\$</span> space to find the solution.</p>\n\n<p>Consider these statements:</p>\n\n<pre><code> dp[i][0] = dp[i-1][0] + triangle[i][0]\n dp[i][i] = dp[i-1][i-1] + triangle[i][-1]\n dp[i][j] = max(dp[i - 1][j - 1], dp[i - 1][j]) + triangle[i][j]\n</code></pre>\n\n<p><code>dp[i][...]</code> only depends upon values in <code>d[i - 1][...]</code>. This means you only need the previous <code>dp</code> row to compute the next <code>dp</code> row; you don't need the whole <code>dp</code> triangle structure, just two rows:</p>\n\n<pre><code> curr = [triangle[0][0]]\n\n for i in range(1, height):\n\n prev = curr\n curr = [None] * (i + 1)\n\n curr[0] = prev[0] + triangle[i][0]\n curr[i] = prev[i - 1] + triangle[i][i]\n\n for j in range(1, i):\n curr[j] = max(prev[j - 1], prev[j]) + triangle[i][j]\n</code></pre>\n\n<p>As a bonus, this should be faster, since less indexing is being performed.</p>\n\n<p>We've still got <code>triangle[i]</code> being indexed constantly. We can eliminate that by iterating over the rows of <code>triangle</code> directly. We'll use <code>enumerate()</code> so we keep the row index:</p>\n\n<pre><code> for i, row in enumerate(triangle[1:], 1):\n\n prev = curr\n curr = [None] * (i + 1)\n\n curr[0] = prev[0] + row[0]\n curr[i] = prev[i - 1] + row[i]\n\n for j in range(1, i):\n curr[j] = max(prev[j - 1], prev[j]) + row[j]\n</code></pre>\n\n<p>That's a little cleaner, and a little faster.</p>\n\n<p>Now the ugliest part having to handle the first and last value separately. The problem is there is no value before the first element, and no value after the last element to compute the <code>max()</code> on. But why isn't there? Or more to the point, why can't there be? If you padded the previous row with duplicated first and last values, you'd turn those special cases into the regular case of a value in the middle of the row:</p>\n\n<pre><code> for i, row in enumerate(triangle[1:], 1):\n\n prev = [curr[0]] + curr + [curr[-1]] # Duplicate first &amp; last values\n curr = [None] * (i + 1)\n\n for j in range(0, i + 1):\n curr[j] = max(prev[j], prev[j + 1]) + row[j]\n</code></pre>\n\n<p>Note: I've had to change <code>prev[j-1]</code> and <code>prev[j]</code> to <code>prev[j]</code> and <code>prev[j + 1]</code> to account for the changed indices, due to the duplicated value at the start.</p>\n\n<p>Now, we are filling in all the values of <code>curr</code> in a simple for loop. This screams list comprehension. No need to allocate the <code>curr</code> list ahead of time anymore.</p>\n\n<pre><code> for i, row in enumerate(triangle[1:], 1):\n\n prev = [curr[0]] + curr + [curr[-1]] # Duplicate first &amp; last values\n curr = [max(prev[j], prev[j + 1]) + row[j] for j in range(0, i + 1) ]\n</code></pre>\n\n<p>But we're still doing a lot of indexing. We've got <code>prev[j]</code>, and <code>row[j]</code> which are normalish indexes, and we've got <code>prev[j + 1]</code> which could be considered <code>adjusted_prev[j]</code> if we assigned <code>adjusted_prev</code> the values of <code>prev[1:]</code>. Then, with all the values being retrieved by a simple <code>[j]</code> index, we can let Python do the indexing for us but turning the indexing into iteration. Finally, since Python knows the number of values in the lists, we no longer need the <code>i</code> index:</p>\n\n<pre><code> for row in triangle[1:]:\n\n prev = [curr[0]] + curr + [curr[-1]] # Duplicate first &amp; last values\n curr = [max(a, b) + x for a, b, x in zip(prev[:-1], prev[1:], row) ]\n</code></pre>\n\n<p>Since <code>prev[:-1]</code> gives us all the values of the <code>curr</code> with the first value duplicated, and <code>prev[1:]</code> gives us all the values of <code>curr</code> with the last value duplicated, we don't even need <code>prev</code>:</p>\n\n<pre><code>def max_triangle_sum(triangle):\n\n curr = [triangle[0][0]]\n\n for row in triangle[1:]:\n curr = [max(a, b) + x for a, b, x in zip([curr[0]] + curr, curr + [curr[-1]], row)]\n\n return max(curr)\n</code></pre>\n\n<p>The space requirement (ignoring <code>triangle</code>) is now <span class=\"math-container\">\\$O(N)\\$</span>, since only the previous row needs to be held in memory while the current row is being computed.</p>\n\n<p>If it is guaranteed that the triangle only contains positive numbers, and since <code>max(0, x) == x</code> whenever <code>x</code> is positive, then instead of duplicating the first and last values, we could append and prepend a zero to each end. This will allow us to remove the first row as a special case:</p>\n\n<pre><code>def max_triangle_sum(triangle):\n\n curr = []\n zero = [0]\n\n for row in triangle:\n curr = [max(a, b) + x for a, b, x in zip(zero + curr, curr + zero, row)]\n\n return max(curr)\n</code></pre>\n\n<p>Now, <code>triangle</code> doesn't even need to be held in memory. Instead, an iterable object could be passed in, which could read the triangle in line by line on demand, further ensuring an <span class=\"math-container\">\\$O(N)\\$</span> memory solution.</p>\n\n<hr>\n\n<p>See other answers for great feedback on input sanitization, and reading the triangle data from a file.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T18:55:35.737", "Id": "232961", "ParentId": "232944", "Score": "5" } } ]
{ "AcceptedAnswerId": "232961", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T14:12:48.360", "Id": "232944", "Score": "6", "Tags": [ "python", "python-3.x", "programming-challenge", "dynamic-programming" ], "Title": "Minimum path sum in a triangle (Project Euler 18 and 67) with Python" }
232944
<p>I made a minesweeper game in c# as a method of studying, and right now its fully operational.</p> <p>I tried to use inheritance, recursion, and other fundamentals as clean as possible. Also I tried to use commenting as much as possible as I see many people do not do this, and it makes the code all the more confusing, both for the reader and the coder (at least for me).</p> <p>I tried my best to handle exceptions and anticipate possible problems, and I fixed any I could find. There was one exception however, it was a stack overflow exception, but it happened only one time and i couldn't reproduce it again to correct. If anyone can reproduce it and inform why and how, it will be much appreciated. </p> <p>If some part of code is missing, just let me know and i will add them as an edit.</p> <p>Thank you very much for your help.</p> <p>Form1.cs :</p> <pre><code>using MineSweeper.Properties; using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace MineSweeper { public partial class Form1 : Form { public Form1() { InitializeComponent(); } readonly string msgBoxTitle = "Warning"; List&lt;int&gt; panels = new List&lt;int&gt;(); int rowCount; int columnCount; private void ModifyMineField() { panels.Clear(); //clears the array in case user will make a new field MineFieldTable.RowStyles.Clear(); //resets the table MineFieldTable.ColumnStyles.Clear(); //resets the table MineFieldTable.Controls.Clear(); //resets the table MineFieldTable.Visible = false; rowCount = Convert.ToInt32(TB_tableDimension1.Text); //take rowCount from user input columnCount = Convert.ToInt32(TB_tableDimension2.Text); //take columnCount from user input int mineCount = Convert.ToInt32(TB_mineCount.Text); //amount of mines, decided by user MineFieldTable.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single; MineFieldTable.AutoSize = true; MineFieldTable.RowCount = rowCount; MineFieldTable.ColumnCount = columnCount; Random rnd = new Random(); int counter = 0; int[] panelArray = new int[rowCount * columnCount]; //track the panel layout, 0= empty, 1=mine, 2=opened for (int i = 0; i &lt; panelArray.Length; i++) //populate the array with empty land, to be re-designated later { panelArray[i] = 0; } while (counter &lt; mineCount) //creating mine coordinates by array numbering { int a = rnd.Next(0, rowCount * columnCount - 1); if (panelArray[a] != 1) { panelArray[a] = 1; counter++; } } panels.AddRange(panelArray); for (int i = 0; i &lt; MineFieldTable.RowCount; i++) //generating row styles { MineFieldTable.RowStyles.Add(new RowStyle(SizeType.Absolute, 30f)); } for (int i = 0; i &lt; MineFieldTable.ColumnCount; i++) //generating column styles { MineFieldTable.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 30f)); } for (int i = 0; i &lt; rowCount * columnCount; i++) //lay the field with mines or not { if (panels[i] != 1) //add empty land { NoFocusButton emptyLand = new NoFocusButton("", FlatStyle.Standard, 0) { }; emptyLand.MouseUp += Land_Click; MineFieldTable.Controls.Add(emptyLand); } if (panels[i] == 1) //add mines { NoFocusButton mine = new NoFocusButton("", FlatStyle.Standard, 1) { }; mine.MouseUp += Land_Click; MineFieldTable.Controls.Add(mine); } } MineFieldTable.Visible = true; //to make field generation quicker, first invisible, then visible } private void BtnCreate_Click(object sender, EventArgs e) { if ( //check if user entered correct parameters int.TryParse(TB_mineCount.Text, out _) == false || int.TryParse(TB_tableDimension1.Text, out _) == false || int.TryParse(TB_tableDimension2.Text, out _) == false || Convert.ToInt32(TB_mineCount.Text) &lt; 1 || Convert.ToInt32(TB_tableDimension1.Text) &lt; 1 || Convert.ToInt32(TB_tableDimension1.Text) &gt; 30 || Convert.ToInt32(TB_tableDimension2.Text) &lt; 1 || Convert.ToInt32(TB_tableDimension2.Text) &gt; 30 || Convert.ToInt32(TB_mineCount.Text) &gt; Convert.ToInt32(TB_tableDimension1.Text) * Convert.ToInt32(TB_tableDimension2.Text)) { MessageBox.Show("Please enter valid values, and consider the following: \n \n-Field cannot be bigger than 30x30.\n \n-Mines cannot be more than the field size.", msgBoxTitle); } else { try { MineFieldTable.Visible = false; ModifyMineField(); } catch (Exception ex) { MessageBox.Show(ex.Message, msgBoxTitle); } } } private void Land_Click(object sender, MouseEventArgs e) { TableLayoutPanelCellPosition clickCoords = MineFieldTable.GetPositionFromControl((Control)sender); //obtaining coordinates of control NoFocusButton currentControl = MineFieldTable.GetControlFromPosition(clickCoords.Column, clickCoords.Row) as NoFocusButton; //the current control, obtained from coords if (e.Button == MouseButtons.Left &amp; currentControl.Text != ".") { if (panels[clickCoords.Column + (clickCoords.Row) * columnCount] == 0) //if the clicked land is empty land { currentControl.LandOpening(clickCoords.Row, clickCoords.Column, MineFieldTable, panels); } if (panels[clickCoords.Column + (clickCoords.Row) * columnCount] == 1) //stepped on a mine! { NoFocusButton currentButton = MineFieldTable.GetControlFromPosition(clickCoords.Column, clickCoords.Row) as NoFocusButton; currentButton.BackgroundImage = Resources.mineExplode; currentButton.Text = ""; currentButton.FlatStyle = FlatStyle.Flat; NoFocusButton currentButton2; //other panels on the land other than the stepped panel for (int i = 0; i &lt; panels.Count; i++) { if (panels[i] == 1) { int row = i / columnCount; int column = i % columnCount; currentButton2 = MineFieldTable.GetControlFromPosition(column, row) as NoFocusButton; if (clickCoords.Row != row | clickCoords.Column != column) //in order to not replace the red mine { currentButton2.FlatStyle = FlatStyle.Flat; currentButton2.BackgroundImage = Resources.mine; } if (currentButton2.Text == ".") //if mine was flagged, show it as green { currentButton2.FlatStyle = FlatStyle.Flat; currentButton2.Image = null; currentButton2.BackgroundImage = Resources.mineGreen; } } if (panels[i] != 1) { int row = i / columnCount; int column = i % columnCount; currentButton2 = MineFieldTable.GetControlFromPosition(column, row) as NoFocusButton; if (currentButton2.Text == ".") //if a flag was placed wrong, indicate that it was wrong { currentButton2.Image = null; currentButton2.Text = ""; currentButton2.Image = Resources.flag2crossed; } } } MessageBox.Show("You lost the game!", "Game Over"); MineFieldTable.Visible = false; MineFieldTable.Controls.Clear(); } } if (e.Button == MouseButtons.Right) //flagging land where suspected to be mines { if (currentControl.Text == "") //place flag { currentControl.Image = Resources.flag2; currentControl.Text = "."; currentControl.ForeColor = Color.Gray; } else if (currentControl.Text == ".") //remove flag { currentControl.Image = null; currentControl.Text = ""; } } if (panels.Contains(0) == false) //if all mines are revealed, finish the game { for (int i = 0; i &lt; panels.Count; i++) { if (panels[i] == 1) { int row = i / columnCount; int column = i % columnCount; NoFocusButton currentButton2 = MineFieldTable.GetControlFromPosition(column, row) as NoFocusButton; if (currentButton2.Text == ".") //if mine was flagged, show it as green { currentButton2.FlatStyle = FlatStyle.Flat; currentButton2.Image = null; currentButton2.BackgroundImage = Resources.mineGreen; } if (currentButton2.Text != ".") //if mine was not flagged, show as usual { currentButton2.FlatStyle = FlatStyle.Flat; currentButton2.BackgroundImage = Resources.mine; } } } MessageBox.Show("You won the game!", "Game Over"); MineFieldTable.Visible = false; MineFieldTable.Controls.Clear(); } } } } </code></pre> <p>NoFocusButton.cs (a custom class for buttons) :</p> <pre><code>using MineSweeper.Properties; using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace MineSweeper { class NoFocusButton : Button { public NoFocusButton(string text, FlatStyle flatstyle, int indexnumber) { SetStyle(ControlStyles.Selectable, false); Text = text; TextAlign = ContentAlignment.MiddleCenter; Margin = new Padding(0); Padding = new Padding(0); Dock = DockStyle.Fill; FlatStyle = flatstyle; FlatAppearance.BorderSize = 0; } public void LandOpening(int coordinateX, int coordinateY, TableLayoutPanel table, List&lt;int&gt; panelArray) //if the opened land is empty, do this { for (int i = -1; i &lt; 2; i++) { for (int j = -1; j &lt; 2; j++) { try { int a = coordinateY + j; int b = coordinateX + i; //coordinates of the current control if (a &gt; -1 &amp;&amp; b &gt; -1 &amp;&amp; a &lt; table.ColumnCount &amp;&amp; b &lt; table.RowCount) //to confirm if the control index is not out of bounds { NoFocusButton currentButton = table.GetControlFromPosition(a, b) as NoFocusButton; if (panelArray[a + b * table.ColumnCount] == 0) //if the nearby land is empty, write the mine count on that land { int nearbyMines = 0; for (int k = -1; k &lt; 2; k++) //to determine minecount near opened land and write it { for (int l = -1; l &lt; 2; l++) { int d = coordinateY + j + k; int e = coordinateX + i + l; //to shorten future code if (d &gt; -1 &amp;&amp; e &gt; -1 &amp;&amp; d &lt; table.ColumnCount &amp;&amp; e &lt; table.RowCount) //to confirm if the control index is not out of bounds { NoFocusButton openingButton = table.GetControlFromPosition(d, e) as NoFocusButton; bool c = int.TryParse(openingButton.Text, out int n); //to shorten future code if (panelArray[d + e * table.ColumnCount] == 1 &amp;&amp; c == false) //to check if cell has number inside { nearbyMines++; } } } } if (a &gt;= 0 &amp;&amp; b &gt;= 0 &amp;&amp; a &lt;= table.ColumnCount &amp;&amp; b &lt;= table.RowCount) //to confirm if the control index is not out of bounds { NoFocusButton x = table.GetControlFromPosition(a, b) as NoFocusButton; if (nearbyMines != 0 &amp; x.Text !=".") //dont write 0 mines { x.Text = nearbyMines.ToString(); } if (x.Text != ".") { x.FlatStyle = FlatStyle.Flat; x.Enabled = false; panelArray[a + b * table.ColumnCount] = 2; //mark this panel in the array as opened } } if (nearbyMines == 0) //using recursion to open more area if there is a panel with zero at the border of opened area { LandOpening(b, a, table, panelArray); } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } } } </code></pre> <p>Form1.Designer.cs :</p> <pre><code>namespace MineSweeper { partial class Form1 { /// &lt;summary&gt; /// Required designer variable. /// &lt;/summary&gt; private System.ComponentModel.IContainer components = null; /// &lt;summary&gt; /// Clean up any resources being used. /// &lt;/summary&gt; /// &lt;param name="disposing"&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt; protected override void Dispose(bool disposing) { if (disposing &amp;&amp; (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// &lt;summary&gt; /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// &lt;/summary&gt; private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.TB_tableDimension1 = new System.Windows.Forms.TextBox(); this.TB_tableDimension2 = new System.Windows.Forms.TextBox(); this.BtnCreate = new System.Windows.Forms.Button(); this.MineFieldTable = new System.Windows.Forms.TableLayoutPanel(); this.TB_mineCount = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // TB_tableDimension1 // this.TB_tableDimension1.Location = new System.Drawing.Point(20, 25); this.TB_tableDimension1.MaxLength = 2; this.TB_tableDimension1.Name = "TB_tableDimension1"; this.TB_tableDimension1.Size = new System.Drawing.Size(20, 20); this.TB_tableDimension1.TabIndex = 2; this.TB_tableDimension1.Text = "10"; // // TB_tableDimension2 // this.TB_tableDimension2.Location = new System.Drawing.Point(50, 25); this.TB_tableDimension2.MaxLength = 2; this.TB_tableDimension2.Name = "TB_tableDimension2"; this.TB_tableDimension2.Size = new System.Drawing.Size(20, 20); this.TB_tableDimension2.TabIndex = 3; this.TB_tableDimension2.Text = "10"; // // BtnCreate // this.BtnCreate.Location = new System.Drawing.Point(160, 25); this.BtnCreate.Name = "BtnCreate"; this.BtnCreate.Size = new System.Drawing.Size(75, 20); this.BtnCreate.TabIndex = 1; this.BtnCreate.Text = "CREATE"; this.BtnCreate.UseVisualStyleBackColor = true; this.BtnCreate.Click += new System.EventHandler(this.BtnCreate_Click); // // MineFieldTable // this.MineFieldTable.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.MineFieldTable.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single; this.MineFieldTable.ColumnCount = 10; this.MineFieldTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this.MineFieldTable.Location = new System.Drawing.Point(20, 50); this.MineFieldTable.Margin = new System.Windows.Forms.Padding(0); this.MineFieldTable.Name = "MineFieldTable"; this.MineFieldTable.RowCount = 10; this.MineFieldTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.MineFieldTable.Size = new System.Drawing.Size(210, 210); this.MineFieldTable.TabIndex = 4; this.MineFieldTable.Visible = false; // // TB_mineCount // this.TB_mineCount.Location = new System.Drawing.Point(100, 25); this.TB_mineCount.MaxLength = 3; this.TB_mineCount.Name = "TB_mineCount"; this.TB_mineCount.Size = new System.Drawing.Size(25, 20); this.TB_mineCount.TabIndex = 4; this.TB_mineCount.Text = "10"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(70, 28); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(27, 13); this.label2.TabIndex = 6; this.label2.Text = "Size"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(125, 28); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(35, 13); this.label3.TabIndex = 7; this.label3.Text = "Mines"; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 6F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(40, 31); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(10, 9); this.label1.TabIndex = 8; this.label1.Text = "X"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScroll = true; this.AutoSize = true; this.ClientSize = new System.Drawing.Size(284, 261); this.Controls.Add(this.label1); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.TB_mineCount); this.Controls.Add(this.MineFieldTable); this.Controls.Add(this.BtnCreate); this.Controls.Add(this.TB_tableDimension2); this.Controls.Add(this.TB_tableDimension1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Form1"; this.Padding = new System.Windows.Forms.Padding(0, 0, 20, 20); this.Text = "MineSweeper by MHS"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox TB_tableDimension1; private System.Windows.Forms.TextBox TB_tableDimension2; private System.Windows.Forms.Button BtnCreate; private System.Windows.Forms.TableLayoutPanel MineFieldTable; private System.Windows.Forms.TextBox TB_mineCount; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label1; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T19:28:30.330", "Id": "455155", "Score": "2", "body": "You should have a board class that represents the logical board, which is (mostly) an multidimensional array of panels. Don't mix you game logic with your UI controls. You should be able to lift your \"board\" class and game logic out and use it without any modifications in a MVC web application, or winforms, or WPF, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T19:37:15.310", "Id": "455156", "Score": "1", "body": "Then you can either have each panel have a list of neighbors precalculated at board creation time (quickest at runtime, but more slightly more memory), or have the board class have a method that will return a list of neighbors for any given panel." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:36:23.773", "Id": "455270", "Score": "0", "body": "It's very impressive you were able to get this to work with brute force. Implementing correct minesweeper behavior is a deceptively difficult task. My main suggestion to you is the separate all the \"engine\" logic from the UI. To see what I mean, take a look at my minesweeper library which excludes the UI, but does include a suite of tests. https://github.com/bradmarder/MSEngine" } ]
[ { "body": "<p>This isn't object-oriented code. In fact the only difference between this implementation and a VBA macro popping up a modal <code>UserForm</code> that completely runs the show, is the language and framework involved: this anti-pattern has a name, and that's \"<strong>Smart UI</strong>\".</p>\n\n<p>The biggest problem with it, is that the entire game logic is completely intertwined with UI concerns, which means none of the game logic can be unit-tested.</p>\n\n<hr>\n\n<h3>Form1.Designer.cs</h3>\n\n<p>Being a designer-generated code file, none of this code should be manually edited, and could have been omitted. The nice thing about including it, is that it becomes reviewable code, because we get to see what you've named all the controls.</p>\n\n<p>I like that you've given a meaningful name to the <code>MineFieldTable</code> layout panel, but these also deserve a meaningful name:</p>\n\n<pre><code>this.Name = \"Form1\";\nprivate System.Windows.Forms.TextBox TB_tableDimension1;\nprivate System.Windows.Forms.TextBox TB_tableDimension2;\nprivate System.Windows.Forms.Label label2;\nprivate System.Windows.Forms.Label label3;\nprivate System.Windows.Forms.Label label1;\n</code></pre>\n\n<p>The last thing you want to see in your form's code-behind, is stuff like <code>label2</code> and <code>TB_tableDimension1</code> - it says nothing about what the purpose of <code>label2</code> is, and leaves the reader assuming. You seem to want to use some Hungarian Notation prefixing scheme (<code>Button</code> -> <code>Btn</code>; <code>TextBox</code> -> <code>TB_</code>), but the scheme is not consistent (where's the type prefix for the <code>MineFieldTable</code>? Why does <code>TB_</code> have an underscore, but not <code>Btn</code>? Why is <code>TB</code> all-caps, but <code>Btn</code> is <code>PascalCase</code>?)... make your life simpler and drop this prefixing habit.</p>\n\n<p>Consider using a fully spelled-out postfix instead:</p>\n\n<ul>\n<li><code>TableHeightBox</code> vs <code>TB_tableDimension1</code></li>\n<li><code>TableWidthBox</code> vs <code>TB_tableDimension2</code></li>\n<li><code>CreateButton</code> vs <code>BtnCreate</code></li>\n<li><code>MineFieldPanel</code> vs <code>MineFieldTable</code></li>\n<li><code>MineCountBox</code> vs <code>TB_mineCount</code></li>\n<li><code>MinesLabel</code> vs <code>label3</code></li>\n<li><code>GridSizeLabel</code> vs <code>label2</code></li>\n<li><code>WhateverThatIsLabel</code> vs <code>label1</code> (why is there a label with just an \"X\" in it anyway?)</li>\n</ul>\n\n<hr>\n\n<h3>Form1.cs</h3>\n\n<p>As mentioned above, the form is doing way, way too many things. In object-oriented code, I would expect the form's code-behind to interact with the game state. Here, the form's controls <em>are</em> the game state.</p>\n\n<p>You will want to heavily refactor everything in here, and pull most of the logic into other classes - and to achieve this, you'll need to actually <em>model</em> the game state, so that the code that's responsible for evaluating game state doesn't need to care for buttons and textboxes.</p>\n\n<p>The first thing I would expect in a Minesweeper-type game, is a class that respresents a grid position and its state.</p>\n\n<p>This is your game state:</p>\n\n<pre><code>int[] panelArray = new int[rowCount * columnCount]; //track the panel layout, 0= empty, 1=mine, 2=opened\n</code></pre>\n\n<p>..but it's local to the method creating the controls/grid, nothing else can access it!</p>\n\n<p>You see the problem with intertwined game and UI logic, is that...</p>\n\n<blockquote>\n<pre><code> if (currentButton2.Text != \".\") //if mine was not flagged, show as usual\n {\n currentButton2.FlatStyle = FlatStyle.Flat;\n currentButton2.BackgroundImage = Resources.mine;\n }\n</code></pre>\n</blockquote>\n\n<p>...game state should be pulled from your <em>model</em>, not from the controls on the form!</p>\n\n<hr>\n\n<h3>NoFocusButton.cs</h3>\n\n<p>These nested loops are very scary, and the single-character loop variable names make them very hard to follow. <code>LandOpening</code> is a poor name for such an important method - you want method names that start with a verb, and that describe what they do / what their purpose is. The domain-specifics aren't clear. What's a \"land\" and why does it \"open\"?</p>\n\n<p>You want the game state to be well-defined <code>enum</code> values, not hard-coded <code>1</code>/<code>0</code>/<code>-1</code> integer literals; you want the underlying value of these <code>enum</code> states to be irrelevant (so, no looping from <code>-1</code> to <code>&lt;2</code>); you want <em>meaningful names</em> for every identifier: <code>i</code>, <code>j</code>, <code>k</code>, <code>a</code>, <code>d</code>, ...there's just too many of them - note that the lowercase <code>L</code>/<code>l</code> is the most evil of all (looks way too much like a <code>1</code> at a glance).</p>\n\n<p>Rule of thumb, if you're looking at a 4-level nested loop structure with conditionals and recursive calls, you're in a bad place called Spaghetti Land - that elusive stack overflow exception is definitely caused by the recursive logic you have there.</p>\n\n<p>Recursion and loops are, most often, different tools for solving the same problem: recursive logic can be expressed with a loop, and a loop can be expressed with recursive logic. Mixing the two makes the code a mind-bender that becomes very hard to follow.</p>\n\n<hr>\n\n<h2>Object Oriented</h2>\n\n<p>As <a href=\"https://codereview.stackexchange.com/questions/232947/minesweeper-implementation-c-winforms#comment455155_232947\">Robert mentioned</a>, the first thing to do when you want to write object-oriented code isn't to think of a UI, but of how you're going to model the game components.</p>\n\n<p>You want a <code>GameBoard</code> (or <code>MineField</code>) object responsible for encapsulating the game state; you want that object to have methods like <code>Clear</code> and <code>Initialize(int width, int height, int mines)</code>, you want a <code>MineFieldCell</code> object that can hold <code>CellState</code> and <code>VisibleState</code> values - running the <code>Initialize</code> method would create that <code>width*height</code> <code>MineFieldCell</code> objects with <code>VisibleState = VisibleState.Masked</code> and <code>CellState = CellState.Mine</code> or <code>CellState = CellState.Safe</code>, so you'd need an <code>enum CellState</code> type with <code>Mine</code> and <code>Safe</code> (or <code>NoMine</code>.. whatever), and an <code>enum VisibleState</code> type with <code>Masked</code>, <code>Flagged</code> and <code>Exposed</code> values; you'll want a <code>MineFieldCell</code> to expose an integer property representing the number of adjacent mines that the UI will read from when the <code>VisibleState</code> is <code>VisibleState.Exposed</code> (can be computed up-front, on on-the-fly)... and then you'll want unit tests that validate that all this logic works as intended - and all of that can (and <em>should</em>) happen <strong>before</strong> you wire any of it up to any UI.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T20:45:41.037", "Id": "232967", "ParentId": "232947", "Score": "5" } } ]
{ "AcceptedAnswerId": "232967", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T14:53:23.513", "Id": "232947", "Score": "7", "Tags": [ "c#", "object-oriented", "game", "winforms", "minesweeper" ], "Title": "Minesweeper Implementation c# winforms" }
232947
<p><strong>I'm currently modifying a research project</strong> (massive test and benchmark of diverse conjectures to try and eventually solve the <a href="http://garden.irmacs.sfu.ca/op/monochromatoc_reachability_in_arc_colored_digraphs" rel="nofollow noreferrer">SSW conjecture</a>) <strong>so that it can run on a big HPC architecture</strong>, which does not handle most of the 'classic' multi-process/multi-thread methods (like fork-based in C, python <a href="https://docs.python.org/3.5/library/multiprocessing.html" rel="nofollow noreferrer">multiprocessing</a> module, or multi-threading libraries). </p> <p>So <strong>I have to go for an <a href="https://www.open-mpi.org/" rel="nofollow noreferrer">OpenMPI</a> based implementation</strong>. </p> <p><strong>I need advice on the manager/worker pattern, and on the 'good and legit' way to use open MPI, good practices included.</strong> I'm also taking advices on coding style and the likes, but it's not the main issue here (academic lab coding style :-) ). </p> <p>The rest of the code (the actual jobs to perform) are working fine, benchmarked, tested, and ... confidential. So <strong>here is a toy case, where a job will consist in printing an integer, sleeping for a short time span, and returning no piece of information to the manager</strong>. Error managing for workers is also handled at worker level, so we don't need to really care about it here. </p> <p>The principle is the following: <strong>I have a 'manager' which sends jobs to perform to a number of workers</strong> (a few thousands in my case). <strong>Each worker is totally independent</strong>, and does not need to return any information to its manager. Workers errors are handled in the workers code. </p> <p>Here is my toy program: </p> <pre><code>/* file: test_mpi.c */ #include &lt;mpi.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;stdbool.h&gt; #define KEEP_WORKING 0 #define NO_MORE_JOBS 1 #define READY_TO_WORK 2 #define WORKER_NOT_AVAILABLE -1 #define MANAGER_RANK 0 #define NB_JOBS 8 int get_rank_from_ready_worker() { MPI_Status status; int worker_useless_msg; MPI_Recv(&amp;worker_useless_msg, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &amp;status); if (status.MPI_TAG == READY_TO_WORK) { return status.MPI_SOURCE; } else { return WORKER_NOT_AVAILABLE; } } void send_job_to_worker(int job, int worker_rank) { MPI_Send(&amp;job, 1, MPI_INT, worker_rank, KEEP_WORKING, MPI_COMM_WORLD); } void signal_to_manager_that_ready() { int empty_msg = 0; MPI_Send(&amp;empty_msg, 1, MPI_INT, MANAGER_RANK, READY_TO_WORK, MPI_COMM_WORLD); } void do_job(int job, int my_rank) { unsigned int sleep_time = 1 + ((rand() + job) % 4); sleep(sleep_time); printf("[%d] performed job %d\n", my_rank, job); } bool receive_job_from_manager(int my_rank) { int job; MPI_Status status; MPI_Recv(&amp;job, 1, MPI_INT, MANAGER_RANK, MPI_ANY_TAG, MPI_COMM_WORLD, &amp;status); if (status.MPI_TAG == KEEP_WORKING) { /* received a job to perform */ do_job(job, my_rank); /* tell manager that it's ready to perform a new job */ signal_to_manager_that_ready(); return true; } else if (status.MPI_TAG == NO_MORE_JOBS) { /* work is over ! */ return false; } else { /* this should not happen */ return false; } } void terminate_worker(int worker_rank) { int empty_job = 0; MPI_Send(&amp;empty_job, 1, MPI_INT, worker_rank, NO_MORE_JOBS, MPI_COMM_WORLD); } int main(int argc, char** argv) { /* init MPI environment */ MPI_Init(&amp;argc, &amp;argv); /* Find out rank, size */ int world_rank, world_size; MPI_Comm_rank(MPI_COMM_WORLD, &amp;world_rank); MPI_Comm_size(MPI_COMM_WORLD, &amp;world_size); /* Check that we have at least one manager &amp; one worker */ if (world_size &lt; 2) { fprintf(stderr, "World size must be greater than 1 for %s\n", argv[0]); MPI_Abort(MPI_COMM_WORLD, 1); } if (world_rank == MANAGER_RANK) { /* manager part */ /* create 'jobs'*/ int jobs[NB_JOBS]; for (int i = 0; i &lt; NB_JOBS; i++) { jobs[i] = i; } int job_to_send = 0, worker_rank; do { /* manager main loop: sending jobs to ready workers */ worker_rank = get_rank_from_ready_worker(); if (worker_rank != WORKER_NOT_AVAILABLE) { send_job_to_worker(jobs[job_to_send], worker_rank); job_to_send ++; } } while (job_to_send &lt; NB_JOBS); /* All jobs done -&gt; terminating workers */ for (int nb_terminated = 0; nb_terminated &lt; world_size-1; nb_terminated++) { terminate_worker(get_rank_from_ready_worker()); } } else { /* worker part */ /* signal to manager that it's ready to work */ signal_to_manager_that_ready(); /* start working loop */ bool keep_working; do { keep_working = receive_job_from_manager(world_rank); } while (keep_working); } MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); return 0; } </code></pre> <p>To compile and run (on unix):</p> <pre><code>mpicc test_mpi.c -o test_mpi -Wall -Wextra mpirun -n 4 ./test_mpi </code></pre> <p>Note that to compile and run this code, Open MPI needs to be installed on the machine.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T12:32:13.210", "Id": "455240", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>Small review</p>\n\n<p><strong>Potential bug</strong></p>\n\n<p><code>rand() + job</code> can overflow leading to <em>undefined behavior</em>. Possible then that <code>1 + ((rand() + job) % 4)</code> is a negative number and code sleeps for a <em>long</em> time.</p>\n\n<p>e.g. <code>rand() + job</code> --> <code>INT_MAX + 2</code> --> <code>-INT_MAX</code> and <code>(-INT_MAX) % 4</code> --> -3. <code>-3 + 1</code> --> <code>unsigned int sleep_time</code> is <code>UINT_MAX -1</code>. Sleep maybe 136 year, longer than old <a href=\"https://en.wikipedia.org/wiki/Rip_Van_Winkle\" rel=\"nofollow noreferrer\">Rip</a>.</p>\n\n<p>Avoid signed integer overflow. Consider unsigned math.</p>\n\n<pre><code>// unsigned int sleep_time = 1 + ((rand() + job) % 4);\nunsigned int sleep_time = 1 + ((0u + rand() + job) % 4);\nsleep(sleep_time);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T12:21:38.010", "Id": "455239", "Score": "2", "body": "Thanks for spotting it :-) Even if it is not going to be part of the code that will run on the big machines, I always like to see how easy it is to create potentially catastrophic bugs in C (and this one would go undetected for a long long time, with such a low probability of being triggered). I'd give a second +1 for the reference to rip but unfortunately I can't." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T03:54:46.100", "Id": "232978", "ParentId": "232954", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T16:40:02.687", "Id": "232954", "Score": "4", "Tags": [ "c", "mpi" ], "Title": "Open MPI: simple manager/workers pattern in C" }
232954
<blockquote> <p>Followed-up <a href="https://codereview.stackexchange.com/questions/233431/less-incomplete-z80-emulator-written-in-c">here</a>.</p> </blockquote> <p>I've written a partial z80 emulator in C++. It has a decent part of the instructions that can be reused implemented but I've had some issues with duplicated code.</p> <p>I'd also like to note that this is my first C++ project; before that I've primarily dealt with C and Assembly.</p> <p><code>emulate.cpp</code>:</p> <pre><code>#include &lt;stdexcept&gt; #include "z80emu.hpp" #include "opcodes.h" #ifndef NDEBUG # include &lt;iostream&gt; using std::cout; using std::endl; #endif namespace z80emu { // return value: number of instructions executed uint16_t z80::emulate() { reg *rp[] = { &amp;regs.bc, &amp;regs.de, &amp;regs.hl, &amp;regs.sp }; reg *rp2[] = { &amp;regs.bc, &amp;regs.de, &amp;regs.hl, &amp;regs.af }; uint16_t inst = 0; for(;;) { switch(mem[regs.pc]) { case NOP: break; case LD_BC_IMM: case LD_DE_IMM: case LD_HL_IMM: case LD_SP_IMM: ld16imm(mem[regs.pc] &gt;&gt; 4, rp); break; case LD_DBC_A: case LD_DDE_A: deref16_u8(mem[regs.pc] &gt;&gt; 4, rp) = regs.af.high; break; case INC_BC: case INC_DE: case INC_HL: case INC_SP: inc16(mem[regs.pc] &gt;&gt; 4, rp); break; case DEC_BC: case DEC_DE: case DEC_HL: case DEC_SP: dec16(mem[regs.pc] &gt;&gt; 4, rp); break; case INC_B: case INC_C: case INC_D: case INC_E: case INC_H: case INC_L: inc8(mem[regs.pc], rp); break; case DEC_B: case DEC_C: case DEC_D: case DEC_E: case DEC_H: case DEC_L: dec8(mem[regs.pc], rp); break; case LD_B_IMM: case LD_C_IMM: case LD_D_IMM: case LD_E_IMM: case LD_H_IMM: case LD_L_IMM: ld8imm(mem[regs.pc], rp); break; case RRCA: rrc8(mem[regs.pc], rp); break; case EX_AF_AF: regs.af.exchange(); break; case ADD_HL_BC: case ADD_HL_DE: case ADD_HL_HL: case ADD_HL_SP: regs.hl.combined += rp[mem[regs.pc] &gt;&gt; 4]-&gt;combined; regs.hl.uncombine(); break; case LD_A_DBC: case LD_A_DDE: regs.af.high = deref16_u8(mem[regs.pc] &gt;&gt; 4, rp); regs.af.combine(); break; default: #ifndef NDEBUG cout &lt;&lt; std::hex &lt;&lt; std::showbase &lt;&lt; "af: " &lt;&lt; regs.af.combined &lt;&lt; endl &lt;&lt; "af': " &lt;&lt; regs.af.exx &lt;&lt; endl &lt;&lt; "bc: " &lt;&lt; regs.bc.combined &lt;&lt; endl &lt;&lt; "bc': " &lt;&lt; regs.bc.exx &lt;&lt; endl &lt;&lt; "de: " &lt;&lt; regs.de.combined &lt;&lt; endl &lt;&lt; "de': " &lt;&lt; regs.de.exx &lt;&lt; endl &lt;&lt; "hl: " &lt;&lt; regs.hl.combined &lt;&lt; endl &lt;&lt; "hl': " &lt;&lt; regs.hl.exx &lt;&lt; endl &lt;&lt; "sp: " &lt;&lt; regs.sp.combined &lt;&lt; endl &lt;&lt; "a: " &lt;&lt; +regs.af.high &lt;&lt; endl &lt;&lt; "f: " &lt;&lt; +regs.af.low &lt;&lt; endl &lt;&lt; "b: " &lt;&lt; +regs.bc.high &lt;&lt; endl &lt;&lt; "c: " &lt;&lt; +regs.bc.low &lt;&lt; endl &lt;&lt; "d: " &lt;&lt; +regs.de.high &lt;&lt; endl &lt;&lt; "e: " &lt;&lt; +regs.de.low &lt;&lt; endl &lt;&lt; "h: " &lt;&lt; +regs.hl.high &lt;&lt; endl &lt;&lt; "l: " &lt;&lt; +regs.hl.low &lt;&lt; endl; #endif throw std::logic_error("Unimplemented opcode!"); } regs.pc++; inst++; } return inst; } } </code></pre> <p><code>main.cpp</code>:</p> <pre><code>#include &lt;cerrno&gt; #include &lt;cstdlib&gt; #include &lt;cstring&gt; #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;exception&gt; #include "z80emu.hpp" void usage(const char *prog_name); int main(int argc, const char **argv) { z80emu::z80 z80; std::ifstream infile; uint16_t file_size; if((unsigned)argc - 2 &gt; 0) { usage(argv[0]); return EXIT_FAILURE; } infile.open(argv[1], std::ifstream::in | std::ifstream::binary); if(!infile.good()) { std::cerr &lt;&lt; "Opening " &lt;&lt; argv[1] &lt;&lt; " failed: " &lt;&lt; std::strerror(errno) &lt;&lt; std::endl; } file_size = infile.seekg(0, infile.end).tellg(); infile.seekg(0, infile.beg); infile.read((char *)z80.mem, file_size); try { z80.emulate(); } catch(std::exception &amp;e) { std::cerr &lt;&lt; "Emulation failed: " &lt;&lt; e.what() &lt;&lt; std::endl; return EXIT_FAILURE; } return 0; } void usage(const char *progname) { std::cout &lt;&lt; " Usage: " &lt;&lt; progname &lt;&lt; " z80-prog" &lt;&lt; std::endl; } </code></pre> <p><code>opcodes.h</code>:</p> <pre><code>#ifndef Z80EMU_OPCODES_H #define Z80EMU_OPCODES_H 1 #define NOP 0x00 #define LD_BC_IMM 0x01 #define LD_DBC_A 0x02 #define INC_BC 0x03 #define INC_B 0x04 #define DEC_B 0x05 #define LD_B_IMM 0x06 #define RLCA 0x07 #define EX_AF_AF 0x08 #define ADD_HL_BC 0x09 #define LD_A_DBC 0x0a #define DEC_BC 0x0b #define INC_C 0x0c #define DEC_C 0x0d #define LD_C_IMM 0x0e #define RRCA 0x0f #define DJNZ_IMM 0x10 #define LD_DE_IMM 0x11 #define LD_DDE_A 0x12 #define INC_DE 0x13 #define INC_D 0x14 #define DEC_D 0x15 #define LD_D_IMM 0x16 #define RLA 0x17 #define JR_IMM 0x18 #define ADD_HL_DE 0x19 #define LD_A_DDE 0x1a #define DEC_DE 0x1b #define INC_E 0x1c #define DEC_E 0x1d #define LD_E_IMM 0x1e #define RRA 0x1f #define JR_NZ_IMM 0x20 #define LD_HL_IMM 0x21 #define LD_DIMM_HL 0x22 #define INC_HL 0x23 #define INC_H 0x24 #define DEC_H 0x25 #define LD_H_IMM 0x26 #define DAA 0x27 #define JR_Z_IMM 0x28 #define ADD_HL_HL 0x29 #define LD_HL_DIMM 0x2a #define DEC_HL 0x2b #define INC_L 0x2c #define DEC_L 0x2d #define LD_L_IMM 0x2e #define CPL 0x2f #define JR_NC_IMM 0x30 #define LD_SP_IMM 0x31 #define LD_DIMM_A 0x32 #define INC_SP 0x33 #define INC_DHL 0x34 #define DEC_DHL 0x35 #define LD_DHL_IMM 0x36 #define SCF 0x37 #define JR_C_IMM 0x38 #define ADD_HL_SP 0x39 #define LD_A_DIMM 0x3a #define DEC_SP 0x3b #define INC_A 0x3c #define DEC_A 0x3d #define LD_A_IMM 0x3e #define CCF 0x3f #endif </code></pre> <p><code>tools.cpp</code>:</p> <pre><code>#include "z80emu.hpp" namespace z80emu { // return reference to 8-bit register or memory location uint8_t &amp;z80::ref8(uint8_t idx, bool low, reg **tab) { // idx is the index for the 16-bit register (usually op &gt;&gt; 4) // if low is true, return the low part of the variable, // otherwise return the high part (usually !!(op &amp; 8)) switch(idx &amp; 3) { case 3: return low ? regs.af.high : mem[regs.hl.combined]; default: return low ? tab[idx]-&gt;low : tab[idx]-&gt;high; } } // return reference to a byte in memory // specified by a 16-bit pointer uint8_t &amp;z80::deref16_u8(uint8_t idx, reg **tab) { return mem[tab[idx]-&gt;combined]; } // load 16-bit register with immediate void z80::ld16imm(uint8_t idx, reg **tab) { // Do these individually because // of endianness and memory wrapping tab[idx]-&gt;low = mem[++regs.pc]; tab[idx]-&gt;high = mem[++regs.pc]; tab[idx]-&gt;combine(); } // load 8-bit register with immediate void z80::ld8imm(uint8_t op, reg **tab) { uint8_t idx = op &gt;&gt; 4; ref8(idx, !!(op &amp; 8), tab) = mem[++regs.pc]; if((idx &amp; 3) != 3) tab[idx]-&gt;combine(); else if(op &amp; 8) regs.af.combine(); } // increment 16-bit register void z80::inc16(uint8_t idx, reg **tab) { tab[idx]-&gt;combined++; tab[idx]-&gt;uncombine(); } // decrement 16-bit register void z80::dec16(uint8_t idx, reg **tab) { tab[idx]-&gt;combined--; tab[idx]-&gt;uncombine(); } // add number to 8-bit register void z80::add8(uint8_t op, reg **tab, uint8_t incr) { uint8_t idx = op &gt;&gt; 4; ref8(idx, !!(op &amp; 8), tab) += incr; if((idx &amp; 3) != 3) tab[idx]-&gt;combine(); else if(op &amp; 8) regs.af.combine(); } // increment 8-bit register void z80::inc8(uint8_t op, reg **tab) { add8(op, tab, 1); } // decrement 8-bit register void z80::dec8(uint8_t op, reg **tab) { add8(op, tab, -1); } void z80::rrc8(uint8_t op, reg **tab) { uint8_t idx = (op &amp; 0x7) &gt;&gt; 1; uint8_t &amp;ref = ref8(idx, op &amp; 1, tab); ref = ref &gt;&gt; 1 | (ref &amp; 1) &lt;&lt; 7; if((idx &amp; 3) != 3) tab[idx]-&gt;combine(); else if((op &amp; 0x7) == 0x7) regs.af.combine(); } } </code></pre> <p><code>z80emu.hpp</code>:</p> <pre><code>#ifndef Z80EMU_HPP #define Z80EMU_HPP 1 #if __cplusplus &gt;= 201103L # include &lt;cstdint&gt; # include &lt;utility&gt; using std::uint16_t; using std::uint8_t; #else # include &lt;stdint.h&gt; # include &lt;algorithm&gt; #endif #include &lt;cstring&gt; #include &lt;vector&gt; // TODO: Decide whether to use struct or class namespace z80emu { enum cc { NZ = 0, Z = 1, NC = 2, C = 3, PO = 4, PE = 5, P = 6, M = 7 }; struct reg { uint8_t high, low; uint16_t combined, exx; void combine() { combined = high &lt;&lt; 8 | low; } void uncombine() { high = combined &gt;&gt; 8; low = combined; } void exchange() { std::swap(combined, exx); uncombine(); } }; #if __cplusplus &gt;= 201103L static_assert(sizeof(reg) == 6, "sizeof(reg) != 6"); #endif struct registers { reg af; reg bc; reg de; reg hl; reg ix; reg iy; reg sp; reg wz; uint16_t pc; }; struct z80 { uint8_t *mem; registers regs; uint16_t emulate(); uint8_t &amp;ref8(uint8_t op, bool low, reg **tab); uint8_t &amp;deref16_u8(uint8_t op, reg **tab); void ld16imm(uint8_t op, reg **tab); void ld8imm(uint8_t op, reg **tab); void inc16(uint8_t op, reg **tab); void dec16(uint8_t op, reg **tab); void add8(uint8_t op, reg **tab, uint8_t incr); void inc8(uint8_t op, reg **tab); void dec8(uint8_t op, reg **tab); void rrc8(uint8_t op, reg **tab); z80() { mem = new uint8_t[0xffff]; } ~z80() { delete[] mem; } }; } #endif </code></pre> <p>Shell script to create example program (filename <code>test</code>) that will cause the program built with the modified version of <code>emulate.cpp</code> to print the registers on exit:</p> <pre><code>#!/bin/sh printf '\001\275\274\021\337\336\041\316\315\061\255\336\377' &gt; test </code></pre> <p>I'd like to note that later on in the implementation (when I get 15/16ths of it done), <code>rp2</code> will be used for <code>push</code> and <code>pop</code> so the <code>af</code> register (accumulator and flags) can be saved.</p> <p>And, for the instructions I do have implemented, everything seems to be working fine (as in, the register values seem to be correct when I use <code>gdb</code> and <code>std::cout</code>).</p> <p>What I'm mainly interested in:</p> <ul> <li><p>Are there any "more C++" things (that work from c++98 to c++2a) that I can do? Have I started using the language's featured adequately?</p></li> <li><p>Can I reduce code duplication? Most of the functions in <code>tools.cpp</code> have to call <code>uncombine</code> or <code>combine</code> after altering the registers. Is there a way around this? What about with the <code>rrc8</code> function?</p></li> <li><p>Are there any C++ "best practices" that I'm missing here?</p></li> <li><p>If there are any other miscellaneous things that could be improved, please let me know, although I would appreciate it if you could focus on the other points more.</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T00:03:48.247", "Id": "455185", "Score": "1", "body": "I would suggest that in order to get better reviews, you include a sample file that your program can emulate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T00:05:42.137", "Id": "455186", "Score": "0", "body": "@tinstaafl I can do that, but it won't be able to do much other than modify the registers. I'll go ahead and add a version of `emulate.cpp` that prints the registers, too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T00:08:09.807", "Id": "455187", "Score": "0", "body": "That's fine. It's mainly so reviewers can step through your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T00:15:29.403", "Id": "455189", "Score": "0", "body": "@tinstaafl Done." } ]
[ { "body": "<p>A few quick observations:</p>\n\n<ol>\n<li><p>Don't use <code>#define</code> for all those compile time constants (opcodes). They should be part of an opcode <code>enum</code> or declared as <code>constexpr int</code>.</p></li>\n<li><p>You're only allocating 65,535 bytes for <code>mem</code>, when you should be allocating 65,536. An attempt to access <code>mem[0xFFFF]</code> will result in Undefined Behavior because it is past the end of the allocated space.</p></li>\n<li><p>Having a default case label to catch unimplemented opcodes is a Good Thing.</p></li>\n<li><p><code>if((unsigned)argc - 2 &gt; 0)</code> is somewhat obscure. What's wrong with <code>if (argc != 2)</code>?</p></li>\n<li><p>I'm not sure what you're trying to do with your <code>reg</code> struct, but you could eliminate the duplicate data storage to add byte and word accessor methods. Both GCC and Clang will optimize (<code>-O3</code>) these to single instruction byte accesses. MSVC does the same for getters, but setters are not fully optimized (with <code>/O2</code> and variations I tried).</p>\n\n<pre><code>struct reg {\n uint16_t combined;\n uint8_t high() const\n {\n return combined &gt;&gt; 8;\n }\n uint8_t low() const\n {\n return combined &amp; 255;\n }\n void seth(uint8_t v)\n {\n combined = (combined &amp; 255) | (v &lt;&lt; 8);\n }\n void setl(uint8_t v)\n {\n combined = (combined &amp; ~255) | v;\n }\n};\n</code></pre>\n\n<p><code>combined</code> could be made private and accessors added to it if desired.</p></li>\n<li><p>While it is unlikely a <code>z80</code> object will be copied, you should <code>=delete</code> the copy and move constructors and assignment operators. See this <a href=\"https://stackoverflow.com/questions/4782757/rule-of-three-becomes-rule-of-five-with-c11\">question</a> on Stack Overflow.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T00:48:35.807", "Id": "455195", "Score": "0", "body": "Uhh... What does point 6 mean? I think you should see the [tag:beginner] tag. I'm also slightly confused by what `constexpr int` is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T01:02:20.723", "Id": "455198", "Score": "0", "body": "Ah, I should've mentioned that I wanted this to be portable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T10:22:24.297", "Id": "455229", "Score": "1", "body": "To get away from `combine()`/`uncombine()`, it might be best to give `reg` some member functions to read/write individual registers in the pair." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T16:12:52.203", "Id": "455280", "Score": "1", "body": "@TobySpeight After marinating on this overnight, I had similar thoughts and updated my answer to use member functions instead of punning with a union." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-04T19:30:47.977", "Id": "456282", "Score": "0", "body": "Do you mind if I show my changes so far to be reviewed? I've addressed most, if not all of your points." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-04T20:32:36.297", "Id": "456293", "Score": "1", "body": "@JL2210 If you've made changes to the code that you want reviewed, they should be posted as a follow on question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-04T21:01:26.903", "Id": "456297", "Score": "0", "body": "Here's the follow-up: https://codereview.stackexchange.com/questions/233431/less-incomplete-z80-emulator-written-in-c" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T00:40:31.253", "Id": "232976", "ParentId": "232962", "Score": "5" } } ]
{ "AcceptedAnswerId": "232976", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T18:56:01.103", "Id": "232962", "Score": "10", "Tags": [ "c++", "beginner", "emulator" ], "Title": "Partial Zilog Z80 emulator written in C++" }
232962
<p>Given a class where the methods return <code>this</code> you can chain them.</p> <pre><code>const e = new Example() e.add(1).add(1).add(1).add(1).add(1) </code></pre> <p>However this breaks does not work if one of the methods is <code>async</code> and returns a promise.</p> <p>I created an alternative method on <code>compose</code> the class <code>Meow2</code> below that adds this kind of functionality.</p> <pre><code>const e = new Example() e.flow(e =&gt; [ e.add(1) e.asyncAdd(1) e.add(1) e.asyncAdd(1) ]).then(console.log) </code></pre> <p>I'm looking for any and all optimizations that can be made to this code.</p> <p>Entire codebase:</p> <pre><code>export namespace Use { type ThenArg&lt;T&gt; = T extends Promise&lt;infer U&gt; ? U : T type RelatedThen&lt;A, B&gt; = A extends Promise&lt;infer U&gt; ? Promise&lt;B&gt; : B export type Func = (...args: any[]) =&gt; any export type Return&lt;A extends Func, B&gt; = RelatedThen&lt;ReturnType&lt;A&gt;, B&gt; export type CallbackValue&lt;A extends Func&gt; = ThenArg&lt;ReturnType&lt;A&gt;&gt; } export namespace Flow { export type Func = (args: any) =&gt; any export type Funcs = readonly Func[] type FuncPass&lt;A, B&gt; = (x: A) =&gt; B type Tail&lt;T extends readonly FuncPass&lt;any, any&gt;[]&gt; = FuncPass&lt;T, void&gt; extends ((h: any, ...r: infer R) =&gt; void) ? R : never; export type Check&lt;T extends readonly FuncPass&lt;any, any&gt;[]&gt; = { [K in keyof T]: K extends keyof Tail&lt;T&gt; ? ( [T[K], Tail&lt;T&gt;[K]] extends [FuncPass&lt;infer A, infer R&gt;, FuncPass&lt;infer S, any&gt;] ? ( [R] extends [S] ? T[K] : FuncPass&lt;A, S&gt; ) : never ) : T[K] } type FirstFnParam&lt;Fns extends Funcs&gt; = Parameters&lt;Fns[0]&gt;[0] export type Params&lt;T extends Funcs&gt; = FirstFnParam&lt;T&gt; type LengthOfTuple&lt;T extends Funcs&gt; = T extends { length: infer L } ? L : never; type DropFirstInTuple&lt;T extends Funcs&gt; = ((...args: T) =&gt; any) extends (arg: any, ...rest: infer U) =&gt; any ? U : T; type LastInTuple&lt;T extends Funcs&gt; = T[LengthOfTuple&lt;DropFirstInTuple&lt;T&gt;&gt;]; type LastFnReturns&lt;Fns extends Funcs&gt; = ReturnType&lt;LastInTuple&lt;Fns&gt;&gt; export type Return&lt;T extends Funcs&gt; = LastFnReturns&lt;T&gt; } function nest&lt;T&gt;(value: T): () =&gt; T { return () =&gt; { return value } } function flow&lt;T extends Flow.Funcs&gt;(...funcs: Flow.Check&lt;T&gt;) { return (input: Flow.Params&lt;T&gt;) =&gt; { return funcs.reduce((acq: Flow.Func, fn: Flow.Func) =&gt; { return use(acq, (acqError, acqValue) =&gt; { if (acqError) throw acqError return use(fn, (fnError, fnValue) =&gt; { if (fnError) throw fnError return fnValue })(acqValue) }) }, nest(input))(input) as Flow.Return&lt;T&gt; } } function isPromise(obj: any) { return !!obj &amp;&amp; (typeof obj === 'object' || typeof obj === 'function') &amp;&amp; typeof obj.then === 'function' } function use&lt;A extends Use.Func, G&gt;(fn: A, callback: (e: Error | null, a: Use.CallbackValue&lt;A&gt;) =&gt; G) { return (...args: Parameters&lt;A&gt;): Use.Return&lt;A, G&gt; =&gt; { try { const v = fn(...args as any[]) if (isPromise(v)) { return v.then((v: any) =&gt; callback(null, v)).catch((e: any) =&gt; callback(e, undefined as Use.CallbackValue&lt;A&gt;)) } return callback(null, v) as Use.Return&lt;A, G&gt; } catch (e) { return callback(e, undefined as Use.CallbackValue&lt;A&gt;) as unknown as Use.Return&lt;A, G&gt; } } } type FlowClassNest&lt;T extends (...args: any) =&gt; any&gt; = (...a: Parameters&lt;T&gt;) =&gt; () =&gt; ReturnType&lt;T&gt; type FlowCallbackArg&lt;T&gt; = { [K in keyof T]: T[K] extends ((...args: any) =&gt; any) ? FlowClassNest&lt;T[K]&gt; : never } type FlowCallback&lt;T&gt; = (t: FlowCallbackArg&lt;T&gt;) =&gt; any[] class Composition&lt;T&gt;{ blacklist = [ 'constructor', '__defineGetter__', '__defineSetter__', 'hasOwnProperty', '__lookupGetter__', '__lookupSetter__', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'valueOf', '__proto__', 'toLocaleString' ] constructor(private readonly parent: any) { } get methodNames() { let methods = new Set(); let parent = this.parent while (parent = Reflect.getPrototypeOf(parent)) { let keys = Reflect.ownKeys(parent) keys.forEach((k) =&gt; methods.add(k)); } return methods } get methodNamesArray() { return Array.from(this.methodNames) } get methodNamesArrayClean() { const arr1 = this.methodNamesArray const arr2 = this.blacklist return arr1.filter((x: string) =&gt; !arr2.includes(x)); } get methods(): FlowCallbackArg&lt;T&gt; { const _methods = this.methodNamesArrayClean.map((key: string) =&gt; ({ [key]: (...args) =&gt; { return () =&gt; { return this.parent[key](...args) } } })) return Object.assign({}, ..._methods) } build(callback: FlowCallback&lt;T&gt;) { return flow(...callback(this.methods))(this.parent) } } </code></pre> <p>Here's an example using above:</p> <pre><code>class Example { say: string setSay(value) { this.say = value return this } async setSayAsync(value) { this.say = value return this } logSay() { console.log(this.say) return this } compose(callback: FlowCallback&lt;Meow2&gt;) { return new Composition(this).build(callback) } } const m = new Example() .compose((m) =&gt; [ m.setSay('A'), m.logSay(), m.setSayAsync('B'), m.logSay(), m.setSay('C'), m.logSay(), ]) m.then(console.log) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T19:11:34.857", "Id": "455149", "Score": "0", "body": "Are you sure that's what the code base looks like? What's the goal of it? `Meow2` doesn't tell me much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T19:12:10.493", "Id": "455150", "Score": "0", "body": "`Meow2` Is an example case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T19:12:50.533", "Id": "455151", "Score": "0", "body": "Which part of the code is not an example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T19:14:17.130", "Id": "455152", "Score": "0", "body": "Everything above `Meow2`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T19:15:46.013", "Id": "455153", "Score": "0", "body": "`Meow 2` is gone " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T22:12:04.397", "Id": "455173", "Score": "1", "body": "\"However this breaks does not work if one of the methods is async and returns a promise. I created an alternative method on compose the class Meow2 below that adds this kind of functionality.\" -- But your example doesn't do the same thing, it does something similar. I'd suggest rewording this. This site is for working code and from a very broad point of view your code \"doesn't work\" since it's not doing that. I only mention that since it seems like this has a downvote and I am unsure why. (Personally I think it's fine.)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T18:59:47.220", "Id": "232963", "Score": "2", "Tags": [ "object-oriented", "typescript" ], "Title": "Composable async methods" }
232963
<p>I was given this coding challenge when a applying for a summer internship but didn't get selected for the next round and I was curious if it could be improved.</p> <p>The problem says:</p> <blockquote> <p>Given a number in base "-2" divide it by 2.</p> <p>For example:</p> <p>Given [1, 0, 0, 1, 1, 1] (-23) the output is [1, 0, 1, 0, 1, 1] (-11)</p> <p>Given [0, 0, 1, 0, 1, 1] (-12) the output is [0, 1, 1, 1] (-6)</p> <p><strong>Note</strong> the array is read from left to right. [1, 0, 0, 1, 1, 1] = 1*(-2)^0 + 0*(-2)^1 + 0*(-2)^2 + 1*(-2)^3 + 1*(-2)^4 + 1 * (-2)^5 = 1 + 0 + 0 + (-8) + 16 + (-32) = -23</p> </blockquote> <p>The easiest solution that I found was to convert the number to an integer, divide it by two and then convert it back to base -2.</p> <p>Thanks in advance for your input.</p> <p>My code in Python:</p> <pre><code>import math # Main function def solution(A): value = math.ceil(calculate_number(A) / 2) p = convert_number_to_binary(value) return p # This function calculates the value of the list def calculate_number(A): total = 0 for i in range(0, len(A)): total += A[i] * (-2) ** i return total # This function converts a number to base -2 def convert_number_to_binary(number): binary = [] if number == 0: return binary while number != 0: number, remainder = divmod(number, -2) if remainder &lt; 0: number += 1 remainder -= -2 binary.append(remainder) return binary print(solution([1, 0, 0, 1, 1, 1])) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T21:37:30.333", "Id": "455169", "Score": "0", "body": "please add the context of how are you running the program" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T21:42:32.353", "Id": "455170", "Score": "2", "body": "That is an arguably bad coding challenge for a summer internship; one wonders what signal they were attempting to extract from that challenge. Your solution seems quite straightforward; there are a few minor stylistic things I might change but the basic approach seems sound. I have given interview problems myself where the problem could be solved by transforming an unpleasant representation into a pleasant one, doing the work in the pleasant form, and then transforming back; it's a good technique that is applicable to real problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T09:55:52.590", "Id": "455226", "Score": "1", "body": "@EricLippert: Well, it tests if you understand the basic Python syntax, basic algorithms, know how to use functions and then if you know proper Python style. Not entirely useless IMO, depending on what you want to achieve..." } ]
[ { "body": "<p>Python has <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code>s to document your functions properly</a>. Just move your comments there, as a first step.</p>\n\n<p>In the <code>calculate_number</code> function (which I would rename to <code>from_base_neg_2</code> or something similar) you can use a <a href=\"https://www.pythonforbeginners.com/basics/list-comprehensions-in-python\" rel=\"nofollow noreferrer\">list comprehension</a> (or even better, a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator expression</a>):</p>\n\n<pre><code>def from_base_neg_2(A):\n \"\"\"Calculate the value of a number in base -2,\n given as a list of coefficients, sorted from smallest exponent to largest.\n \"\"\"\n return sum(a * (-2) ** i for i, a in enumerate(A))\n</code></pre>\n\n<p>Similarly, I would call the inverse function <code>to_base_neg_2</code> or something like it.</p>\n\n<p>Your main calling code should be under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this module. Arguably the <code>solution</code> function should be defined last, since it depends on all the other functions and that makes it slightly easier to read.</p>\n\n<pre><code>def solution(A):\n \"\"\"Main function.\n Divide A, a number in base -2, by 2.\n \"\"\"\n return to_base_neg_2(math.ceil(from_base_neg_2(A) / 2))\n\nif __name__ == \"__main__\":\n print(solution([1, 0, 0, 1, 1, 1]))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T10:03:44.717", "Id": "232985", "ParentId": "232968", "Score": "3" } }, { "body": "<h3>A bug?</h3>\n\n<p>Here</p>\n\n<pre><code>value = math.ceil(calculate_number(A) / 2)\n</code></pre>\n\n<p>you use the <code>ceil</code> function, apparently to truncate the result dividing a negative number towards zero, so that, for example, <code>-23</code> becomes <code>-11</code>. But for positive odd numbers this gives an unexpected result:</p>\n\n<pre><code>print(solution([1, 1, 1])) # 1 - 2 + 4 = 3\n</code></pre>\n\n<p>returns <code>[0, 1, 1] = -2 + 4 = 2</code> where I would expect <code>[1] = 1</code>. If that line is replaced by</p>\n\n<pre><code>value = int(calculate_number(A) / 2)\n</code></pre>\n\n<p>then both positive and negative values are rounded towards zero. As a side-effect, the </p>\n\n<pre><code>import math\n</code></pre>\n\n<p>is not needed anymore.</p>\n\n<h3>Some small simplifications</h3>\n\n<p>The test</p>\n\n<pre><code>if number == 0:\n return binary\n</code></pre>\n\n<p>in <code>convert_number_to_binary()</code> is not needed: If the passed number is zero then the <code>while</code> loop will not execute.</p>\n\n<p>The exponentiation in the conversion from binary to number can be avoided if the digits are processed in reverse order:</p>\n\n<pre><code>def calculate_number(A):\n total = 0\n for digit in reversed(A):\n total = (-2) * total + digit\n return total\n</code></pre>\n\n<p>And that can be compactly expressed as a <a href=\"https://docs.python.org/3.8/library/functools.html#functools.reduce\" rel=\"nofollow noreferrer\"><code>reduce</code></a> operation:</p>\n\n<pre><code>import functools\n\ndef calculate_number(binary):\n return functools.reduce(lambda total, digit: -2 * total + digit, reversed(binary))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T11:00:53.220", "Id": "232987", "ParentId": "232968", "Score": "4" } }, { "body": "<h2>General</h2>\n\n<ul>\n<li><p>As per <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> conventions, the variables in functions should be in lowercase.</p></li>\n<li><p>Adding docstrings is recommended. <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a></p></li>\n<li><p>Names should be short and meaningful. For example, <code>convert_number_to_binary</code> should actually be <code>to_base_minus_two</code>. Also, <code>calculate_number</code> should be <code>from_base_minus_two</code></p></li>\n<li><p>Use <a href=\"https://stackoverflow.com/questions/32557920/what-are-type-hints-in-python-3-5\">type hints</a></p></li>\n<li><p>Instead of <code>x == 0</code> python allows you to use use <code>not x</code>. Similarly, <code>x != 0</code> can be replaced with <code>x</code>.</p></li>\n<li><p>Envelop the main code inside <code>if __name__ == '__main__':</code>. This will prevent the code from being run if imported from another module.</p></li>\n<li><p>Following @Martin R's advice, you can change -2 to a constant <code>BASE</code></p></li>\n</ul>\n\n<h2>Function <code>solution</code></h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>value = math.ceil(from_base_minus_two(A) / 2)\np = to_base_minus_two(value)\nreturn p\n</code></pre>\n\n<p>Can be replaced with the one liner:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return to_base_minus_two(math.ceil(from_base_minus_two(a) / 2))\n</code></pre>\n\n<h2>Function <code>from_base_minus_two</code></h2>\n\n<pre><code>total = 0\nfor i in range(0, len(a)):\n total += a[i] * BASE ** i\nreturn total\n</code></pre>\n\n<p>Instead, you can use:</p>\n\n<pre><code>return sum(j * BASE ** i for i, j in enumerate(a)))\n</code></pre>\n\n<h2>Function <code>to_base_minus_two</code></h2>\n\n<p>The value you are finding isn't exactly <code>binary</code>. Change it to <code>base_minus_two</code></p>\n\n<p>You don't need to use</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if number == 0:\n return base_minus_two\n</code></pre>\n\n<p>Automatically, the while loop will terminate immediately as <code>number</code> is 0, and will return <code>base_minus_two</code> which is <code>[]</code></p>\n\n<hr>\n\n<p>Here's what the final code might look like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import math\nfrom typing import List\n\n\nBASE = -2\n\n\ndef from_base_minus_two(a: List[int]) -&gt; int:\n \"\"\" Converts base 'BASE' to decimal \"\"\"\n\n return sum(j * BASE ** i for i, j in enumerate(a))\n\n\ndef to_base_minus_two(number: int) -&gt; List[int]:\n \"\"\" Converts decimal to 'BASE' \"\"\"\n\n base_minus_two = []\n\n while number:\n number, remainder = divmod(number, BASE)\n\n if remainder &lt; 0:\n number += 1\n remainder -= BASE\n\n base_minus_two.append(remainder)\n\n return base_minus_two\n\n\ndef solution(a: List[int]) -&gt; List[int]:\n \"\"\"\n\n * Converts from 'BASE' to decimal\n * Divides the decimal by 2\n * Converts the decimal back to 'BASE'\n\n \"\"\"\n\n return to_base_minus_two(math.ceil(from_base_minus_two(a) / 2))\n\n\nif __name__ == '__main__':\n print(solution([1, 0, 0, 1, 1, 1]))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T12:14:44.650", "Id": "455238", "Score": "1", "body": "Re *“remainder -= -2 can be replaced with remainder += 2”*: I'd prefer the original version because it emphasizes the connection to the base -2. (Or better, `remainder -= BASE` using a constant definition)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T16:32:39.610", "Id": "455287", "Score": "0", "body": "@MartinR Thanks for the idea. I've updated my code according to it" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T11:15:00.520", "Id": "232988", "ParentId": "232968", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T20:57:06.190", "Id": "232968", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Divide by two a number in base -2" }
232968
<p>This is a <code>HashMap</code> implementation written in Python. All the methods are based on the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html" rel="nofollow noreferrer">java implementation</a> of a <code>HashMap</code>. Any and all critique is welcome.</p> <p>This implementation is just a rewrite of some java <code>HashMap</code> methods. Yes, it's basically a wrapper class for pythons <code>dict</code>. This implementation is a simple exercise to see if I could write something from Java in Python.</p> <pre><code>from typing import Union, List class HashMap: def __init__(self): self.capacity = 16 self.map = {} def clear(self) -&gt; None: """ Clears all the entries into this hashmap :return: None """ self.map = {} def contains_key(self, key: object) -&gt; bool: """ Returns if the map contains the passed key :param key -&gt; object: Value to check residency in map keyset :return bool: True if "key" in map keyset, False otherwise """ return key in self.map.keys() def contains_value(self, value: object) -&gt; bool: """ Returns if the map contains the passed value :param value -&gt; object: Value to check residency in map valueset :return bool: True if "value" in map valueset, False otherwise """ return value in self.map.values() def entry_set(self) -&gt; set: """ Returns a set of the hashmap :return set: A set representation of the map """ return set(self.map) def get(self, key: object) -&gt; Union[object, None]: """ Returns the value at the passed key, None if not present :param key -&gt; object: Key to retrieve value in map :return Union[object, None]: value at "key", None if key is not present in map """ return self.map[key] if key in self.map.keys() else None def get_or_default(self, key: object, default_value: object) -&gt; object: """ Returns the value at the passed key, or default_value if not present :param key -&gt; object: Key to retrieve value in map\n :param default_value -&gt; object: Value to return if key is not present in map :return object: Value associated with "key", "default_value" otherwise """ return self.map[key] if key in self.map.keys() else default_value def is_empty(self) -&gt; bool: """ Returns if the map has no key-value entries :return bool: True if map isn't empty, False otherwise """ return self.map != {} def key_set(self) -&gt; set: """ Returns a set of all the keys :return set: Set of all keys in map """ return set(self.map.keys()) def put(self, key: object, value: object) -&gt; object: """ Adds the key-value pair to the map, returning the value :param key -&gt; object: Key to add to set\n :param value -&gt; object: Value to add to set :return object: "value" passed """ self.map[key] = value return value def remove(self, key: object) -&gt; Union[object, None]: """ Removes the mapping for the passed key, returning the value :param key -&gt; object: Key to retrieve value from map :return object: Value associated with "key", None if key not in map keyset """ if key in self.map.keys(): value = self.map[key] del self.map[key] return value return None def size(self) -&gt; int: """ Returns the size of the hashmap :return int: Size of map """ return len(self.map) def values(self) -&gt; List[object]: """ Returns a list of the values in the hashmap :return List[object]: List of values in map """ return list(self.map.values()) </code></pre> <p>Testing Implementation</p> <pre><code>if __name__ == "__main__": hashmap = HashMap() hashmap.put("Ben", 18) hashmap.put(5, 18) hashmap.put("5", True) hashmap.put(False, 3.661) print(hashmap.get(5)) print(hashmap.get(False)) print(hashmap.get("Ben")) print(hashmap.size()) print(hashmap.values()) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T03:36:11.360", "Id": "455207", "Score": "2", "body": "What's the purpose of this exercise -- is it to actually implement a hash map to get a better understanding of how they work (you haven't done that since you aren't hashing keys or mapping them to buckets), or is it to implement a Java-style interface over Python's hashmap (I don't think you've done that either; if nothing else you seem to be ignoring the `capacity` attribute which I assume would have some sort of meaning in Java-land), or is it something else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T11:04:58.097", "Id": "455232", "Score": "0", "body": "@SamStafford I've provided some more description." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T05:42:35.207", "Id": "455357", "Score": "0", "body": "IMO this question shows no research effort, and so is worthy of downvotes. What do you expect to get out of a review? \"This is an interface that doesn't utilize all the methods `dict` provides\"." } ]
[ { "body": "<h3><em>Refactoring the core interface:</em></h3>\n\n<p>Since presented <code>HashMap</code> class is just a custom wrapper around Python's <em>dictionary</em> - it should borrow all the advantages from that.</p>\n\n<p>As the class provides a public interface for the internal data structure - that data structure needs to be <em>protected</em> (or private). Otherwise, the one can easily compromise it like shown below:</p>\n\n<pre><code>hashmap = HashMap()\nhashmap.map = tuple()\n</code></pre>\n\n<p>So we change the constructor/initializer to the following:</p>\n\n<pre><code>def __init__(self):\n self.capacity = 16\n self._map = {}\n</code></pre>\n\n<p>Let get down to instance methods:</p>\n\n<ul>\n<li><strong><code>clear</code></strong> method. It reassigns the internal <em>map</em> with <code>self._map = {}</code>.<br>\nIn ideal perspective using <code>self._map.clear()</code> would be preferable as it allows to beat potential copies of <code>self._map</code> (even if that's unlikely to happen)</li>\n<li><strong><code>contains_key</code></strong> method.<br>\nReturns <code>key in self._map.keys()</code> which is a verbose way of <strong><code>key in self._map</code></strong></li>\n<li><p><strong><code>entry_set</code></strong> method and <strong><code>key_set</code></strong> method lead to confusion as they return the same result:<br>\n<code>return set(self._map)</code> is technically equal to <code>return set(self._map.keys())</code>.</p>\n\n<p>To fix that - let's perceive \"entry\" as a <code>(key, value)</code> pair.<br>\nTherefore the definition of <code>entry_set</code> is changed to:</p>\n\n<pre><code>def entry_set(self) -&gt; set:\n \"\"\"\n Returns a set of the hashmap\n\n :return set: A set representation of the map\n \"\"\"\n return set(self._map.items())\n</code></pre></li>\n<li><p><strong><code>get</code></strong> method. The noisy expression <code>self._map[key] if key in self._map.keys() else None</code> should be eliminated in favor of flexible <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.get\" rel=\"nofollow noreferrer\"><code>dict.get()</code></a> method:</p>\n\n<pre><code>self._map.get(key, None)\n</code></pre></li>\n<li><p><strong><code>get_or_default</code></strong> method has the same issue as <code>get</code> method, and the optimal way would be to just combine them into a single unified method:</p>\n\n<pre><code>def get(self, key: object, default_value=None) -&gt; object:\n \"\"\"\n Returns the value at the passed key, or default_value if not present\n\n :param key -&gt; object: Key to retrieve value in map\\n\n :param default_value -&gt; object: Value to return if key is not present in map\n\n :return object: Value associated with \"key\", \"default_value\" otherwise \n \"\"\"\n return self._map.get(key, default_value)\n</code></pre></li>\n<li><p><strong><code>is_empty</code></strong> method. The returned value <code>self._map != {}</code> is simply replaced with <strong><code>bool(self._map)</code></strong></p></li>\n<li><p><strong><code>key_set</code></strong> method. The returned value <code>set(self._map.keys())</code> is simplified to <strong><code>set(self._map)</code></strong></p></li>\n<li><p><strong><code>remove</code></strong> method. The whole method body:</p>\n\n<pre><code>if key in self._map.keys():\n value = self._map[key]\n del self._map[key]\n return value\nreturn None\n</code></pre>\n\n<p>can be replaced with the convenient <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.pop\" rel=\"nofollow noreferrer\"><code>dict.pop</code></a> method:</p>\n\n<pre><code>return self._map.pop(key, None)\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>The final optimized implementation:</p>\n\n<pre><code>class HashMap:\n\n def __init__(self):\n self.capacity = 16\n self._map = {}\n\n def clear(self) -&gt; None:\n \"\"\"\n Clears all the entries into this hashmap\n\n :return: None\n \"\"\"\n self._map.clear()\n\n def contains_key(self, key: object) -&gt; bool:\n \"\"\"\n Returns if the map contains the passed key\n\n :param key -&gt; object: Value to check residency in map keyset\n\n :return bool: True if \"key\" in map keyset, False otherwise\n \"\"\"\n return key in self._map\n\n def contains_value(self, value: object) -&gt; bool:\n \"\"\"\n Returns if the map contains the passed value\n\n :param value -&gt; object: Value to check residency in map valueset\n\n :return bool: True if \"value\" in map valueset, False otherwise\n \"\"\"\n return value in self._map.values()\n\n def entry_set(self) -&gt; set:\n \"\"\"\n Returns a set of the hashmap\n\n :return set: A set representation of the map\n \"\"\"\n return set(self._map.items())\n\n def get(self, key: object, default_value=None) -&gt; object:\n \"\"\"\n Returns the value at the passed key, or default_value if not present\n\n :param key -&gt; object: Key to retrieve value in map\\n\n :param default_value -&gt; object: Value to return if key is not present in map\n\n :return object: Value associated with \"key\", \"default_value\" otherwise \n \"\"\"\n return self._map.get(key, default_value)\n\n def is_empty(self) -&gt; bool:\n \"\"\"\n Returns if the map has no key-value entries\n\n :return bool: True if map isn't empty, False otherwise\n \"\"\"\n return bool(self._map)\n\n def key_set(self) -&gt; set:\n \"\"\"\n Returns a set of all the keys\n\n :return set: Set of all keys in map\n \"\"\"\n return set(self._map)\n\n def put(self, key: object, value: object) -&gt; object:\n \"\"\"\n Adds the key-value pair to the map, returning the value\n\n :param key -&gt; object: Key to add to set\\n\n :param value -&gt; object: Value to add to set\n\n :return object: \"value\" passed\n \"\"\"\n self._map[key] = value\n return value\n\n def remove(self, key: object) -&gt; Union[object, None]:\n \"\"\"\n Removes the mapping for the passed key, returning the value\n\n :param key -&gt; object: Key to retrieve value from map\n\n :return object: Value associated with \"key\", None if key not in map keyset\n \"\"\"\n\n return self._map.pop(key, None)\n\n def size(self) -&gt; int:\n \"\"\"\n Returns the size of the hashmap\n\n :return int: Size of map\n \"\"\"\n return len(self._map)\n\n def values(self) -&gt; List[object]:\n \"\"\"\n Returns a list of the values in the hashmap\n\n :return List[object]: List of values in map\n \"\"\"\n return list(self._map.values())\n</code></pre>\n\n<p>P.S. obviously, Python's <code>dict</code> itself is a good <em>hashmap</em> :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T22:52:14.410", "Id": "232973", "ParentId": "232970", "Score": "4" } }, { "body": "<p>This is a small review focusing only on the type hints.</p>\n\n<ul>\n<li><p>In all methods, the type of <code>key</code> should be <a href=\"https://docs.python.org/3/library/typing.html#typing.Hashable\" rel=\"nofollow noreferrer\"><code>Hashable</code></a>, not <code>object</code>. Unhashable objects (e.g. mutable collections like lists) cannot be used as keys in Python dictionaries, and the same goes for <code>HashMap</code> since it uses a Python dictionary behind the scenes.</p></li>\n<li><p>Instead of just using <code>set</code> as the return type, prefer using <a href=\"https://docs.python.org/3/library/typing.html#typing.Set\" rel=\"nofollow noreferrer\"><code>Set</code></a> with the type of the elements it contains:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def key_set(self) -&gt; Set[Hashable]:\n</code></pre></li>\n<li><p>Although they are equivalent, consider using <code>Optional[T]</code> instead of <code>Union[T, None]</code> as it is more readable:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get(self, key: Hashable) -&gt; Optional[object]:\n</code></pre></li>\n<li><p><code>__init__</code>'s return type should be <code>None</code>. After correcting this, you'll also need to provide a type hint for <code>self.map</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def __init__(self) -&gt; None:\n self.map: Dict[Hashable, object] = {}\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T09:45:39.063", "Id": "233112", "ParentId": "232970", "Score": "3" } } ]
{ "AcceptedAnswerId": "232973", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T21:18:30.270", "Id": "232970", "Score": "2", "Tags": [ "python", "python-3.x", "hash-map" ], "Title": "HashMap in Python" }
232970
<p>I am learning about GraphQL so I decided to make a schema for some sort of social network. Please let me know if there are any best practices I should follow based on my schema below. </p> <pre><code> scalar DateTime type Query { # user currentUser: User # use request "Authorization" header to get credentials getUser(uid: String!): User # friends getFriendRequest(requestId: Int!): FriendRequest } type Mutation { initializeNewUser: User! editCurrentUser(input: EditUserInput): User! # friends sendFriendRequest(toUid: String!): FriendRequest # from this mutation, can accept or reject friend requests. # server should handle adding of new friend on input.status == RequestStatus.accept updateFriendRequest(input: UpdateFriendRequestInput!): FriendRequest! # unfriend uid, and return updated list of friends unfriend(uid: String!): [Friend!]! } input UpdateFriendRequestInput { requestId: Int! status: RequestStatus! } input EditUserInput { displayName: String profilePic: String } type User { uid: String! profilePic: String displayName: String createdOn: DateTime! isOnline: Boolean friends: [Friend!]! friendRequests: [FriendRequest!]! } type Friend { user: User! friendsSince: DateTime! mutualFriends: [Friend!]! } type FriendRequest { requestId: Int! requestingUser: User! receivingUser: User! status: RequestStatus requestedAt: DateTime! } enum RequestStatus { pending accepted rejected } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T23:50:19.567", "Id": "455182", "Score": "0", "body": "Welcome to CR! I've created the tag for you, since this is a relatively new technology we didn't have a tag for. I have refrained from unilaterally deciding whether reviewing a GraphQL schema definition is on-topic or not though - I'll cook up a [meta] post for the community to discuss and debate (IMO it's not very different than reviewing a plain SQL schema definition script, which *is* on-topic here albeit with an overlap with [dba.se]). In the meantime have an upvote, so that when the meta discussion is up you have enough rep to chime in as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T00:14:29.910", "Id": "455188", "Score": "0", "body": "Meta discussion about the tag: https://codereview.meta.stackexchange.com/q/9414/23788" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T16:39:08.887", "Id": "455289", "Score": "0", "body": "As the meta discussion is currently making a rather solid case for GraphQL *schema* to be off-topic if presented without any code to consume it, I'll be putting this question on hold so that it can be freely edited without interference from potential answers." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T22:41:39.820", "Id": "232972", "Score": "2", "Tags": [ "json", "api", "server", "graphql" ], "Title": "GraphQL Schema for a Social Network" }
232972
<p>Please review my code. I would love to know what improvements I can make in terms of efficiency as well as readability. Thank you!</p> <pre><code>using System; using System.Linq; public class Bojo { public static long NextBiggerNumber(long n) { //check if bigger number is even a possibility if (NoBiggerNumber(n)) return -1; var results = FindPivot(n.ToString()); //Console.WriteLine(results.FirstPart + "," + results.PivotIndex + "," + results.SecondPart); string newSecondPart = ReorganizeSecondPart(results.SecondPart); return Convert.ToInt64(results.FirstPart + newSecondPart); } private static string ReorganizeSecondPart(string secondPart) { string newSecondPart = ""; var secondPartNumbers = secondPart.Select(c =&gt; c - '0').ToList(); //Step 1 - Find second largest digit for pivot index i.e. 0 var sortedAsc = secondPartNumbers.OrderBy(n =&gt; n).ToList(); var duplicatesRemoved = sortedAsc.Distinct().ToList(); var nextPivotIndex = duplicatesRemoved.IndexOf(secondPartNumbers[0]) + 1; newSecondPart += duplicatesRemoved[nextPivotIndex].ToString(); //Step 2 - Rearrange the rest of the second part excluding the new pivot sortedAsc.Remove(duplicatesRemoved[nextPivotIndex]); newSecondPart += String.Concat(sortedAsc.Select(n =&gt; n.ToString())); return newSecondPart; } private static (string FirstPart, int PivotIndex, string SecondPart) FindPivot(string strNumber) { var numbers = strNumber.Select(c =&gt; c - '0').ToArray(); for (int i = numbers.Count() - 1; i &gt;= 1; i--) { if (numbers[i] &gt; numbers[i - 1]) { int pivot = i - 1; string left = strNumber.Substring(0, i - 1); string right = strNumber.Substring(i - 1); return (left, pivot, right); } } return ("",-1, ""); } public static bool NoBiggerNumber(long n) { string strN = n.ToString(); if (strN.Length == 1) return true; if (strN.Distinct().Count() == 1) return true; for (int i = 1; i &lt; strN.Length; i++) { if (strN[i] &gt; strN[i - 1]) return false; } return true; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T01:51:34.227", "Id": "455199", "Score": "4", "body": "Hello Emma, could you explain in more detail what your code is supposed to do? Otherwise we can't really review it,,," } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T23:27:33.057", "Id": "232974", "Score": "1", "Tags": [ "c#" ], "Title": "Next Bigger Number with the same digits Solution" }
232974
<p>I've made this module in Lua as a mod for Project Zomboid game. In future I will develop my mods in a small team (of 2-4 programmers). At this moment I have no experience in teamwork, because most of the time I was programming alone.</p> <p>My question is: 1) What are my main mistakes (in terms of code architecture)? 2) How to make this code better, so it would be easy to develop this code (with my team) in future?</p> <pre class="lang-lua prettyprint-override"><code>local SKIP_FRAMES = 100; local function round(x) return math.floor(x + 0.5) end local function DropItem(item) if item:isFavorite() then item:setFavorite(false) end local act = ISInventoryTransferAction:new(getPlayer(), item, item:getContainer(), getPlayerLoot(getPlayer():getPlayerNum()).inventory) act:transferItem(item) end local IGNORE_BOTTLE_ONCE = { --PopEmpty=1, WineEmpty=1, WhiskeyEmpty=1, WaterBottleEmpty=1, WineEmpty2=1, PopBottleEmpty=1, } local BIG_ITEM_WEIGHT_TRESHOLD = 1950 -- граммы local MEDIUM_ITEM_WEIGHT_TRESHOLD = 550 local MAX_SMALL_ITEMS_WEIGHT = 1000 local MAX_MEDIUM_ITEMS = 3 local MAX_BIG_ITEMS = 1 local BIG_SLOT_TYPES = { BigWeapon=1,BigBlade=1,Shovel=1, GuitarAcoustic=1,PickAxeHandleSpiked=1, Rifle=1, } local MEDIUM_SLOT_TYPES = { Nightstick=1,Wrench=1,PipeWrench=1, Pistol=1,Pistol2=1,Pistol3=1, } local SMALL_SLOT_TYPES = { Drumstick=1, -- 3kg? why? } --Check if item is big. Depends on weight and size (properties) local function isBigItem(rec) local slot_type = rec.item:getAttachmentType() if slot_type and BIG_SLOT_TYPES[slot_type] or rec.item:isTwoHandWeapon() then return true end end local function getItemSize(rec) if rec.slot then if BIG_SLOT_TYPES[rec.slot] then return 'big' elseif MEDIUM_SLOT_TYPES[rec.slot] then return 'medium' elseif SMALL_SLOT_TYPES[rec.slot] then return 'small' end end if rec.wep then if rec.item:isTwoHandWeapon() then return 'big' end end if rec.weight &gt; BIG_ITEM_WEIGHT_TRESHOLD then return 'big' elseif rec.weight &gt; MEDIUM_ITEM_WEIGHT_TRESHOLD then return 'medium' end return 'small' end local function prepareRecord(item) local rec = { item = item, name = item:getType(), weight = round(item:getWeight()*1000), actual = round(item:getActualWeight()*1000), wep = item:IsWeapon(), slot = item:getAttachmentType(), cat = item:getCategory() } if rec.wep then rec.damage = (item:getMinDamage() + item:getMaxDamage()) * 0.5 end if rec.cat == 'Clothing' then rec.def = item:getBiteDefense() end rec.size = getItemSize(rec) return rec end local GUN_CLIPS = { ['556Clip']=1,['223Clip']=1,['308Clip']=1,['44Clip']=1,['45Clip']=1,['9mmClip']=1, } local IGNORE_ITEMS = { -- Zero weight ['223Bullets']=1,['308Bullets']=1,Bullets38=1,Bullets44=1,Bullets45=1,['556Bullets']=1,Bullets9mm=1, --bullets Nails=1, Cigarettes=1, } function DropItems() local player = getPlayer() if player:isNearVehicle() then return --packing and repairing a car is allowed end local inv = player:getInventory() local items = {} local count_big = 0 local count_medium = 0 for i=1,inv:getItems():size() do local item = inv:getItems():get(i-1) if item and (item:getAttachedSlot() == -1) and (not item:isEquipped()) and item:getJobDelta() == 0 and not IGNORE_ITEMS[item:getType()] then local rec = prepareRecord(item) table.insert(items, rec) if rec.size == 'big' then count_big = count_big + 1 elseif rec.size == 'medium' then count_medium = count_medium + 1 end end end --print((#items - count_big - count_medium) .. ' / ' .. count_medium .. ' / ' .. count_big) -- Sorting items by their weights table.sort(items, function(a,b) local fav_a, fav_b = a.item:isFavorite(), b.item:isFavorite() if fav_a ~= fav_b then return fav_a end if a.wep ~= b.wep then return a.wep end if a.wep and b.wep then return a.damage &gt; b.damage end if GUN_CLIPS[a.name] ~= GUN_CLIPS[b.name] then return GUN_CLIPS[a.name] ~= nil end if a.cat == 'Clothing' then if b.cat == 'Clothing' then if a.def ~= b.def then return a.def &gt; b.def end else return false end elseif b.cat == 'Clothing' then return true -- We prefer to drop clothes rather than other items end return a.actual &lt; b.actual end) --for _, item in ipairs(items) do -- print(item.weight) --end local added_big = 0 local smallItemsWeight = 0 --sum of weight of all kept items local was_battle = false local added_small = 0 local added_medium = 0 local MAX_ADD_SMALL = nil if count_big &gt; 0 and count_medium &gt; 0 then -- first found type is winner local found = nil for _, rec in ipairs(items) do if rec.size == 'big' or rec.size == 'medium' then found = rec.size break end end if found then -- always true! MAX_ADD_SMALL = found == 'big' and MAX_BIG_ITEMS - count_big or MAX_MEDIUM_ITEMS - count_medium end end if not MAX_ADD_SMALL then MAX_ADD_SMALL = count_big &gt; 0 and MAX_BIG_ITEMS - count_big or MAX_MEDIUM_ITEMS - count_medium end for _, rec in ipairs(items) do local item = rec.item if not was_battle and IGNORE_BOTTLE_ONCE[rec.name] then was_battle = true else if rec.size == 'medium' then -- Medium Items if added_big &gt; 0 then DropItem(item) -- drop all medium items! elseif added_medium &gt;= MAX_MEDIUM_ITEMS then DropItem(item) else added_medium = added_medium + 1 end elseif rec.size == 'big' then -- Big Items if added_medium &gt; 0 then DropItem(item) elseif added_big &gt;= MAX_BIG_ITEMS then DropItem(item) else added_big = added_big + 1 end else -- Small Items if smallItemsWeight + rec.actual &gt; MAX_SMALL_ITEMS_WEIGHT then if added_small &lt; MAX_ADD_SMALL then added_small = added_small + 1 else DropItem(item) end else smallItemsWeight = smallItemsWeight + rec.actual --sum of weight of all kept items end end end end --print('ADDED_SMALL: ',added_small) end local frame = 0; function DropItemsOnPlayerMove() frame = frame + 1; if frame &gt;= SKIP_FRAMES then frame = 0 end if frame == 0 then if getPlayerLoot(getPlayer():getPlayerNum()).inventory:getType()=="floor" then DropItems() end --print("Dropping Items") end end Events.OnPlayerMove.Add(DropItemsOnPlayerMove); ----------Patch tooltips--------- local old_draw_fn = ISInventoryPane.drawItemDetails function ISInventoryPane:drawItemDetails(item, y, xoff, yoff, red, ...) old_draw_fn(self, item, y, xoff, yoff, red, ...) --Add size info of the item --ISUIElement:drawText(str, x, y, r, g, b, a, font) --self:drawText end local cache_render_item = nil local cache_render_size = nil local cache_render_text = nil local old_render = ISToolTipInv.render function ISToolTipInv:render() if self.item ~= cache_render_item then cache_render_item = self.item local rec = prepareRecord(cache_render_item) cache_render_size = rec.size cache_render_text = rec.size == 'big' and getText('IGUI_RI_BIG_ITEM') or (rec.size == 'medium' and getText('IGUI_RI_MEDIUM_ITEM')) end if not cache_render_text then --small item (or error?) return old_render(self) end -- Ninja double injection in injection! local stage = 1 local save_th = 0 local old_setHeight = self.setHeight self.setHeight = function(self, num, ...) if stage == 1 then stage = 2 save_th = num num = num + 25 else stage = -1 --error end return old_setHeight(self, num, ...) end local old_drawRectBorder = self.drawRectBorder self.drawRectBorder = function(self, ...) if stage == 2 then local r,g,b=1,1,1 if cache_render_size == 'big' then r,g,b = 1,0.7,0.3 elseif cache_render_size == 'medium' then r,g,b = 0.8,1,0 end self.tooltip:DrawText(UIFont.Small, cache_render_text, 5, save_th, r, g, b, 1); stage = 3 else stage = -1 --error end return old_drawRectBorder(self, ...) end old_render(self) self.setHeight = old_setHeight self.drawRectBorder = old_drawRectBorder end --Events.OnRefreshInventoryWindowContainers.Add(onUpdateInventory) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T01:58:09.697", "Id": "455201", "Score": "3", "body": "Hello Maris, please edit your title to explain what your code does and give more detail to what your code does.." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-25T23:32:24.167", "Id": "232975", "Score": "1", "Tags": [ "game", "lua" ], "Title": "Improving a code design of simple game mod for better teamwork" }
232975
<p>My code below creates a folder based on the passed data from my client-side(VueJs) and checks if there's already an existing folder and deletes it if there is otherwise it will create a new one. </p> <p>My problem here is that I think my code is too long and unreadable although it accomplishes the task that I want to happen.</p> <p>Can someone help me to make this code better? </p> <pre><code>router.post('/album', (req, res) =&gt; { let sql = "INSERT INTO GALLERY SET ALBUM = ?, DESCRIPTION = ?"; let body = [req.body.ALBUM, req.body.DESCRIPTION] myDB.query(sql, body, (error, results) =&gt; { if (error) { console.log(error); } else { let directory = `path\\public\\${req.body.ALBUM}`; if (fse.existsSync(directory)) { fse.removeSync(directory, err =&gt; { if (err) { console.log(err); } else { console.log("Success"); } }) } else { fse.mkdirpSync(directory, err =&gt; { if (err) { console.log(object); } else { console.log("Success"); } }) } } }) }) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T01:55:26.127", "Id": "455200", "Score": "0", "body": "Could you add what the `req` object contains in detail? And explain where `fse` is coming from, I'm guessing it's a file system access, but more detail wouldn't hurt." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T07:13:07.290", "Id": "455215", "Score": "0", "body": "What is the benefit from removing the whole directory every time?" } ]
[ { "body": "<p>The built in file system package (fs) provides you with a commands to create directories.</p>\n\n<p><code>fs.mkdirSync(path[, options])</code> <a href=\"https://nodejs.org/api/fs.html#fs_fs_mkdirsync_path_options\" rel=\"nofollow noreferrer\">for synchronous</a></p>\n\n<p><code>fs.mkdir(path[, options], callback)</code> <a href=\"https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback\" rel=\"nofollow noreferrer\">for asynchronous</a></p>\n\n<p>According to their documentation, you can add an option for recursively creating a folder. It also notes </p>\n\n<p>\"<em>Calling fs.mkdir() when path is a directory that exists results in an error only when recursive is false.</em>\"</p>\n\n<p>With this information, you should be able to force it to always create the folder using only this logic:</p>\n\n<pre><code>const fs = require('fs')\nfs.mkdir( directory, { recursive: true }, (err) =&gt; {\n if (err) throw err;\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T18:10:48.780", "Id": "233013", "ParentId": "232977", "Score": "2" } } ]
{ "AcceptedAnswerId": "233013", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T01:39:00.550", "Id": "232977", "Score": "2", "Tags": [ "javascript", "node.js" ], "Title": "Reduce the number of code if possible when creating a folder" }
232977
<p>I've created 2 helpers for <code>std::regex</code>. </p> <p>The first helper <code>match</code> fills the given <code>std::vector&lt;std::pair&lt;std::string, std::size_t&gt;&gt;</code> with the first match with all subgroup matches and their positions. <code>match_all</code> builds on <code>match</code> and sets the given <code>std::vector&lt;std::vector&lt;std::pair&lt;std::string, std::size_t&gt;&gt;&gt;</code> to all the matches in the text.</p> <p>I would like to maybe in the future use <a href="https://github.com/hanickadot/compile-time-regular-expressions" rel="nofollow noreferrer">CTRE</a> instead of <code>std::regex</code> but for now this is what I have:</p> <pre><code>using match_result = std::vector&lt;std::pair&lt;std::string, std::size_t&gt;&gt;; using match_all_result = std::vector&lt;match_result&gt;; std::size_t match(const std::regex&amp; regex, const std::string&amp; input, match_result* result) { std::size_t total{ 0 }; std::smatch m; if (std::regex_search(input, m, regex)) { total = m.size(); if (result != nullptr) { std::size_t startPos{}; std::string original{}; for (size_t i = 0; i &lt; m.size(); i++) { const std::string dataMatch{ m[i] }; std::size_t pos{}; if (i == 0) { //full match startPos = pos = m.position(); original = dataMatch; } else { pos = startPos; if (dataMatch != original) pos += original.find(dataMatch); } result-&gt;emplace_back(dataMatch, pos); } } } return total; } std::size_t match_all(const std::regex&amp; regex, std::string input, match_all_result* result) { match_result m{}; std::size_t positionFix{}; auto first{ true }; std::size_t total{}; while (const auto t = match(regex, input, &amp;m)) { total += t; const auto sumLP = m[0].first.size() + m[0].second; if (first) { positionFix = sumLP; first = false; } else { if (result) { for (auto&amp; [m1, p1] : m) { p1 += positionFix; } } positionFix += sumLP; } //input = input.c_str() + (sumLP); input = input.substr(sumLP); if (result) { result-&gt;push_back(m); m.clear(); } } return total; } </code></pre> <p>You can see the code running here: <a href="https://gcc.godbolt.org/z/wHRZET" rel="nofollow noreferrer">https://gcc.godbolt.org/z/wHRZET</a></p> <p>NOTE: fixed the description as what I had described what my code did previously. It now does not return a vector but expects a pointer to a vector to be passed.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T07:07:58.730", "Id": "232979", "Score": "2", "Tags": [ "c++", "regex" ], "Title": "c++ regex helpers" }
232979
<p>Hey I'm trying to optimise <a href="https://vincentgarreau.com/particles.js/" rel="noreferrer">particles.js library from Vincent Garrau</a> in order to get 60fps @ 500 particles ~.</p> <p>I've already refactored the code to use a quad tree instead but it does not seem to be enough. In fact, I saw no improvement using the quad tree. Maybe I implemented it incorrectly ?</p> <p><strong>What I'm doing ?</strong></p> <ul> <li>Generating n number of particles</li> <li>For each frame : reset the quad tree. For each particle, move it a little and insert it into the tree. Then for each particles, check through a tree query if other particles are close. If there are, draw a line between them. Render the canvas.</li> </ul> <p>Most code below. Full codepen here <a href="https://codepen.io/audrenbdb/pen/NWWVpmQ" rel="noreferrer">https://codepen.io/audrenbdb/pen/NWWVpmQ</a></p> <pre><code>function update () { let particle let ms = 0 quadTree.clear() for (let i = 0, l = particlesList.length; i &lt; l; i++) { particle = particlesList[i] ms = speed / 2 particle.x += particle.vx * ms particle.y += particle.vy * ms let new_pos = bounce ? { x_left: size, x_right: canvas.width, y_top: size, y_bottom: canvas.height } : { x_left: -size, x_right: canvas.width + size, y_top: -size, y_bottom: canvas.height + size } if (particle.x - size &gt; canvas.width) { particle.x = new_pos.x_left particle.y = Math.random() * canvas.height } else if (particle.x + size &lt; 0) { particle.x = new_pos.x_right particle.y = Math.random() * canvas.height } if (particle.y - size &gt; canvas.height) { particle.y = new_pos.y_top particle.x = Math.random() * canvas.width } else if (particle.y + size &lt; 0) { particle.y = new_pos.y_bottom particle.x = Math.random() * canvas.width } if (bounce) { if (particle.x + size &gt; canvas.width) particle.vx = -particle.vx else if (particle.x - size &lt; 0) particle.vx = -particle.vx if (particle.y + size &gt; canvas.height) particle.vy = -particle.vy else if (particle.y - size &lt; 0) particle.vy = -particle.vy } if (interaction.status === 'mousemove') { repulse(particle) } draw(particle) particle.circle.x = particle.x particle.circle.y = particle.y particle.circle.r = linkDistance quadTree.insert(particle) } let explored = [] var i var j for (i = 0; i &lt; particlesList.length; i++) { let links = quadTree.query(particlesList[i].circle) for (j = 0; j &lt; links.length; j++) { if (links[j] !== particlesList[i] &amp;&amp; !explored.includes(links[j])) { linkParticles(particlesList[i], links[j]) } } explored.push(particlesList[i]) } } function repulse (particle) { const dx_mouse = particle.x - interaction.pos_x const dy_mouse = particle.y - interaction.pos_y const dist_mouse = Math.sqrt(Math.pow(dx_mouse, 2) + Math.pow(dy_mouse, 2)) const velocity = 100 const repulseFactor = Math.min( Math.max( (1 / repulseDistance) * (-1 * Math.pow(dist_mouse / repulseDistance, 2) + 1) * repulseDistance * velocity, 0 ), 50 ) let posX = particle.x + (dx_mouse / dist_mouse) * repulseFactor let posY = particle.y + (dy_mouse / dist_mouse) * repulseFactor if (bounce) { if (posX - size &gt; 0 &amp;&amp; posX + size &lt; canvas.width) particle.x = posX if (posY - size &gt; 0 &amp;&amp; posY + size &lt; canvas.height) particle.y = posY } else { particle.x = posX particle.y = posY } } function createParticle () { let x = Math.random() * canvas.width let y = Math.random() * canvas.height const vx = Math.random() - 0.5 const vy = Math.random() - 0.5 if (x &gt; canvas.width - size * 2) x -= size else if (x &lt; size * 2) x += size if (y &gt; canvas.height - size * 2) y -= size else if (y &lt; size * 2) y += size let particle = { x: x, y: y, vx: vx, vy: vy, circle: new Circle(x, y, size) } return particle } function setCanvasSize () { canvas.height = canvas.offsetHeight canvas.width = canvas.offsetWidth boundary = new Rectangle( canvas.width / 2, canvas.height / 2, canvas.width, canvas.height ) quadTree = new QuadTree(boundary, 4) context = canvas.getContext('2d') context.fillRect(0, 0, canvas.width, canvas.height) context.fillStyle = `rgba(${particleRGB},1)`; } function linkParticles (particle1, particle2) { let opacityValue = 1 const dist = Math.sqrt( Math.pow(particle1.x - particle2.x, 2) + Math.pow(particle1.y - particle2.y, 2) ) opacityValue = 1 - dist / (.7 * linkDistance) context.strokeStyle = `rgba(${linkRGB}, ${opacityValue})` context.lineWidth = linkWidth context.beginPath() context.moveTo(particle1.x, particle1.y) context.lineTo(particle2.x, particle2.y) context.stroke() context.closePath() } function draw (particle) { context.beginPath() context.arc( Math.floor(particle.x), Math.floor(particle.y), size, 0, Math.PI * 2, false ) context.closePath() context.fill() } function animate () { context.clearRect(0, 0, canvas.width, canvas.height) update() requestAnimationFrame(animate) } </code></pre> <p><strong>Quad tree code</strong></p> <pre><code>class Circle { constructor (x, y, r) { this.x = x this.y = y this.r = r } contains (point) { let d = Math.pow(point.x - this.x, 2) + Math.pow(point.y - this.y, 2) return d &lt;= this.r * this.r } intersects (range) { let xDyst = Math.abs(range.x - this.x) let yDist = Math.abs(range.y - this.y) let r = this.r let w = range.w let h = range.h let edges = Math.pow(xDist - w, 2) + Math.pow(yDist - h, 2) if (xDist &gt; r + w || yDist &gt; r + h) return false if (xDist &lt;= w || yDist &lt;= h) return true return edges &lt;= this.r * this.r } } class Rectangle { constructor (x, y, w, h) { this.x = x this.y = y this.w = w this.h = h } contains (point) { return ( point.x &gt;= this.x - this.w &amp;&amp; point.x &lt;= this.x + this.w &amp;&amp; point.y &gt;= this.y - this.h &amp;&amp; point.y &lt;= this.y + this.h ) } intersects (range) { return !( range.x - range.w &gt; this.x + this.w || range.x + range.w &lt; this.x - this.w || range.y - range.h &gt; this.y + this.h || range.y + range.h &lt; this.y - this.h ) } } class QuadTree { constructor (boundary, capacity) { this.boundary = boundary this.capacity = capacity this.points = [] this.divided = false } insert (point) { if (!this.boundary.contains(point)) return false if (this.points.length &lt; this.capacity) { this.points.push(point) return true } else { if (!this.divided) { this.subdivide() this.divided = true } if (this.northEast.insert(point)) return true else if (this.northWest.insert(point)) return true else if (this.southEast.insert(point)) return true else if (this.southWest.insert(point)) return true } } subdivide () { let x = this.boundary.x let y = this.boundary.y let w = this.boundary.w let h = this.boundary.h let ne = new Rectangle(x + w / 2, y - h / 2, w / 2, h / 2) let nw = new Rectangle(x - w / 2, y - h / 2, w / 2, h / 2) let se = new Rectangle(x + w / 2, y + h / 2, w / 2, h / 2) let sw = new Rectangle(x - w / 2, y + h / 2, w / 2, h / 2) this.northWest = new QuadTree(ne, this.capacity) this.northEast = new QuadTree(nw, this.capacity) this.southWest = new QuadTree(se, this.capacity) this.southEast = new QuadTree(sw, this.capacity) this.divided = true } query (range, found = []) { if (!this.boundary.intersects(range)) { } else { for (let p of this.points) { if (range.contains(p)) { found.push(p) } } if (this.divided) { this.northEast.query(range, found) this.northWest.query(range, found) this.southEast.query(range, found) this.southWest.query(range, found) } return found } } clear () { if (this.divided) { delete this.northEast delete this.northWest delete this.southEast delete this.southWest } this.points = [] this.divided = false } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T13:14:18.463", "Id": "455248", "Score": "0", "body": "variables are set in the very begining. You can see them in the codepen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T13:18:19.097", "Id": "455249", "Score": "0", "body": "Ok, I've checked that link. Besides, that visualization is pretty impressive, looks nice" } ]
[ { "body": "<h3>Some set of functional improvements/corrections for <code>QuadTree</code> class</h3>\n\n<ul>\n<li><p><strong><code>QuadTree.insert</code></strong> method.<br>In such a conditional:</p>\n\n<pre><code>if (this.points.length &lt; this.capacity) {\n this.points.push(point)\n return true\n} else {\n ...\n</code></pre>\n\n<p>specifying <code>else</code> branch doesn't make sense as the 1st <code>if</code> branch, if <em>truthy</em>, will <code>return</code> immediately from the function.</p>\n\n<p>A sequence of exclusive conditions</p>\n\n<pre><code>if (this.northEast.insert(point)) return true\nelse if (this.northWest.insert(point)) return true\nelse if (this.southEast.insert(point)) return true\nelse if (this.southWest.insert(point)) return true\n</code></pre>\n\n<p>returns the same result, therefore can be appropriately consolidated. </p>\n\n<p>The final optimized version:</p>\n\n<pre><code>insert(point) {\n if (!this.boundary.contains(point)) return false\n if (this.points.length &lt; this.capacity) {\n this.points.push(point)\n return true\n }\n if (!this.divided) {\n this.subdivide()\n this.divided = true\n }\n\n if ((this.northEast.insert(point)) ||\n (this.northWest.insert(point)) ||\n (this.southEast.insert(point)) ||\n (this.southWest.insert(point))) return true\n}\n</code></pre></li>\n<li><p><strong><code>QuadTree.subdivide</code></strong> method.<br>As boundary width <code>w</code> and height <code>h</code> are only used in context of their <em>halved</em> values - those factors can be calculated at once to avoid <strong>16</strong> repetitive divisions:</p>\n\n<pre><code>subdivide() {\n let x = this.boundary.x,\n y = this.boundary.y,\n w = this.boundary.w / 2,\n h = this.boundary.h / 2;\n\n let ne = new Rectangle(x + w, y - h, w, h);\n let nw = new Rectangle(x - w, y - h, w, h);\n let se = new Rectangle(x + w, y + h, w, h);\n let sw = new Rectangle(x - w, y + h, w, h);\n\n this.northWest = new QuadTree(ne, this.capacity);\n this.northEast = new QuadTree(nw, this.capacity);\n this.southWest = new QuadTree(se, this.capacity);\n this.southEast = new QuadTree(sw, this.capacity);\n\n this.divided = true;\n}\n</code></pre></li>\n<li><p><strong><code>QuadTree.query</code></strong> method.<br>The construction</p>\n\n<pre><code>if (!this.boundary.intersects(range)) {\n} else {\n</code></pre>\n\n<p>is just an awkwardly flipped equivalent to:</p>\n\n<pre><code>if (this.boundary.intersects(range)) {\n ...\n</code></pre>\n\n<p>Iterating over <code>this.points</code> with</p>\n\n<pre><code>for (let p of this.points) {\n if (range.contains(p)) {\n found.push(p)\n }\n}\n</code></pre>\n\n<p>can be flexibly replaced with <code>Array.filter</code> approach.<br>\nEventually the function/method would look as:</p>\n\n<pre><code>query(range, found = []) {\n if (this.boundary.intersects(range)) {\n found.push(...this.points.filter((p) =&gt; range.contains(p)));\n if (this.divided) {\n this.northEast.query(range, found)\n this.northWest.query(range, found)\n this.southEast.query(range, found)\n this.southWest.query(range, found)\n }\n return found\n }\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T13:20:58.933", "Id": "455251", "Score": "0", "body": "thanks alot I'll look into it. I think I also need to nail ways to improve how I render canvas and its particles" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T13:09:00.043", "Id": "232995", "ParentId": "232980", "Score": "2" } }, { "body": "<p>Great question, some possible pointers;</p>\n\n<ul>\n<li>Use the Chrome Dev Tool Performance, it will show you where the code slows down:\n<a href=\"https://i.stack.imgur.com/RudZm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RudZm.png\" alt=\"enter image description here\"></a></li>\n<li><p>Avoid floating-point coordinates and use integers instead with canvas calls, so</p>\n\n<pre><code> context.moveTo(~~particle1.x, ~~particle1.y)\n context.lineTo(~~particle2.x, ~~particle2.y)\n</code></pre></li>\n<li><p>A double bitwise NOT <code>~~</code> is the same as calling, <code>Math.floor()</code> but faster.</p>\n\n<p>It made <code>linkParticles</code> 30% faster for me</p></li>\n<li><p>Because this does not require a transparent background, you could instantiate the context like this</p>\n\n<p><code>var ctx = canvas.getContext('2d', { alpha: false })</code> </p>\n\n<p>and then replace <code>clearRect</code> with <code>fillRect</code> so that you get your blue background</p></li>\n<li>Finally, you want to consider batching up your lines, because ultimately the program draws very large spiderweb like images.</li>\n<li>I was reading up on <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas/OffscreenCanvas\" rel=\"nofollow noreferrer\">OffscreenCanvas</a>, but I don't think it will speed this up much</li>\n<li>Finally, it seems that the basic Canvas methods are slowing this down, you may want to investigate rewriting this with <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context\" rel=\"nofollow noreferrer\">WebGL</a></li>\n</ul>\n\n<p>You can find some good reading <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Optimizing_canvas\" rel=\"nofollow noreferrer\">here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T20:30:23.523", "Id": "455321", "Score": "0", "body": "Thanks for these nice suggestions. What do you mean by batching up your lines ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T21:46:29.023", "Id": "455328", "Score": "0", "body": "I mean to draw more than 1 line with 1 openpath/ closepath pair, a lot of lines are connected you could draw them in 1 go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T22:09:00.140", "Id": "455330", "Score": "0", "body": "excellent idea, I'll post an update soon" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T22:48:20.097", "Id": "455334", "Score": "0", "body": "I don't think I can draw more than 1 line per open path considering opacity is different on each line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T23:04:10.207", "Id": "455335", "Score": "0", "body": "Found a good improvement though. Create a single particle canvas that I just use on every `draw()`call with drawImage" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T18:41:50.990", "Id": "233015", "ParentId": "232980", "Score": "2" } }, { "body": "<p>See rewrite example to see how these changes are implemented.</p>\n\n<ul>\n<li>Batch render calls to avoid GPU state changes.</li>\n<li>Reuse arrays, don't delete them or recreate them. In the rewrite the array of found particles is never deleted. Rather than use its <code>length</code> there is a new <code>foundCount</code> that is used to add found points and return the number of points found from <code>QuadTree.query</code></li>\n<li>Reuse data structures rather than delete and rebuild. The <code>quadTree</code> uses the <code>close</code> function to close all quads but does not delete the quads so it is much faster next frame as it does not need to rebuild what will be a very similar data structure. </li>\n<li>Use flags to avoid array searches. The loop where you find links you keep an array of explored items. For each found point you search that array. All you need to do is mark the point as explored saving you having to do all those searches.</li>\n</ul>\n\n<p>There are many more changes but this was a little longer than I expected and I am way over it now.</p>\n\n<p>In the example rewrite I removed the <code>bounce</code> setting (sorry I took it out before I knew what it was for and forgot to put it back.). Your copy has bounce set to false to match the rewrite.</p>\n\n<h3>UPDATE</h3>\n\n<p>I am refreshed and looked over the code to notice some issues that I have fixed. Poor timing fixed, Quad name miss matches <code>NE</code> was <code>NW</code>, and the distance check in the quad query was too small so doubled the size.</p>\n\n<p>Also added a few more optimizations.</p>\n\n<ul>\n<li>Added a <code>depth</code> property to quads. Only starts adding particles to quads 2 levels down or deeper.</li>\n<li>Quad point arrays do not change length. The quad property <code>pointCount</code> now used rather than the <code>points.length</code></li>\n<li>Top three quad layers are never closed.</li>\n<li>Use the <code>pointCount</code> as early query skip when querying quads.</li>\n</ul>\n\n<p>And some other minor changes unrelated to performance</p>\n\n<h2>Your code</h2>\n\n<p>Your code copied from the link you provided with a few small mods made to fit the CR snippet and display the render time.</p>\n\n<p>The render time in the top left is the <strike>mean render time in ~1second blocks</strike> running mean time over 10 rendered frames.</p>\n\n<p>On the laptop I am using this renders in about ~50ms</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const number = 200\nconst speed = 6\nconst linkWidth = 1\nconst linkDistance = 120\nconst size = 2\nconst repulseDistance = 140\nconst particleRGB = '255, 255, 255'\nconst linkRGB = '255, 255, 255'\nconst bounce = false\n\n\n\nlet interaction = {\n status: 'mouseleave',\n pos_x: 0,\n pos_y: 0\n}\nlet particlesList = []\nlet quadTree\nlet boundary\n\nlet canvas\nlet context\n\nwindow.onload = () =&gt; {\n canvas = document.getElementById('quad-tree')\n canvas.style.height = \"100%\"\n canvas.style.width = \"100%\"\n\n setCanvasSize()\n \n for (let i = 0; i &lt; number; i++) {\n let particle = createParticle()\n particlesList.push(particle)\n quadTree.insert(particle)\n }\n\n window.addEventListener('resize', () =&gt; setCanvasSize())\n canvas.addEventListener('mousemove', e =&gt; {\n interaction.pos_x = e.offsetX\n interaction.pos_y = e.offsetY\n interaction.status = 'mousemove'\n })\n canvas.addEventListener('mouseleave', () =&gt; {\n interaction.pos_x = null\n interaction.pos_y = null\n interaction.status = 'mouseleave'\n })\n animate()\n}\n\nfunction update () {\n let particle\n let ms = 0\n quadTree.clear()\n\n for (let i = 0, l = particlesList.length; i &lt; l; i++) {\n particle = particlesList[i]\n ms = speed / 2\n particle.x += particle.vx * ms\n particle.y += particle.vy * ms\n\n let new_pos = bounce\n ? {\n x_left: size,\n x_right: canvas.width,\n y_top: size,\n y_bottom: canvas.height\n }\n : {\n x_left: -size,\n x_right: canvas.width + size,\n y_top: -size,\n y_bottom: canvas.height + size\n }\n\n if (particle.x - size &gt; canvas.width) {\n particle.x = new_pos.x_left\n particle.y = Math.random() * canvas.height\n } else if (particle.x + size &lt; 0) {\n particle.x = new_pos.x_right\n particle.y = Math.random() * canvas.height\n }\n if (particle.y - size &gt; canvas.height) {\n particle.y = new_pos.y_top\n particle.x = Math.random() * canvas.width\n } else if (particle.y + size &lt; 0) {\n particle.y = new_pos.y_bottom\n particle.x = Math.random() * canvas.width\n }\n\n if (bounce) {\n if (particle.x + size &gt; canvas.width) particle.vx = -particle.vx\n else if (particle.x - size &lt; 0) particle.vx = -particle.vx\n if (particle.y + size &gt; canvas.height) particle.vy = -particle.vy\n else if (particle.y - size &lt; 0) particle.vy = -particle.vy\n }\n\n if (interaction.status === 'mousemove') {\n repulse(particle)\n }\n\n draw(particle)\n\n particle.circle.x = particle.x\n particle.circle.y = particle.y\n particle.circle.r = linkDistance\n quadTree.insert(particle)\n }\n\n let explored = []\n var i\n var j\n for (i = 0; i &lt; particlesList.length; i++) {\n let links = quadTree.query(particlesList[i].circle)\n for (j = 0; j &lt; links.length; j++) {\n if (links[j] !== particlesList[i] &amp;&amp; !explored.includes(links[j])) {\n linkParticles(particlesList[i], links[j])\n }\n }\n explored.push(particlesList[i])\n }\n}\n\nfunction repulse (particle) {\n const dx_mouse = particle.x - interaction.pos_x\n const dy_mouse = particle.y - interaction.pos_y\n const dist_mouse = Math.sqrt(Math.pow(dx_mouse, 2) + Math.pow(dy_mouse, 2))\n const velocity = 100\n\n const repulseFactor = Math.min(\n Math.max(\n (1 / repulseDistance) *\n (-1 * Math.pow(dist_mouse / repulseDistance, 2) + 1) *\n repulseDistance *\n velocity,\n 0\n ),\n 50\n )\n let posX = particle.x + (dx_mouse / dist_mouse) * repulseFactor\n let posY = particle.y + (dy_mouse / dist_mouse) * repulseFactor\n\n if (bounce) {\n if (posX - size &gt; 0 &amp;&amp; posX + size &lt; canvas.width) particle.x = posX\n if (posY - size &gt; 0 &amp;&amp; posY + size &lt; canvas.height) particle.y = posY\n } else {\n particle.x = posX\n particle.y = posY\n }\n}\n\nfunction createParticle () {\n let x = Math.random() * canvas.width\n let y = Math.random() * canvas.height\n const vx = Math.random() - 0.5\n const vy = Math.random() - 0.5\n\n if (x &gt; canvas.width - size * 2) x -= size\n else if (x &lt; size * 2) x += size\n if (y &gt; canvas.height - size * 2) y -= size\n else if (y &lt; size * 2) y += size\n\n let particle = {\n x: x,\n y: y,\n vx: vx,\n vy: vy,\n circle: new Circle(x, y, size)\n }\n return particle\n}\n\nfunction setCanvasSize () {\n canvas.height = innerHeight\n canvas.width = innerWidth\n boundary = new Rectangle(\n canvas.width / 2,\n canvas.height / 2,\n canvas.width,\n canvas.height\n )\n quadTree = new QuadTree(boundary, 4)\n\n context = canvas.getContext('2d')\n context.fillRect(0, 0, canvas.width, canvas.height)\n\n context.fillStyle = `rgba(${particleRGB},1)`;\n}\n\nfunction linkParticles (particle1, particle2) {\n let opacityValue = 1\n const dist = Math.sqrt(\n Math.pow(particle1.x - particle2.x, 2) +\n Math.pow(particle1.y - particle2.y, 2)\n )\n opacityValue = 1 - dist / 80\n context.strokeStyle = `rgba(${linkRGB}, ${opacityValue})`\n context.lineWidth = linkWidth\n context.beginPath()\n context.moveTo(particle1.x, particle1.y)\n context.lineTo(particle2.x, particle2.y)\n context.stroke()\n context.closePath()\n}\n\nfunction draw (particle) {\n context.beginPath()\n context.arc(\n Math.floor(particle.x),\n Math.floor(particle.y),\n size,\n 0,\n Math.PI * 2,\n false\n )\n context.closePath()\n context.fill()\n}\n\n\nvar times = [];\nvar renderCount = 0 \nfunction animate () {\n context.clearRect(0, 0, canvas.width, canvas.height)\n const now = performance.now();\n update()\n renderCount += 1;\n times[renderCount % 10] = (performance.now() - now);\n const total = times.reduce((total, time) =&gt; total + time, 0);\n\n info.textContent = \"Running ave render time: \" + (total / times.length).toFixed(3) + \"ms\";\n requestAnimationFrame(animate)\n}\n\n\nclass Circle {\n constructor (x, y, r) {\n this.x = x\n this.y = y\n this.r = r\n }\n\n contains (point) {\n let d = Math.pow(point.x - this.x, 2) + Math.pow(point.y - this.y, 2)\n return d &lt;= this.r * this.r\n }\n\n intersects (range) {\n let xDyst = Math.abs(range.x - this.x)\n let yDist = Math.abs(range.y - this.y)\n\n let r = this.r\n\n let w = range.w\n let h = range.h\n\n let edges = Math.pow(xDist - w, 2) + Math.pow(yDist - h, 2)\n\n if (xDist &gt; r + w || yDist &gt; r + h) return false\n if (xDist &lt;= w || yDist &lt;= h) return true\n return edges &lt;= this.r * this.r\n }\n}\n\nclass Rectangle {\n constructor (x, y, w, h) {\n this.x = x\n this.y = y\n this.w = w\n this.h = h\n }\n\n contains (point) {\n return (\n point.x &gt;= this.x - this.w &amp;&amp;\n point.x &lt;= this.x + this.w &amp;&amp;\n point.y &gt;= this.y - this.h &amp;&amp;\n point.y &lt;= this.y + this.h\n )\n }\n\n intersects (range) {\n return !(\n range.x - range.w &gt; this.x + this.w ||\n range.x + range.w &lt; this.x - this.w ||\n range.y - range.h &gt; this.y + this.h ||\n range.y + range.h &lt; this.y - this.h\n )\n }\n}\n\nclass QuadTree {\n constructor (boundary, capacity) {\n this.boundary = boundary\n this.capacity = capacity\n this.points = []\n this.divided = false\n }\n\n insert (point) {\n if (!this.boundary.contains(point)) return false\n if (this.points.length &lt; this.capacity) {\n this.points.push(point)\n return true\n } else {\n if (!this.divided) {\n this.subdivide()\n this.divided = true\n }\n\n if (this.northEast.insert(point)) return true\n else if (this.northWest.insert(point)) return true\n else if (this.southEast.insert(point)) return true\n else if (this.southWest.insert(point)) return true\n }\n }\n\n subdivide () {\n let x = this.boundary.x\n let y = this.boundary.y\n let w = this.boundary.w\n let h = this.boundary.h\n\n let ne = new Rectangle(x + w / 2, y - h / 2, w / 2, h / 2)\n let nw = new Rectangle(x - w / 2, y - h / 2, w / 2, h / 2)\n let se = new Rectangle(x + w / 2, y + h / 2, w / 2, h / 2)\n let sw = new Rectangle(x - w / 2, y + h / 2, w / 2, h / 2)\n\n this.northWest = new QuadTree(ne, this.capacity)\n this.northEast = new QuadTree(nw, this.capacity)\n this.southWest = new QuadTree(se, this.capacity)\n this.southEast = new QuadTree(sw, this.capacity)\n\n this.divided = true\n }\n\n query (range, found = []) {\n if (!this.boundary.intersects(range)) {\n } else {\n for (let p of this.points) {\n if (range.contains(p)) {\n found.push(p)\n }\n }\n if (this.divided) {\n this.northEast.query(range, found)\n this.northWest.query(range, found)\n this.southEast.query(range, found)\n this.southWest.query(range, found)\n }\n return found\n }\n }\n\n clear () {\n if (this.divided) {\n delete this.northEast\n delete this.northWest\n delete this.southEast\n delete this.southWest\n }\n this.points = []\n this.divided = false\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.float {\n position: absolute;\n top: 0px;\n left: 0px;\n}\ncanvas {\n background: #59F;\n}\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;canvas class=\"float\" id=\"quad-tree\"&gt;&lt;/canvas&gt;\n&lt;code class=\"float\" id=\"info\"&gt;&lt;/code&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>Rewrite 20 times faster.</h2>\n\n<p>Again the time is in the top corner to show performance. </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\nconst number = 200;\nconst speed = 1;\nconst linkWidth = 0.5;\nconst linkDistance = 120;\nconst size = 1.5;\nvar repulseDistance = repulseDistance = Math.min(innerWidth,innerHeight) / 6;\nconst PARTICLES_PER_QUAD = 4;\nconst linkDistance2 = (0.7 * linkDistance) ** 2;\nconst repulseDistance2 = repulseDistance ** 2;\nvar showQuads = false;\nMath.TAU = Math.PI * 2;\nconst particleStyle = \"#FFF\";\nconst linkRGB = \"#FFF\";\nconst quadStyle = \"#F00\";\nconst candidates = [];\nvar W,H;\n\nconst mouse = { x: 0, y: 0}\nconst particlesList = [];\nconst links = [[],[],[],[]];\nconst linkBatchAlphas = [0.2, 0.4, 0.7, 0.9];\nconst linkBatches = links.length;\nconst linkPool = [];\nlet quadTree;\nlet boundary;\nconst ctx = canvas.getContext(\"2d\");\nW = canvas.height = innerHeight;\nH = canvas.width = innerWidth;\ncanvas.addEventListener('mousemove', e =&gt; {\n mouse.x = e.offsetX;\n mouse.y = e.offsetY;\n})\ncanvas.addEventListener('click', e =&gt; {\n showQuads = !showQuads;\n \n})\n\nsetTimeout(start, 42);\n\nfunction start(){ \n quadTree = new QuadTree();\n for (let i = 0; i &lt; number; i++) {\n particlesList.push(new Particle(canvas, size));\n }\n\n animate();\n}\n\n \nvar times = [];\nvar renderCount = 0 \nfunction animate () {\n if (canvas.width !== innerWidth || canvas.height !== innerHeight) { setCanvasSize() }\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n const now = performance.now();\n updateParticles();\n updateLinks();\n\n\n renderCount += 1;\n times[renderCount % 10] = (performance.now() - now);\n const total = times.reduce((total, time) =&gt; total + time, 0);\n\n info.textContent = \"Running ave render time: \" + (total / times.length).toFixed(3) + \"ms\";\n\n\n requestAnimationFrame(animate);\n\n}\n\nfunction updateParticles() { \n quadTree.close();\n ctx.fillStyle = particleStyle;\n ctx.beginPath();\n for (const particle of particlesList) { particle.update(ctx, true) }\n ctx.fill();\n}\nfunction updateLinks() {\n\n var i,j, link;\n \n if(showQuads) {\n ctx.strokeStyle = quadStyle;\n ctx.lineWidth = 1;\n ctx.beginPath();\n }\n for(const p1 of particlesList) {\n p1.explored = true;\n const count = quadTree.query(p1, 0, candidates);\n for (j = 0; j &lt; count; j++) {\n const p2 = candidates[j];\n if (!p2.explored) {\n link = linkPool.length ? linkPool.pop() : new Link();\n link.init(p1, candidates[j]);\n links[link.batchId].push(link);\n }\n }\n }\n if(showQuads) { ctx.stroke() }\n var alphaIdx = 0;\n ctx.lineWidth = linkWidth;\n ctx.strokeStyle = linkRGB;\n for(const l of links) {\n ctx.globalAlpha = linkBatchAlphas[alphaIdx++]; \n \n ctx.beginPath();\n while(l.length) { linkPool.push(l.pop().addPath(ctx)) }\n ctx.stroke();\n }\n ctx.globalAlpha = 1;\n}\nfunction resetParticles() {\n quadTree = new QuadTree();\n for (const particle of particlesList) { particle.reset(canvas) };\n\n \n}\n\nfunction setCanvasSize () {\n W = canvas.height = innerHeight;\n H = canvas.width = innerWidth;\n repulseDistance = Math.min(W,H) / 12;\n resetParticles();\n}\n\n\n\nclass Link {\n constructor() { }\n init(p1, p2) { // p1,p2 are particles\n this.p1 = p1;\n this.p2 = p2;\n const dx = p1.x - p2.x;\n const dy = p1.y - p2.y;\n this.alpha = 1 - (dx * dx + dy * dy) / linkDistance2;\n this.batchId = this.alpha * linkBatches | 0;\n this.batchId = this.batchId &gt;= linkBatches ? linkBatches : this.batchId;\n } \n addPath(ctx) {\n ctx.moveTo(this.p1.x, this.p1.y);\n ctx.lineTo(this.p2.x, this.p2.y);\n return this;\n }\n \n}\n\n\nclass Particle {\n constructor (canvas, r) {\n this.r = r;\n this.speedScale = speed / 2;\n this.reset(canvas, r);\n }\n reset(canvas, r = this.r) {\n const W = canvas.width - r * 2; // Canvas width and height reduced so \n // that the bounds check is not needed\n const H = canvas.height - r * 2;\n this.x = Math.random() * W + r;\n this.y = Math.random() * H + r;\n this.vx = Math.random() - 0.5;\n this.vy = Math.random() - 0.5;\n this.quad = undefined;\n this.explored = false;\n\n }\n addPath(ctx) {\n //ctx.moveTo(this.x + this.r, this.y);\n //ctx.arc(this.x, this.y, this.r, 0, Math.TAU);\n ctx.rect(this.x - this.r, this.y - this.r, this.r * 2, this.r * 2);\n }\n near(p) {\n return ((p.x - this.x) ** 2 + (p.y - this.y) ** 2) &lt;= linkDistance2;\n }\n intersects(range) {\n const xd = Math.abs(range.x - this.x);\n const yd = Math.abs(range.y - this.y);\n const r = linkDistance;\n const w = range.w;\n const h = range.h;\n if (xd &gt; r + w || yd &gt; r + h) { return false }\n if (xd &lt;= w || yd &lt;= h) { return true }\n return ((xd - w) ** 2 + (yd - h) ** 2) &lt;= linkDistance2;\n\n }\n update(ctx, repulse = true) { \n this.explored = false;\n const r = this.r;\n const W = ctx.canvas.width + r;\n const H = ctx.canvas.height + r;\n this.x += this.vx * this.speedScale;\n this.y += this.vy * this.speedScale;\n if (this.x &gt; W) {\n this.x = 0;\n this.y = Math.random() * (H - r);\n } else if (this.x &lt; -r) {\n this.x = W - r;\n this.y = Math.random() * (H - r);\n }\n if (this.y &gt; H) {\n this.y = 0\n this.x = Math.random() * (W - r);\n } else if (this.y &lt; -r) {\n this.y = H - r;\n this.x = Math.random() * (W - r);\n }\n repulse &amp;&amp; this.repulse();\n this.addPath(ctx);\n quadTree.insert(this);\n this.quad &amp;&amp; (this.quad.drawn = false)\n }\n repulse() {\n // I have simplified the math (I did not check as I went so behaviour may vary a little from the original)\n var dx = this.x - mouse.x;\n var dy = this.y - mouse.y;\n\n const dist = (dx * dx + dy * dy) ** 0.5;\n var rf = ((1 - (dist / repulseDistance) ** 2) * 100);\n rf = (rf &lt; 0 ? 0 : rf &gt; 50 ? 50 : rf) / dist; // ternary is quicker than Math.max(Math.min(rf,50), 0) \n this.x += dx * rf;\n this.y += dy * rf;\n }\n}\n\nclass Bounds {\n constructor(x, y, w, h) { this.init(x, y, w, h) }\n init(x,y,w,h) { \n this.x = x; \n this.y = y; \n this.w = w; \n this.h = h; \n this.left = x - w;\n this.right = x + w;\n this.top = y - h;\n this.bottom = y + h;\n this.diagonal = (w * w + h * h);\n }\n\n contains(p) {\n return (p.x &gt;= this.left &amp;&amp; p.x &lt;= this.right &amp;&amp; p.y &gt;= this.top &amp;&amp; p.y &lt;= this.bottom);\n }\n\n near(p) {\n if (!this.contains(p)) {\n const dx = p.x - this.x;\n const dy = p.y - this.y;\n const dist = (dx * dx + dy * dy) - this.diagonal - linkDistance2;\n return dist &lt; 0;\n }\n return true;\n }\n}\n\nclass QuadTree {\n constructor(boundary, depth = 0) {\n this.boundary = boundary || new Bounds(canvas.width / 2,canvas.height / 2,canvas.width / 2 ,canvas.height / 2);\n this.divided = false; \n this.points = depth &gt; 1 ? [] : null;\n this.pointCount = 0\n this.drawn = false;\n this.depth = depth;\n if(depth === 0) { // BM67 Fix on resize\n this.subdivide();\n this.NE.subdivide();\n this.NW.subdivide();\n this.SE.subdivide();\n this.SW.subdivide();\n }\n\n\n }\n\n addPath() { // getting ctx from global as this was a last min change\n const b = this.boundary;\n ctx.rect(b.left, b.top, b.w * 2, b.h * 2);\n this.drawn = true;\n }\n addToSubQuad(particle) {\n if (this.NE.insert(particle)) { return true }\n if (this.NW.insert(particle)) { return true }\n if (this.SE.insert(particle)) { return true }\n if (this.SW.insert(particle)) { return true } \n particle.quad = undefined; \n }\n insert(particle) {\n if (this.depth &gt; 0 &amp;&amp; !this.boundary.contains(particle)) { return false }\n \n if (this.depth &gt; 1 &amp;&amp; this.pointCount &lt; PARTICLES_PER_QUAD) { \n this.points[this.pointCount++] = particle;\n particle.quad = this;\n return true;\n } \n if (!this.divided) { this.subdivide() }\n return this.addToSubQuad(particle);\n }\n\n subdivide() {\n if (!this.NW) { // if this is undefined we know all 4 are undefined\n const x = this.boundary.x;\n const y = this.boundary.y;\n const w = this.boundary.w / 2;\n const h = this.boundary.h / 2;\n const depth = this.depth + 1;\n\n this.NE = new QuadTree(new Bounds(x + w, y - h, w, h), depth);\n this.NW = new QuadTree(new Bounds(x - w, y - h, w, h), depth); \n this.SE = new QuadTree(new Bounds(x + w, y + h, w, h), depth);\n this.SW = new QuadTree(new Bounds(x - w, y + h, w, h), depth);\n } else {\n this.NE.pointCount = 0;\n this.NW.pointCount = 0; \n this.SE.pointCount = 0;\n this.SW.pointCount = 0; \n }\n\n this.divided = true;\n }\n query(part, fc, found) { //part = particle fc found count\n var i = this.pointCount;\n if (this.depth === 0 || this.boundary.near(part)) {\n if (this.depth &gt; 1) {\n showQuads &amp;&amp; !this.drawn &amp;&amp; this.addPath();\n while (i--) {\n const p = this.points[i];\n if (!p.explored &amp;&amp; part.near(p)) { found[fc++] = p }\n }\n if (this.divided) {\n fc = this.NE.pointCount ? this.NE.query(part, fc, found) : fc;\n fc = this.NW.pointCount ? this.NW.query(part, fc, found) : fc;\n fc = this.SE.pointCount ? this.SE.query(part, fc, found) : fc;\n fc = this.SW.pointCount ? this.SW.query(part, fc, found) : fc;\n }\n } else if(this.divided) { // BM67 Fix on resize\n fc = this.NE.query(part, fc, found);\n fc = this.NW.query(part, fc, found);\n fc = this.SE.query(part, fc, found);\n fc = this.SW.query(part, fc, found);\n }\n }\n return fc;\n }\n\n close() {\n if (this.divided) {\n this.NE.close();\n this.NW.close();\n this.SE.close();\n this.SW.close();\n }\n \n if (this.depth === 2 &amp;&amp; this.divided) { // BM67 Fix on resize\n this.NE.pointCount = 0;\n this.NW.pointCount = 0;\n this.SE.pointCount = 0;\n this.SW.pointCount = 0;\n } else if (this.depth &gt; 2) {\n this.divided = false;\n }\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.float {\n position: absolute;\n top: 0px;\n left: 0px;\n}\ncanvas {\n background: #59F;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;canvas class=\"float\" id=\"canvas\"&gt;&lt;/canvas&gt;\n&lt;code class=\"float\" id=\"info\"&gt;&lt;/code&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T06:34:15.683", "Id": "455362", "Score": "0", "body": "That's amazing, thanks, on my way to read, understand then refactor !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T11:29:13.667", "Id": "455385", "Score": "0", "body": "Yes I've seen the switch between NW and NE, thought you were tired ! I'm adding the repulse function. Also I've noticed that I can use drawImage() and \"duplicate\" the same particle in many different positions. I've seen a very significant perf gain. I'll try to post asap. You nailed alot of optimizations!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:23:47.127", "Id": "455425", "Score": "0", "body": "I get quite often pointCount is undefined when resizing multiple times the window. I have a hard time grasping out what happens." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:50:58.477", "Id": "455429", "Score": "0", "body": "@AdoRen Could not reproduce error but there are some bad points in the code when resizing creates a new quad tree and code assumes its already built. Have added update to snippet and marked them with `// BM67 Fix on resize` In `QuadTree` constructor, `QuadTree.close` and `QuadTree.query` with luck that will solve the problem." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T00:48:42.803", "Id": "233032", "ParentId": "232980", "Score": "3" } } ]
{ "AcceptedAnswerId": "233032", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T07:34:55.893", "Id": "232980", "Score": "6", "Tags": [ "javascript", "performance", "canvas" ], "Title": "Performance in particles.js library" }
232980
<p>I created this program originally for <a href="https://projecteuler.net/problem=14" rel="nofollow noreferrer">Project Euler 14</a>.</p> <p>Here's the code:</p> <pre><code>from sys import setrecursionlimit setrecursionlimit(10 ** 9) def memo(f): f.cache = {} def _f(*args): if args not in f.cache: f.cache[args] = f(*args) return f.cache[args] return _f @memo def collatz(n): if n == 1: return 1 if n % 2: print(3 * n + 1) return 1 + collatz(3 * n + 1) if not n % 2: print(n // 2) return 1 + collatz(n // 2) if __name__ == '__main__': number = None while True: try: number = input('Please enter a number: ') number = int(number) break except ValueError: print(f'Value has to be an interger instead of "{number}"\n') print('\nThe collatz sequence: ') length = collatz(number) print(f'\nLength of the collatz sequence for {number}: {length}') </code></pre> <p>I would like to make this faster and neater if possible.</p>
[]
[ { "body": "<h2>Useless Code</h2>\n\n<p>Your <code>@memo</code>-ization doesn't do anything of value:</p>\n\n<ul>\n<li>Your mainline calls <code>collatz()</code> exactly once. Unless given the value <code>1</code>, the <code>collatz()</code> function calls itself with <code>3*n + 1</code> or <code>n // 2</code>, and since the Collatz sequence doesn't have any loops until the value <code>1</code> is reached, it will never call itself with a value it has already been called with. So, you are memoizing values which will never, ever be used.</li>\n<li>Your <code>collatz()</code> function doesn't just return a value; it has a side-effect: printing! If you did call <code>collatz()</code> with a value that has already been memoized, nothing will be printed.</li>\n</ul>\n\n<h2>Tail Call, without Tail Call Optimization</h2>\n\n<p>You've increased the recursion limit to <span class=\"math-container\">\\$10^9\\$</span> stack levels, which is impressive. But the algorithm doesn't need to be recursive. A simple loop would work. And since Python cannot do Tail Call Optimization, you should replace recursion with loops wherever possible. Doing so eliminates the need for the increased stack limit:</p>\n\n<pre><code>def collatz(n):\n count = 1\n\n while n &gt; 1:\n if n % 2 != 0:\n n = n * 3 + 1\n else:\n n //= 2\n\n print(n)\n count += 1\n\n return count\n</code></pre>\n\n<h2>Separate Sequence Generation from Printing</h2>\n\n<p>You can create a very simple Collatz sequence generator:</p>\n\n<pre><code>def collatz(n):\n while n &gt; 1:\n yield n\n n = n * 3 + 1 if n % 2 else n // 2\n yield 1\n</code></pre>\n\n<p>Using this generator, the caller can print out the Collatz sequence with a simple loop:</p>\n\n<pre><code>for x in collatz(13):\n print(x)\n</code></pre>\n\n<p>Or, if the caller just wants the length of the Collatz sequence, without printing out each item in the sequence, you can determine the length of the sequence with <code>len(list(collatz(13)))</code>. Better would be to count the items returned by the generator without realizing the list in memory: <code>sum(1 for _ in collatz(13))</code>.</p>\n\n<h2>Project Euler 14</h2>\n\n<p>The above generator works great for determining the sequence from any arbitrary value. If you want to compute the length of <code>collatz(n)</code> for <span class=\"math-container\">\\$1 \\le n \\le 1,000,000\\$</span>, you may want to return to memoization. However, this is Code Review, and while you alluded to PE14, you didn't actually provide code for that, so that cannot be reviewed here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T04:51:06.740", "Id": "233046", "ParentId": "232981", "Score": "2" } } ]
{ "AcceptedAnswerId": "233046", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T08:42:06.470", "Id": "232981", "Score": "2", "Tags": [ "python", "python-3.x", "collatz-sequence" ], "Title": "Collatz sequence using Python 3.x" }
232981
<p>I recently worked with some pickle files which had a really strange format where the keys are sometimes delimiter separated with colons and placed in the same depth but also mixed with ordinary key value pairs.</p> <p>This is a basic example of this mixed format:</p> <pre><code>{ "objects": { "list::1": { "attr1": "foo" "attr2": "bar" }, "list::2": { "attr1": "foo" "attr2": "bar" }, "list::3": { "attr1": "foo" "attr2": "bar" "nested::data::inner": { "test": 1 } } }, "dates": { "2018::11::01": true, "2018::11::02": false, "2018::10::02": false, } } </code></pre> <p>The challenge was to convert this to a .mat file so it can be analyzed using matlab. However, because the length of the fields are sometimes > 63 (the delimiter separated string) the conversion was unsuccessful. This is my implementation on normalizing these mixed format nested dictionaries.</p> <p>Maybe there is an inverse to json_normalize() from pandas library to do this?</p> <pre><code>import json mydict = { "a": { "test::test2::test3::test4": { "name": "ok", "age": 1 }, "test::test2::test4::test4": { "name": "ok1", "age": 2 }, "test::test2::test4::test5": { "name": "ok1", "body::head::foot": { "age": 2, "thing": "test" } } }, "b": { "name": "ok2", "age": "test2" } } def set_nested(data, args, new_val): if args and data: element = args[0] if element: value = data.get(element) if len(args) == 1: data[element] = new_val else: set_nested(value, args[1:], new_val) from collections import MutableMapping # see https://stackoverflow.com/questions/7204805/dictionaries-of-dictionaries-merge/24088493#24088493 def rec_merge(d1, d2): ''' Update two dicts of dicts recursively, if either mapping has leaves that are non-dicts, the second's leaf overwrites the first's. ''' for k, v in d1.items(): # in Python 2, use .iteritems()! if k in d2: # this next check is the only difference! if all(isinstance(e, MutableMapping) for e in (v, d2[k])): d2[k] = rec_merge(v, d2[k]) # we could further check types and merge as appropriate here. d3 = d1.copy() d3.update(d2) return d3 def normalize(old_dict, delim="::"): new_dict = { } for key in old_dict.keys(): splitted = key.split(delim) is_split = len(splitted) &gt; 1 if is_split: new_key = splitted[0] x = new_dict.get(new_key) if not x or not isinstance(x, dict): x = {} y = {} for s in reversed(splitted[1:]): y = {s: y} set_nested(y, splitted[1:], old_dict[key]) new_val = rec_merge(x, y) new_dict[new_key] = new_val if isinstance(old_dict[key], dict): new_dict[new_key] = normalize(new_dict[new_key]) else: if isinstance(old_dict[key], dict): new_dict[key] = normalize(old_dict[key]) else: new_dict[key] = old_dict[key] return new_dict print (json.dumps(normalize(mydict), indent=2)) </code></pre> <p>This is the expected output after normalizing:</p> <pre><code>{ "a": { "test": { "test2": { "test3": { "test4": { "name": "ok", "age": 1 } }, "test4": { "test4": { "name": "ok1", "age": 2 }, "test5": { "name": "ok1", "body": { "head": { "foot": { "age": 2, "thing": "test" } } } } } } } }, "b": { "name": "ok2", "age": "test2" } } </code></pre> <p>Is there a way to simplify the logic in normalize function?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T12:56:08.990", "Id": "455244", "Score": "0", "body": "This...sounds like a weird format. Your first example I would not have interpreted that way, it looks quite different to the example you are parsing in your script (no multiple levels). In any case, is the outer level always just one level deep (i.e. is the first level always a true level and not nested with delimiters)? And are the final elements guaranteed to be unique or is e.g. `\"a::b\": {\"c\": 2}, \"a::b::c\": {\"d\": 3}` a possibility and how to deal with it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T13:05:22.770", "Id": "455246", "Score": "2", "body": "@Graipher it is a weird format and that's why I want to normalize it. Yes the first example might have been oversimplified. I can't change the format stored in the pickle files but I can guarantee that the outer level is always a normal key without delimiters. The example you provided is not how the pickle files are formatted. I'll update the example with a more clear description." } ]
[ { "body": "<p>Ok, so you have a arbitrary deep path and need to get a dictionary out of it. For this you can use an infinitely nestable <code>defaultdict</code>, as shown in <a href=\"https://stackoverflow.com/a/4178355/4042267\">this answer</a> by <a href=\"https://stackoverflow.com/users/56338/sth\">@sth</a>:</p>\n\n<pre><code>from collections import defaultdict\n\nclass InfiniteDict(defaultdict):\n def __init__(self):\n defaultdict.__init__(self, self.__class__)\n</code></pre>\n\n<p>This allows you to write stuff like <code>d[\"a\"][\"b\"][\"c\"] = 3</code> and it will automatically create all nested layers. It allows you to parse the dictionary recursively. The outer dictionary can be handled in the same way as the inner dictionaries, because <code>*a, b = \"foo\".split(\"::\") -&gt; a, b = [], \"foo\"</code>.</p>\n\n<pre><code>def parse(d):\n # reached a leave\n if not isinstance(d, dict):\n return d\n out = InfiniteDict()\n for path, values in d.items():\n # parse the path, if possible\n try:\n *path, key = path.split(\"::\")\n except AttributeError:\n # do nothing if path is not a string\n path, key = [], path\n # follow the path down almost to the end\n # noop if path = []\n temp = out\n for x in path:\n temp = temp[x]\n # assign it to the last part of the path\n # need to parse that as well, in case it has another path\n # works only `sys.getrecursionlimit()` levels deep, obviously\n temp[key] = parse(values) \n return out\n</code></pre>\n\n<p>For the given example this produces:</p>\n\n<pre><code>InfiniteDict(__main__.InfiniteDict,\n {'a': InfiniteDict(__main__.InfiniteDict,\n {'test': InfiniteDict(__main__.InfiniteDict,\n {'test2': InfiniteDict(__main__.InfiniteDict,\n {'test3': InfiniteDict(__main__.InfiniteDict,\n {'test4': InfiniteDict(__main__.InfiniteDict,\n {'age': 1,\n 'name': 'ok'})}),\n 'test4': InfiniteDict(__main__.InfiniteDict,\n {'test4': InfiniteDict(__main__.InfiniteDict,\n {'age': 2,\n 'name': 'ok1'}),\n 'test5': InfiniteDict(__main__.InfiniteDict,\n {'body': InfiniteDict(__main__.InfiniteDict,\n {'head': InfiniteDict(__main__.InfiniteDict,\n {'foot': InfiniteDict(__main__.InfiniteDict,\n {'age': 2,\n 'thing': 'test'})})}),\n 'name': 'ok1'})})})})}),\n 'b': InfiniteDict(__main__.InfiniteDict,\n {'age': 'test2', 'name': 'ok2'})})\n</code></pre>\n\n<p>Which looks worse than it is, because <code>InfiniteDict</code> inherits from <code>dict</code> in the end:</p>\n\n<pre><code>isinstance(InfiniteDict(), dict)\n# True\nInfiniteDict.mro()\n# [__main__.InfiniteDict, collections.defaultdict, dict, object]\n</code></pre>\n\n<p>And so you can <code>json.dumps</code> it, just like you did in your code:</p>\n\n<pre><code>import json\n\n...\n\nif __name__ == \"__main__\":\n mydict = {...}\n print(json.dumps(parse(mydict), indent=2))\n\n# {\n# \"a\": {\n# \"test\": {\n# \"test2\": {\n# \"test3\": {\n# \"test4\": {\n# \"name\": \"ok\",\n# \"age\": 1\n# }\n# },\n# \"test4\": {\n# \"test4\": {\n# \"name\": \"ok1\",\n# \"age\": 2\n# },\n# \"test5\": {\n# \"name\": \"ok1\",\n# \"body\": {\n# \"head\": {\n# \"foot\": {\n# \"age\": 2,\n# \"thing\": \"test\"\n# }\n# }\n# }\n# }\n# }\n# }\n# }\n# },\n# \"b\": {\n# \"name\": \"ok2\",\n# \"age\": \"test2\"\n# }\n# }\n</code></pre>\n\n<p>The advantage of this is that the <code>InfiniteDict</code> deals with most of the nasty recursive stuff, and the only thing left to do is make paths out of the strings, if necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:16:36.323", "Id": "455260", "Score": "0", "body": "Great solution, it works perfect for converting the pickle file to a mat file. I don't understand the decision for using this strange format since it can't be imported easily into matlab or similar and the guy who is responsible simply said \"you have to do the conversion yourself\"..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:18:29.833", "Id": "455261", "Score": "0", "body": "@Linus Well, it is a slightly compressed version, compared to json. But the gains are not much, especially if you have to parse it manually..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:22:26.940", "Id": "455263", "Score": "1", "body": "Yeah, the pickle files are about 140MB big so the compression might be helpful in someway but it's not a easy format to work with. Anyway, thank you for the time and code review :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T13:21:01.560", "Id": "232996", "ParentId": "232990", "Score": "6" } } ]
{ "AcceptedAnswerId": "232996", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T12:13:01.737", "Id": "232990", "Score": "5", "Tags": [ "python", "hash-map", "converting" ], "Title": "Normalizing mixed format nested dictionary with delimiter separated keys" }
232990
<p>In an angular application I would like to set the browser title to something that is helpful. (Helpful means that the user gets a meaningful history and can identify tabs easily). Setting the title should be as automatic as possible. That means:</p> <ul> <li>If the route changes and the component that becomes active has title, then it should be used</li> <li>If the route changes and the component that becomes active has no title a default title should be used</li> <li>Dynamic titles should be allowed, so e.g. in the hero-app I might want to display the name of the hero currently displayed in the title</li> <li>The title must allow localization</li> </ul> <p>Angular does have a the <code>Title</code>-Service to set the title, but it is setter-based, so I'd have to make sure that each and every route/component sets a title or every component that sets a tile needs to unset it in <code>ngOnDestroy</code>. That is already quite cumbersome and then there are situations where this won't work at all, because multiple components might override each other.</p> <p>I could not find an existing solution, so I created my own. It looks like this:</p> <ol> <li><p>I create my own <code>TitleService</code> which wraps angular's service:</p> <pre class="lang-js prettyprint-override"><code>import { Injectable } from '@angular/core'; import { debounceTime, switchMap } from 'rxjs/operators'; import { Title } from '@angular/platform-browser'; import { BehaviorSubject, combineLatest, Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class TitleService { private titleSegments = new BehaviorSubject&lt;Observable&lt;string&gt;[]&gt;([of('My App')]); constructor(private delegate: Title) { this.titleSegments .pipe( switchMap((values: Observable&lt;string&gt;[]) =&gt; combineLatest(values)), debounceTime(100) // Prevents "flickering", if during loading the title changes a lot ) .subscribe(segments =&gt; this.delegate.setTitle(segments.join(' &lt; '))); } addTitleSegment(segment: Observable&lt;string&gt;) { this.titleSegments.next([segment, ...this.titleSegments.value]); } popTitleSegment() { this.titleSegments.next(this.titleSegments.value.slice(1)); } } </code></pre></li> <li><p>I create a directive and a component to interact with mit <code>TitleService</code>. Directive:</p> <pre class="lang-js prettyprint-override"><code>import { Directive, ElementRef, Input, OnDestroy } from '@angular/core'; import { ReplaySubject } from 'rxjs'; import { TitleService } from '../core/title.service'; @Directive({ selector: '[appPageTitle]' }) export class PageTitleDirective implements OnDestroy { private title$ = new ReplaySubject&lt;string&gt;(1); constructor(private titleService: TitleService, el: ElementRef) { this.title$.subscribe(title =&gt; el.nativeElement.innerText = title); titleService.addTitleSegment(this.title$); } @Input() set appPageTitle(title: string) { this.title$.next(title); } ngOnDestroy(): void { this.titleService.popTitleSegment(); } } </code></pre> <p>Component:</p> <pre class="lang-js prettyprint-override"><code> import { Component, Input, OnDestroy } from '@angular/core'; import { TitleService } from '../core/title.service'; import { ReplaySubject } from 'rxjs'; @Component({ selector: 'app-page-title', template: '', }) export class PageTitleComponent implements OnDestroy { private title$ = new ReplaySubject&lt;string&gt;(1); constructor(private titleService: TitleService) { titleService.addTitleSegment(this.title$); } @Input() set title(title: string) { this.title$.next(title); } ngOnDestroy(): void { this.titleService.popTitleSegment(); } } </code></pre> <p>The component and the directive are very similar. I use the directive most of the time, so I can use heading and title in one go, but in case there is no heading I use the directive, which has no effect on the UI.</p></li> </ol> <p>Now I can simply use the directive/component in my HTML. E.g. like this:</p> <p>root.html:</p> <pre class="lang-html prettyprint-override"><code>&lt;h1 appPageTitle="Heroes"&gt;&lt;/h1&gt; &lt;app-edit-hero&gt;&lt;/app-edit-hero&gt; </code></pre> <p>edit.html:</p> <pre class="lang-html prettyprint-override"><code>&lt;h1 [appPageTitle]="'edit' + hero.name"&gt;&lt;/h1&gt; ... </code></pre> <p>And in this case I get (if <code>hero.name === 'My Hero'</code>):</p> <blockquote> <p>edit My Hero &lt; Heroes &lt; MY APP</p> </blockquote> <p>As browser title, which looks great. Also it is very easy to manage, since this happens mostly automatically, whenever routes change or the data I would like changes.</p> <p>Questions:</p> <ul> <li>Are there any hidden pitfalls? E.g. I depend on the correct order of construction and destruction of components when navigating. Are there any cases where this might be a problem?</li> <li>Is this OK with standard angular coding best practices?</li> <li>Is there anything from the usability/accessibility perspective that might be a problem?</li> <li>Any general suggestions of improvement?</li> <li>Are there other existing approaches, that I have missed during my research?</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T12:22:33.690", "Id": "232991", "Score": "1", "Tags": [ "angular-2+" ], "Title": "Angular: Setting the browser title according to active components" }
232991
<p>I was practicing <code>divide-two-integers</code> question from leetcode </p> <p><strong>Question:</strong> Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.</p> <p>Return the quotient after dividing dividend by divisor.</p> <p>The integer division should truncate toward zero.</p> <p><strong>Question Link:</strong> <a href="https://leetcode.com/problems/divide-two-integers/" rel="nofollow noreferrer">https://leetcode.com/problems/divide-two-integers/</a></p> <p>For this I wrote the following algorithm but clearly it isn't optimized with my time complexity coming out to be about <code>8248 ms</code>. Can someone please help me in optimizing the code? </p> <pre><code> /** * @param {number} dividend * @param {number} divisor * @return {number} */ /** * @param {number} dividend * @param {number} divisor * @return {number} */ var divide = function(dividend, divisor) { let negativeFlag = false let quiotentHolder = 0 if (divisor === 0 || dividend === 0) return 0; if (dividend === -2147483648 &amp;&amp; divisor === -1) return 2147483647; else if (dividend &lt; 0 &amp;&amp; divisor &lt; 0) { dividend = -dividend divisor = -divisor } else if ((dividend &lt; 0 &amp;&amp; divisor &gt; 0) || (dividend &gt; 0 &amp;&amp; divisor &lt; 0)) { negativeFlag = true divisor &lt; 0 ? divisor = -divisor :dividend = -dividend } while (divisor &lt;= dividend) { dividend = dividend - divisor quiotentHolder += 1 } if (negativeFlag) return -quiotentHolder else return quiotentHolder } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T13:41:16.827", "Id": "455253", "Score": "0", "body": "`number - number - number` indeed equals `-number`, but why complicating it that much? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T15:36:08.197", "Id": "455276", "Score": "0", "body": "@slepic Updated code" } ]
[ { "body": "<h1>Division by zero</h1>\n\n<p>Your implementation returns zero if you devide by zero. That is wrong. Division by zero is undefined.</p>\n\n<pre><code>if (divisor === 0 || dividend === 0) return 0;\n</code></pre>\n\n<p>On other hand, zero divided by nonzero is zero, that's ok. But zero divided by zero is still undefined. And so it should be checked first.</p>\n\n<pre><code>if (divisor === 0) throw \"Division by zero\";\nif (dividend === 0) return 0;\n</code></pre>\n\n<h1>Edge cases</h1>\n\n<p>For some reason you are checking combination <code>-2147483648/-1</code> then you claim it is <code>2147483647</code>, but that's wrong. Firstly, <code>2147483648</code> is representable in js number type. But if you consider it overflow, you should throw overflow error.</p>\n\n<pre><code>if (dividend === -2147483648 &amp;&amp; divisor === -1) throw 'Overflow error';\n</code></pre>\n\n<p>Btw notice, that <code>-2147483648/n</code> would also overflow further in your code because you convert dividend and divisor to positives. And so maybe you should throw overflow error in this case as well no matter the divisor.</p>\n\n<pre><code>if (dividend === -2147483648) throw 'Overflow error';\n</code></pre>\n\n<h1>Simplify conditions</h1>\n\n<p>There is unnecesarily complex condition:</p>\n\n<pre><code>(dividend &lt; 0 &amp;&amp; divisor &gt; 0) || (dividend &gt; 0 &amp;&amp; divisor &lt; 0)\n</code></pre>\n\n<p>assuming the first if was already executed, then the eleseif condition can be simplified as</p>\n\n<pre><code>dividend &lt; 0 || divisor &lt; 0\n</code></pre>\n\n<p>Or even better, split it in two elseifs, because you have a ternary that checks again.</p>\n\n<pre><code>if (dividend &lt; 0 &amp;&amp; divisor &lt; 0) {\n dividend = -dividend\n divisor = -divisor\n} else if (dividend &lt; 0) {\n negativeFlag = true\n dividend = -dividend;\n} else if (divisor &lt; 0) {\n negativeFlag = true\n divisor = -divisor;\n}\n</code></pre>\n\n<p>Notice that I omitted zeroes, because they have been excluded in the beginning.</p>\n\n<h1>Negative flag</h1>\n\n<p>This flag is unnecesary, you could instead have an integer variable with value of +1 or -1.</p>\n\n<pre><code>let quotientUnit = 1;\nif (...) quotientUnit = -1;\nlet quiotentHolder = 0;\nwhile (divisor &lt;= dividend) {\n dividend -= divisor; //notice -=\n quiotentHolder += quotientUnit;\n}\nreturn quiotentHolder;\n</code></pre>\n\n<h1>Performance</h1>\n\n<p>Just of curiosity, have you tried something like <code>big/small</code>. Is it fast? It seems to me the bigger the result of the division, the more time consuming your algorithm is... Not sure if there is a faster way though. Division without division is not something I usualy think of :) But I could suppose there is not, because that's why we have division optimized in our CPUs, where it can be fastened by paralel processing (by which i mean paralel nature of logic gates, not running multiple threads inside a CPU)</p>\n\n<p>EDIT: You mentioned that your \"time complexity is about <code>8248 ms</code>\". Firstly, time complexity is not a meassure of time. Time complexity is more like a meassure of relative time consumption based on the size of the input. Since in your case there is no \"size of input\", time complexity makes no sense with this algorithm. If you wanted to define something like time complexity for your algorithm, it would probably be something like <code>O(dividend/divisor)</code>, but this is not really a time complexity, but I am still able to make sense of it...</p>\n\n<p>But let's suppose you meant the actual run time. Not sure what input does the <code>8248 ms</code> refer to. As I said, the speed is different for different inputs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-27T16:16:13.697", "Id": "459077", "Score": "0", "body": "Maybe some kind of `arr[n] = arr[n-1] + arr[n-1]` loop to build a list of powers of two times the divisor, then subtract them from the dividend starting with the largest?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T06:59:12.570", "Id": "233049", "ParentId": "232992", "Score": "4" } }, { "body": "<p>I did a recursive solution using powers of two times the divisor. Essentially, it finds the highest <code>divisor * 2^n</code> that still fits in the dividend, subtracts it and repeats.</p>\n\n<pre><code>const divide = (dividend, divisor) =&gt; {\n if (dividend === -2147483648 &amp;&amp; divisor === -1) return 2147483647;\n const result = dividePositive(Math.abs(dividend), Math.abs(divisor))\n return dividend &lt; 0 === divisor &lt; 0 ? result : 0 - result\n};\n\nconst dividePositive = (dividend, divisor) =&gt; {\n if(dividend &lt; divisor) return 0\n let subtract = divisor, result = 1\n while(subtract &lt; dividend-subtract) {\n subtract += subtract\n result += result\n }\n return result + dividePositive(dividend-subtract, divisor)\n}\n</code></pre>\n\n<p>I've tried tricks like using <code>subtract &lt;&lt;= 1</code> instead of <code>subtract += subtract</code>, having an extra while loop instead of the recursion, saving the powers of two in tables etc. but never achieved anything that would be noticeably faster.</p>\n\n<p>For reference, a version saving the intermediate results if you want to tweak further. Note that <code>n &lt;&lt;= 1</code> flips around to negative numbers at 2^32, giving you a bit of a headache with handling high numbers.</p>\n\n<pre><code>var divide = function(dividend, divisor) {\n if (dividend === -2147483648 &amp;&amp; divisor === -1) return 2147483647;\n flipSign = dividend &lt; 0 != divisor &lt; 0\n dividend = Math.abs(dividend);\n divisor = Math.abs(divisor);\n\n var subtract = divisor, result = 1\n powers = [], results = []\n while(subtract &lt;= dividend) {\n powers.push(subtract)\n results.push(result)\n subtract += subtract;\n result += result;\n }\n final = 0;\n for(var i = powers.length -1; i &gt;= 0; i--) {\n if(dividend &gt;= powers[i]) {\n dividend -= powers[i];\n final += results[i];\n }\n }\n return flipSign ? 0 - final : final\n};\n</code></pre>\n\n<p>Copy paste the code to <a href=\"https://leetcode.com/problems/divide-two-integers/\" rel=\"nofollow noreferrer\">https://leetcode.com/problems/divide-two-integers/</a> and submit to run and get the time results.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-06T11:47:00.113", "Id": "460107", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-29T17:15:15.550", "Id": "234790", "ParentId": "232992", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T12:44:42.630", "Id": "232992", "Score": "4", "Tags": [ "javascript" ], "Title": "Leetcode: divide-two-integers" }
232992
<p>I am creating a dialect of ActionScript 3.0 and now have a working verifier, or “symbol solving” verifier. The language upgrades ActionScript 3.0 with few operators, light syntax facilities, numeric enums and way more compile-time semantics.</p> <p>To test verifying, run:</p> <pre><code>$ git clone https://github.com/shockscript/sxc $ cd sxc $ npm install $ npm link $ npm test </code></pre> <p>There's no proper test unit, but the command <code>npm test</code> runs <code>sxc tests/sources</code>, which includes all sources in <code>sxc/library</code> and few sources in <code>sxc/tests/sources</code>, parses and verifies them. Errors accompanied by the comment <code>// Verify error</code> will occur.</p> <p>Generic functions are alternatively called multi-functions and do not involve type substitution at compile time:</p> <pre><code>generic function fn(value):Boolean generic function fn(value:RegExp):Boolean generic function fn(value:String):Boolean </code></pre> <p>Generic classes are final and therefore cannot be extended. The following is an example:</p> <pre><code>final class A.&lt;T&gt; { } var a = new A.&lt;A.&lt;uint&gt;&gt; </code></pre> <p>Type substitution only occurs with instantiations of generic classes. It occurs directly with every access on the instantiation. I'm wondering if my substitution with structural types (aka. composed types) is correct: to prevent cycles, it pre-creates type symbols and mutates them later once the further composing types have any type parameter occurrence replaced.</p> <p><a href="https://github.com/shockscript/sxc/blob/master/src/sxc-semantics/src/type.js#L53" rel="nofollow noreferrer">type.js</a></p> <pre class="lang-js prettyprint-override"><code>class Type { /*...*/ replace(params, args) { return this._replace(params, args) } _replace(params, args, w = null, u = null) { if (this instanceof ClassType) { if (this.typeParameters) { const args2 = [] for (const param of this.typeParameters) { const i = params.indexOf(param) args2.push(i === -1 ? param : args[i]) } return this.instantiate(args2) } } else if (this instanceof GI) { w = w || new Map let type2 = w.get(this) if (type2) return type2 type2 = new GI(null, []) w.set(this, type2) const args = [] for (const type of this.originArguments) args.push(type._replace(params, args, w)) return this.origin.instantiate(args, type2) } else if (this instanceof TypeParameter) { const i = params.indexOf(this) if (i !== -1) return args[i] } else if (this instanceof FunctionType) { w = w || new Map let type2 = w.get(this) if (type2) return type2 type2 = new FunctionType w.set(this, type2) if (this.params) { type2.params = [] for (const param of this.params) type2.params.push(param._replace(params, args, w)) } if (this.optParams) { type2.optParams = [] for (const param of this.optParams) type2.optParams.push(param._replace(params, args, w)) } if (this.restParam) type2.restParam = this.restParam._replace(params, args, w) if (this.returnType) type2.returnType = this.returnType._replace(params, args, w) type2.delegate = this.context.statics.ObjectType.delegate type2.context = this.context return type2 } else if (this instanceof TupleType) { w = w || new Map let type2 = w.get(this) if (type2) return type2 type2 = new TupleType([]) w.set(this, type2) for (const type of this.types) type2.types.push(type._replace(params, args, w)) type2.delegate = this.context.statics.ObjectType.delegate type2.context = this.context return type2 } else if (this instanceof UnionType) { w = w || new Map let type2 = w.get(this) if (type2) return type2 type2 = new UnionType([]) w.set(this, type2) u = u || [] u.push(type2) for (const type of this.types) { const type3 = type._replace(params, args, w, u) if (u.indexOf(type3) === -1 &amp;&amp; this.types.indexOf(type3) === -1) type2.types.push(type3) } type2.context = this.context u.pop() return type2 } else if (this instanceof NullableType) { w = w || new Map let type2 = w.get(this) if (type2) return type2 type2 = new NullableType(null) w.set(this, type2) let innerType = this.innerType._replace(params, args, w) if (innerType instanceof NullableType) if (!innerType.innerType.containsNullValue()) innerType = innerType.innerType else if (innerType instanceof NonNullableType) innerType = innerType.innerType type2.innerType = innerType type2.delegate = innerType.delegate type2.context = this.context return type2 } else if (this instanceof NonNullableType) { w = w || new Map let type2 = w.get(this) if (type2) return type2 type2 = new NonNullableType(null) w.set(this, type2) let innerType = this.innerType._replace(params, args, w) if (innerType instanceof NullableType) if (innerType.innerType.containsNullValue()) innerType = innerType.innerType else if (innerType instanceof NonNullableType) innerType = innerType.innerType type2.innerType = innerType type2.delegate = innerType.delegate type2.context = this.context return type2 } return this } /*...*/ } </code></pre> <p>The parameters <code>w</code> and <code>u</code> serve to prevent any cycle. <code>w</code> means wrapping types (given by a offending <code>_replace()</code> call) and <code>u</code> means union hierarchy (to prevent union reoccuring with itself).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T22:39:56.803", "Id": "455709", "Score": "1", "body": "I scanned through the project at GitHub, and I wondered where the test suite is. For a programming language of this complexity I expect a test suite that covers success and failure cases for each of the type comparisons. Right now it looks to me as if your language defines that a `NullableType of X` equals `X`, which sounds obviously wrong to me. Where are these tests and examples?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T01:23:04.020", "Id": "455714", "Score": "0", "body": "@RolandIllig I've added a comprovation that this confusion does not occur: [nullability.sx](https://github.com/shockscript/shockscript/blob/master/comp-sx/testsuite/nullability.sx). It'll report `VerifyError: Error #1317: Parameter must be of type ?uint` (for callback that takes `?uint`, but explicitly passes `uint`). A type annotation is not even required to begin with in this case, so it's redundant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T04:59:34.667", "Id": "455715", "Score": "0", "body": "And where is the corresponding test that ensures that the compiler issues exactly this error message?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:25:40.353", "Id": "455725", "Score": "0", "body": "@RolandIllig In case I put instructions in this post. It requires Git and Node.js in your shell environment. If under Termux app (Android) you can install Node.js by simply running `pkg install nodejs`. After installing ShockScript (entering `$ cd shockscript/comp-sx`, `$ npm install` and `$ npm link`), you can verify all sources under `testsuite` using the command `comp-sx --builtins langlib/**/*.sx testsuite/**/*.sx` (you must reside in `comp-sx` directory as these source directories are located there)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:33:30.463", "Id": "455728", "Score": "0", "body": "Does the \"you can verify\" mean I have to manually inspect the output? If so, that's unacceptable since this is something that is too boring and error-prone for humans. Tasks like this are better left to computers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:39:58.600", "Id": "455730", "Score": "0", "body": "@RolandIllig The verifier produces error/warning list and the command `comp-sx` properly displays each report. There is not an integrated testsuite nor a performance profiler. Errors within included scripts (using the `include` directive) should be properly reported as well." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:02:51.973", "Id": "232998", "Score": "3", "Tags": [ "compiler", "language-design" ], "Title": "Scripting language with generic classes" }
232998
<p>I inherited this code and have to fix it. It does work and I know I can refactor the code using <code>If Not Intersect(Target, Me.Range()) Is Nothing Then</code> syntax. I am wondering if using a function to pass the cell references in this case would be best, but im not really familiar on working with functions yet and would like some input or guidance on best practice with the code below. Please note I am well aware of the usage of <code>select</code> within this code block, but the original author wants me to keep the <code>select</code> to move the active cell based on selections made in the worksheet.</p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Range) Application.ScreenUpdating = False Application.EnableEvents = False Dim wb As Workbook: Set wb = Application.ThisWorkbook Dim wsDE As Worksheet: Set wsDE = wb.Sheets("Data Entry") Dim Unique_Identifier As String Dim Wire_Type As String With wsDE Select Case Target.Address Case Is = "$B$4": Hide_All Select Case Range("B4") Case Is &lt;&gt; "" Range("A100:A199").EntireRow.Hidden = False Range("B101").Select Sheet5.Visible = xlSheetVisible 'Confirmation-Incoming Range("B5") = "" Case Else: Range("B5").Select End Select Case Is = "$B$5": Hide_All Select Case Range("B5") Case Is &lt;&gt; "" Range("A200:A211").EntireRow.Hidden = False Range("A216:A227").EntireRow.Hidden = False Range("B201").Select With ThisWorkbook Sheet7.Visible = xlSheetVisible 'Checklist Sheet4.Visible = xlSheetVisible 'Confirmation-Outgoing-1 Sheet2.Visible = xlSheetVisible 'Wire Transfer Request-1 End With Select Case Range("B5") Case Is &gt; 1 Range("A200:A299").EntireRow.Hidden = False Unique_Identifier = Range("B5").Value Wire_Type = "Deposit/Loan" Call Find_Recurring(Unique_Identifier, Wire_Type) End Select Case Else: Range("B6").Select End Select Case Is = "$B$6": Hide_All Select Case Range("B6") Case Is &lt;&gt; "" Range("A300:A312").EntireRow.Hidden = False Range("A316:A330").EntireRow.Hidden = False Range("B301").Select With ThisWorkbook Sheet3.Visible = xlSheetVisible 'Checklist-Loan Closing Sheet12.Visible = xlSheetVisible 'Confirmation-Outgoing-2 Sheet11.Visible = xlSheetVisible 'Wire Transfer Request-2 End With Case Else: Range("B7").Select End Select Case Is = "$B$7": Hide_All Select Case Range("B7") Case Is &lt;&gt; "" Range("A400:A411").EntireRow.Hidden = False Range("A414:A499").EntireRow.Hidden = False Range("B401").Select With ThisWorkbook Sheet9.Visible = xlSheetVisible 'Checklist-Cash Management Sheet14.Visible = xlSheetVisible 'Confirmation-Outgoing-3 End With Case Else: Range("B8").Select End Select Case Is = "$B$8": Hide_All Select Case Range("B8") Case Is &lt;&gt; "" Range("A500:A599").EntireRow.Hidden = False Range("B501").Select With ThisWorkbook Sheet13.Visible = xlSheetVisible 'Wire Transfer Request - Brokered-Internet End With Case Else: Range("B9").Select End Select Case Is = "$B$9": Hide_All Select Case Range("B9") Case Is &lt;&gt; "" Range("A600:A610").EntireRow.Hidden = False Range("B601").Select Sheet8.Visible = xlSheetVisible 'Checklist-Internal Select Case Range("B9") Case Is &gt; 1 Range("A600:A699").EntireRow.Hidden = False Unique_Identifier = Range("B9").Value Wire_Type = "Internal" Call Find_Recurring(Unique_Identifier, Wire_Type) End Select Case Else: Range("B10").Select End Select Case Is = "$B$10": Hide_All Select Case Range("B10") Case Is &lt;&gt; "" Sheet6.Visible = xlSheetVisible 'Wire Transfer Agreement Sheets("Wire Transfer Agreement").Visible = True Range("A5000:A5099").EntireRow.Hidden = False Range("A5005:A5011").EntireRow.Hidden = True Range("B5001").Select Case Else: Range("B11").Select End Select Case Is = "$B$11": Hide_All Select Case Range("B11") Case Is &lt;&gt; "" ' Sheets("Recurring Wire Transfer Request").Visible = True Sheet18.Visible = xlSheetVisible 'Recurring Wire Transfer Request Range("A5100:A5118").EntireRow.Hidden = False Range("A5111:A5114").EntireRow.Hidden = True Range("B5101").Select Case Else: Range("B11").Select End Select 'Wires from Deposit Account or Loan (Post-Closing) Section Case Is = "$B$205" Select Case LCase(Range("B205")) Case Is = "yes" Range("A212:A215").EntireRow.Hidden = False Case Else Range("A212:A215").EntireRow.Hidden = True Range("B206").Select End Select Case Is = "$B$227" Select Case LCase(Range("B227")) Case Is = "domestic" Range("A222:A243").EntireRow.Hidden = False Range("A267:A299").EntireRow.Hidden = False Range("A244:A266").EntireRow.Hidden = True Range("B229").Select Case Is = "international" Range("A244:A299").EntireRow.Hidden = False Range("A228:A243").EntireRow.Hidden = True Range("B245").Select Case Is &lt;&gt; "international", "domestic" Range("A228:A299").EntireRow.Hidden = True Range("B227").Select End Select Case Is = "$B$269" Select Case LCase(Range("B269")) Case Is = "yes" Sheets("Wire Transfer Agreement").Visible = True Range("A5000:A5099").EntireRow.Hidden = False Range("B282:B299").EntireRow.Hidden = True Application.ScreenUpdating = True Range("B5001").Select Case Else Sheets("Wire Transfer Agreement").Visible = False Range("A5000:A5099").EntireRow.Hidden = True Range("B281:B299").EntireRow.Hidden = False Range("B270").Select End Select 'Loan-Closing Wires Section Case Is = "$B$306" Select Case LCase(Range("B306")) Case Is = "yes" Range("A313:A316,A331").EntireRow.Hidden = False Case Else Range("A313:A316").EntireRow.Hidden = True Range("A331").EntireRow.Hidden = False Range("B307").Select End Select Case Is = "$B$331" Select Case LCase(Range("B331")) Case Is = "domestic" Range("A332:A347").EntireRow.Hidden = False Range("A370:A399").EntireRow.Hidden = False Range("A348:A369").EntireRow.Hidden = True Range("B331").Select Case Is = "international" Range("A347:A399").EntireRow.Hidden = False Range("A332:A346").EntireRow.Hidden = True Range("B349").Select Case Is &lt;&gt; "domestic", "international" Range("A332:A399").EntireRow.Hidden = True Range("B331").Select End Select Case Is = "$B$373" Select Case LCase(Range("B373")) Case Is = "yes" Sheets("Wire Transfer Agreement").Visible = True Range("A5000:A5099").EntireRow.Hidden = False Range("B383:B399").EntireRow.Hidden = True Application.ScreenUpdating = True Range("B5001").Select Case Else Sheets("Wire Transfer Agreement").Visible = False Range("A5000:A5099").EntireRow.Hidden = True Range("B383:B399").EntireRow.Hidden = False Range("B374").Select End Select 'Cash Management Wires Section Case Is = "$B$406" Select Case LCase(Range("B406")) Case Is = "yes" Range("A412:A413").EntireRow.Hidden = False Case Else Range("A412:A413").EntireRow.Hidden = True Range("B407").Select End Select Case Is = "$B$425" Select Case LCase(Range("B425")) Case Is = "yes" Range("A430:A431").EntireRow.Hidden = False Case Else Range("A430:A431").EntireRow.Hidden = True Range("B426").Select End Select 'Internal Foresight Wires Section Case Is = "$B$610" Select Case LCase(Range("B610")) Case Is = "domestic" Range("A611:A625").EntireRow.Hidden = False Range("A648:A699").EntireRow.Hidden = False Range("A626:A647").EntireRow.Hidden = True Range("B612").Select Case Is = "international" Range("A626:A699").EntireRow.Hidden = False Range("A611:A625").EntireRow.Hidden = True Range("B627").Select Case Is &lt;&gt; "international", "domestic" Range("A611:A699").EntireRow.Hidden = True Range("B610").Select End Select 'Wire Transfer Agreement Section Case Is = "$B$5004" Range("A5005:A5011").EntireRow.Hidden = True Range("B5004").Select Select Case LCase(Range("B5004")) Case Is = "entity" Range("A5007:A5011").EntireRow.Hidden = False Range("B5007").Select Case Is = "individual(s)" Range("A5005:A5006").EntireRow.Hidden = False Range("B5005").Select End Select 'Recurring Wire Transfer Request Section Case Is = "$B$5104" Range("A5111:A5114").EntireRow.Hidden = True Range("B5105").Select Select Case LCase(Range("B5104")) Case Is = "yes" Range("A5111:A5114").EntireRow.Hidden = False Range("B5105").Select Case Is = "no" Range("A5111:A5114").EntireRow.Hidden = True Range("B5105").Select End Select Case Is = "$B$5118" Select Case LCase(Range("B5118")) Case Is = "domestic" Range("A5119:A5131").EntireRow.Hidden = False Range("A5132:A5199").EntireRow.Hidden = True Range("A5150").EntireRow.Hidden = False Range("B5120").Select Case Is = "international" Range("A5119:A5131").EntireRow.Hidden = True Range("A5132:A5149").EntireRow.Hidden = False Range("A5151:A5199").EntireRow.Hidden = True Range("B5133").Select Case Is &lt;&gt; "international", "domestic" Range("A5119:A5199").EntireRow.Hidden = True Range("B5118").Select End Select End Select End With 'CIF Calls If Not Intersect(Target, Range("B103")) Is Nothing Then CIFIncoming If Not Intersect(Target, Range("B206")) Is Nothing Then CIFOutD If Not Intersect(Target, Range("B307")) Is Nothing Then CIFOutL If Not Intersect(Target, Range("B407")) Is Nothing Then CIFOutCM If Not Intersect(Target, Range("B506")) Is Nothing Then CIFBrokered Application.ScreenUpdating = True Application.EnableEvents = True End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:22:41.297", "Id": "455264", "Score": "1", "body": "What do you have to \"fix\" and what is your point in refactoring?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:23:07.207", "Id": "455265", "Score": "0", "body": "What's going on with `B5`? You have two switches with the same criteria, one nested in the other. Looks like you could pull the second `select case range(\"b5\")` out and it would work just fine. Have you attempted to simply some of the hidden ranges? E.g., Switch cases are for the cell and set a range, if range exists then `.hidden=false`. Lots of little things, but **regarding the inquiry to the use of a `Function()`**, i don't believe it would be appropriate to use when `Target` is literally the cell and adding the function would be redundant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:26:44.537", "Id": "455266", "Score": "0", "body": "@PeterT I should have used the term \"clean up\" not fix, sorry about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:28:30.467", "Id": "455267", "Score": "0", "body": "@Cyril I have already started cleaning up the redundancies with the cell references :). Thanks for the input regarding the use of a `Function()` I can see what you are saying." } ]
[ { "body": "<p>I think this is what, in rugby, they would call a 'hospital pass'.</p>\n\n<p>As someone who has fixed much code like this, I am going to hit some highlights only. If you manage to fix these highlights, I would love to see the revised code in another question for the second round. Because the job you have undertaken will take many passes to get right (but it will be worth it).</p>\n\n<h2>Set yourself up for success</h2>\n\n<blockquote>\n <p><em>[…] but the original author wants me to keep the select [...]</em></p>\n</blockquote>\n\n<p>If you are fixing and maintaining the code, then it must be written in a way that makes it easy for <strong><em>you</em></strong> to maintain. If you are fixing this and someone else must maintain it, then be that nice coder and make it easy for them to maintain. However, moving the user to view particular cells in a work process is a user requirement that you should keep in mind.</p>\n\n<p><strong><code>Option Explicit</code></strong> at the top of every module. Just a reminder - you might already have it there.</p>\n\n<p>Use <strong>Named Ranges</strong> in the sheets. It will make future maintenance so much easier. And it will make the current code easier to understand - <code>.Range(\"DateEntryDate\")</code> is easier to understand than <code>.Range(\"$B$3\")</code></p>\n\n<h2>Exit early</h2>\n\n<p>For performance reasons alone, always find the reasons not to run the code at the very start and exit. At the moment, if I make a change in $ABC$678023983, this code is going to fire and run. What a waste of time and cycles! Example:</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\nDim validRange as Range\n Set validRange = Intersect(Target, Me.Range(\"$B4:$B11\")) '&lt;-- wow, a named range here would be good.\n If validRange is Nothing Then\n Exit Sub ' &lt;--- explicit exit, easy to see.\n End If\n\n If Target.Cells.Count &gt; 1 Then\n Exit Sub ' &lt;-- always manage the range size!\n End If\n\n ' … other code \nEnd Sub\n</code></pre>\n\n<h2>Qualify your ranges</h2>\n\n<p>Most of the code is written with unqualified ranges (implied action on the active sheet).</p>\n\n<pre><code>Range(\"A400:A411\").EntireRow.Hidden = False\n</code></pre>\n\n<p>However, this assumes that the active sheet continues to be the sheet that the <code>_Change</code> event occurred in. Never make that assumption. Remember this code?</p>\n\n<pre><code>Range(\"B101\").Select\n</code></pre>\n\n<p>This means that the active cell will jump. With future modifications to the code or workbook, this may even jump to a different sheet.</p>\n\n<p>In addition, the code calls some utility functions (e.g. <code>Hide_all</code>) - these may also alter the active sheet.</p>\n\n<p>Having noted that, what is with <code>With wsDE</code>? There is an entire <code>With</code> block that in no way whatsoever that references the object (<code>wsDE</code>)!</p>\n\n<h2>Code readability</h2>\n\n<p>Don't use the line joiner, it can lead to confusion:</p>\n\n<pre><code> Case Is = \"$B$4\": Hide_All\n Select Case Range(\"B4\")\n Case Is &lt;&gt; \"\"\n Range(\"A100:A199\").EntireRow.Hidden = False\n Range(\"B101\").Select\n Sheet5.Visible = xlSheetVisible 'Confirmation-Incoming\n Range(\"B5\") = \"\"\n Case Else: Range(\"B5\").Select\n End Select\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code> Case Is = \"$B$4\"\n Hide_All\n Select Case Range(\"B4\")\n Case Is &lt;&gt; \"\"\n Range(\"A100:A199\").EntireRow.Hidden = False\n Range(\"B101\").Select\n Sheet5.Visible = xlSheetVisible 'Confirmation-Incoming\n Range(\"B5\") = \"\"\n Case Else\n Range(\"B5\").Select\n End Select\n</code></pre>\n\n<p>All of a sudden, the indent levels and code scope is easier to understand. The <code>Else</code> becomes more obvious. Much easier to read.</p>\n\n<p>Declare variables closer to where you are going to use them, and in the same scope. </p>\n\n<pre><code>Dim Unique_Identifier As String\nDim Wire_Type As String\n</code></pre>\n\n<p>Took me a while to work out if they were actually used.</p>\n\n<h2>What is next?</h2>\n\n<p>If you address the above points you will end up with some slightly cleaner code. You will recognise yourself that it requires more work. However, you will have a cleaner foundation to figure out the remaining inefficiencies. One step at a time and you will get there!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T20:56:49.013", "Id": "455324", "Score": "0", "body": "I appreciate you taking the time to look through all of this code. Those are the exact changes I made except for adding the `Exit Sub` since i didnt even think about that. I will post a round 2 of this once ive had a chance to go back and complete the updating I've been working on :)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:04:56.547", "Id": "455419", "Score": "0", "body": "I hope you dont take offense that I accepted TinMan's answer. I only accepted his answer because it was almost the exact same way i had refactored the original code myself. I did upvote this answer because it did provide useful information not only for myself, but for others that may view this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T18:41:14.000", "Id": "455469", "Score": "0", "body": "no problems, glad you found them both useful." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T20:16:02.397", "Id": "233018", "ParentId": "232999", "Score": "5" } }, { "body": "<p>As AJD pointed out, using Named Ranges will make the code easier to understand, read, write and modify. The same logic can be applied to worksheet code names. </p>\n\n<p>Here are the names that I used when refactoring the code:</p>\n\n<ul>\n<li>Sheets(\"Wire Transfer Agreement\") -> wsWTA</li>\n<li>Sheet2 -> wsWireTransferRequest1</li>\n<li>Sheet3 -> wsChecklistLoanClosing</li>\n<li>Sheet4 -> wsConfirmationOutgoing1</li>\n<li>Sheet5 -> wsConfirmationIncoming</li>\n<li>Sheet7 -> wsChecklist</li>\n<li>Sheet6 -> wsWireTransferAgreement</li>\n<li>Sheet8 -> wsChecklistInternal</li>\n<li>Sheet9 -> wsChecklistCashManagement</li>\n<li>Sheet11 -> wsWireTransferRequest2</li>\n<li>Sheet12 -> wsConfirmationOutgoing2</li>\n<li>Sheet13 -> wsWTRBrokeredInternet</li>\n<li>Sheet14 -> wsConfirmationOutgoing3</li>\n<li>Sheet18 -> wsRecurringWTR</li>\n</ul>\n\n<p>Using nested <code>Select</code> statements are particularly hard to read. Normally I would alternate <code>Select</code> with <code>If..ElseIf..Else</code> statements but the procedure is entirely too long; so I recommend writing a subroutine for each <code>Case</code> of the top level <code>Select</code> statement (see code below).</p>\n\n<p>I only use <code>Range.EntireRow</code> when working with <code>Range</code> variables (e.g. <code>Target.EntireRow</code>). Using <code>Rows()</code> directly will make you code more condensed and the extra whitespace will make it easier to read. </p>\n\n<p>Before</p>\n\n<blockquote>\n<pre><code>Range(\"A200:A211\").EntireRow.Hidden = False\n</code></pre>\n \n <p>After</p>\n\n<pre><code>Rows(\"200:211\").Hidden = False\n</code></pre>\n</blockquote>\n\n<p><code>Application.ScreenUpdating = True</code> is no longer required. <code>ScreenUpdating</code> now resumes after the code has finished executing. </p>\n\n<h2>Refactored Code</h2>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\n Application.ScreenUpdating = False\n Application.EnableEvents = False\n Dim Unique_Identifier As String\n Dim Wire_Type As String\n\n Select Case Target.Address\n Case Is = \"$B$4\"\n EntryB4\n Case Is = \"$B$5\"\n EntryB5\n Case Is = \"$B$6\"\n EntryB6\n Case Is = \"$B$7\"\n EntryB7\n Case Is = \"$B$8\"\n EntryB8\n Case Is = \"$B$9\"\n EntryB9\n Case Is = \"$B$10\"\n EntryB10\n Case Is = \"$B$11\"\n EntryB11\n Rem Wires from Deposit Account or Loan (Post-Closing) Section\n Case Is = \"$B$205\"\n EntryB205\n Case Is = \"$B$227\"\n EntryB227\n Case Is = \"$B$269\"\n EntryB269\n Rem Loan-Closing Wires Section\n Case Is = \"$B$306\"\n EntryB306\n Case Is = \"$B$331\"\n EntryB331\n Case Is = \"$B$373\"\n EntryB373\n Rem Cash Management Wires Section\n Case Is = \"$B$406\"\n EntryB406\n Case Is = \"$B$425\"\n EntryB425\n Rem Internal Foresight Wires Section\n Case Is = \"$B$610\"\n EntryB610\n Rem Wire Transfer Agreement Section\n Case Is = \"$B$5004\"\n EntryB5004\n Rem Recurring Wire Transfer Request Section\n Case Is = \"$B$5104\"\n EntryB5104\n Case Is = \"$B$5118\"\n EntryB5118\n End Select\n\n Rem CIF Calls\n If Not Intersect(Target, Range(\"B103\")) Is Nothing Then CIFIncoming\n If Not Intersect(Target, Range(\"B206\")) Is Nothing Then CIFOutD\n If Not Intersect(Target, Range(\"B307\")) Is Nothing Then CIFOutL\n If Not Intersect(Target, Range(\"B407\")) Is Nothing Then CIFOutCM\n If Not Intersect(Target, Range(\"B506\")) Is Nothing Then CIFBrokered\n\n Application.EnableEvents = True\n\nEnd Sub\n\nSub EntryB4()\n With wsDataEntry\n .Activate\n Hide_All\n Select Case .Range(\"B4\")\n Case Is &lt;&gt; \"\"\n .Rows(\"100:199\").Hidden = False\n .Range(\"B101\").Select\n wsConfirmationIncoming.Visible = xlSheetVisible\n .Range(\"B5\") = \"\"\n Case Else\n .Range(\"B5\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB5()\n With wsDataEntry\n Hide_All\n .Activate\n Select Case .Range(\"B5\")\n Case Is &lt;&gt; \"\"\n .Rows(\"200:211\").Hidden = False\n .Rows(\"216:227\").Hidden = False\n .Range(\"B201\").Select\n With ThisWorkbook\n wsChecklist.Visible = xlSheetVisible\n wsConfirmationOutgoing1.Visible = xlSheetVisible\n wsWireTransferRequest1.Visible = xlSheetVisible\n End With\n\n Select Case .Range(\"B5\")\n Case Is &gt; 1\n .Rows(\"200:299\").Hidden = False\n Unique_Identifier = .Range(\"B5\").Value\n Wire_Type = \"Deposit/Loan\"\n Call Find_Recurring(Unique_Identifier, Wire_Type)\n End Select\n\n Case Else: .Range(\"B6\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB7()\n With wsDataEntry\n Hide_All\n .Activate\n Select Case .Range(\"B7\")\n Case Is &lt;&gt; \"\"\n .Rows(\"400:411\").Hidden = False\n .Rows(\"414:499\").Hidden = False\n .Range(\"B401\").Select\n With ThisWorkbook\n wsChecklistCashManagement.Visible = xlSheetVisible\n wsConfirmationOutgoing3.Visible = xlSheetVisible\n End With\n Case Else: .Range(\"B8\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB8()\n With wsDataEntry\n Hide_All\n .Activate\n Select Case .Range(\"B8\")\n Case Is &lt;&gt; \"\"\n .Rows(\"500:599\").Hidden = False\n .Range(\"B501\").Select\n With ThisWorkbook\n wsWTRBrokeredInternet.Visible = xlSheetVisible\n End With\n Case Else: .Range(\"B9\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB9()\n With wsDataEntry\n Hide_All\n .Activate\n Select Case .Range(\"B9\")\n Case Is &lt;&gt; \"\"\n .Rows(\"600:610\").Hidden = False\n .Range(\"B601\").Select\n wsChecklistInternal.Visible = xlSheetVisible\n\n Select Case .Range(\"B9\")\n Case Is &gt; 1\n .Rows(\"600:699\").Hidden = False\n Unique_Identifier = .Range(\"B9\").Value\n Wire_Type = \"Internal\"\n Call Find_Recurring(Unique_Identifier, Wire_Type)\n End Select\n\n Case Else: .Range(\"B10\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB10()\n With wsDataEntry\n Hide_All\n .Activate\n Select Case .Range(\"B10\")\n Case Is &lt;&gt; \"\"\n Sheet6.Visible = xlSheetVisible\n wsWTA.Visible = True\n .Rows(\"5000:5099\").Hidden = False\n .Rows(\"5005:5011\").Hidden = True\n .Range(\"B5001\").Select\n Case Else: .Range(\"B11\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB11()\n With wsDataEntry\n Hide_All\n .Activate\n Select Case .Range(\"B11\")\n Case Is &lt;&gt; \"\"\n wsRecurringWTR.Visible = xlSheetVisible\n .Rows(\"5100:5118\").Hidden = False\n .Rows(\"5111:5114\").Hidden = True\n .Range(\"B5101\").Select\n Case Else: .Range(\"B11\").Select\n End Select\n End With\nEnd Sub\n\nRem Wires from Deposit Account or Loan (Post-Closing) Section\nSub EntryB205()\n With wsDataEntry\n .Activate\n Select Case LCase(.Range(\"B205\"))\n Case Is = \"yes\"\n .Rows(\"212:215\").Hidden = False\n Case Else\n .Rows(\"212:215\").Hidden = True\n .Range(\"B206\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB227()\n With wsDataEntry\n .Activate\n Select Case LCase(.Range(\"B227\"))\n Case Is = \"domestic\"\n .Rows(\"222:243\").Hidden = False\n .Rows(\"267:299\").Hidden = False\n .Rows(\"244:266\").Hidden = True\n .Range(\"B229\").Select\n Case Is = \"international\"\n .Rows(\"244:299\").Hidden = False\n .Rows(\"228:243\").Hidden = True\n .Range(\"B245\").Select\n Case Is &lt;&gt; \"international\", \"domestic\"\n .Rows(\"228:299\").Hidden = True\n .Range(\"B227\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB269()\n With wsDataEntry\n .Activate\n Select Case LCase(.Range(\"B269\"))\n Case Is = \"yes\"\n wsWTA.Visible = True\n .Rows(\"5000:5099\").Hidden = False\n .Rows(\"282:299\").Hidden = True\n\n .Range(\"B5001\").Select\n Case Else\n wsWTA.Visible = False\n .Rows(\"5000:5099\").Hidden = True\n .Rows(\"281:299\").Hidden = False\n .Range(\"B270\").Select\n End Select\n End With\nEnd Sub\n\nRem Loan-Closing Wires Section\nSub EntryB306()\n With wsDataEntry\n .Activate\n Select Case LCase(.Range(\"B306\"))\n Case Is = \"yes\"\n .Range(\"A313:A316,A331\").EntireRow.Hidden = False\n Case Else\n .Rows(\"313:316\").Hidden = True\n .Rows(331).Hidden = False\n .Range(\"B307\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB331()\n With wsDataEntry\n .Activate\n Select Case LCase(.Range(\"B331\"))\n Case Is = \"domestic\"\n .Rows(\"332:347\").Hidden = False\n .Rows(\"370:399\").Hidden = False\n .Rows(\"348:369\").Hidden = True\n .Range(\"B331\").Select\n Case Is = \"international\"\n .Rows(\"347:399\").Hidden = False\n .Rows(\"332:346\").Hidden = True\n .Range(\"B349\").Select\n Case Is &lt;&gt; \"domestic\", \"international\"\n .Rows(\"332:399\").Hidden = True\n .Range(\"B331\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB373()\n With wsDataEntry\n .Activate\n Select Case LCase(.Range(\"B373\"))\n Case Is = \"yes\"\n wsWTA.Visible = True\n .Rows(\"5000:5099\").Hidden = False\n .Rows(\"383:399\").Hidden = True\n\n .Range(\"B5001\").Select\n Case Else\n wsWTA.Visible = False\n .Rows(\"5000:5099\").Hidden = True\n .Rows(\"383:399\").Hidden = False\n .Range(\"B374\").Select\n End Select\n\n End With\nEnd Sub\n\nRem Cash Management Wires Section\nSub EntryB406()\n With wsDataEntry\n .Activate\n Select Case LCase(.Range(\"B406\"))\n Case Is = \"yes\"\n .Rows(\"412:413\").Hidden = False\n Case Else\n .Rows(\"412:413\").Hidden = True\n .Range(\"B407\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB425()\n With wsDataEntry\n .Activate\n Select Case LCase(.Range(\"B425\"))\n Case Is = \"yes\"\n .Rows(\"430:431\").Hidden = False\n Case Else\n .Rows(\"430:431\").Hidden = True\n .Range(\"B426\").Select\n End Select\n End With\nEnd Sub\n\nRem Internal Foresight Wires Section\nSub EntryB610()\n With wsDataEntry\n .Activate\n Select Case LCase(.Range(\"B610\"))\n Case Is = \"domestic\"\n .Rows(\"611:625\").Hidden = False\n .Rows(\"648:699\").Hidden = False\n .Rows(\"626:647\").Hidden = True\n .Range(\"B612\").Select\n Case Is = \"international\"\n .Rows(\"626:699\").Hidden = False\n .Rows(\"611:625\").Hidden = True\n .Range(\"B627\").Select\n Case Is &lt;&gt; \"international\", \"domestic\"\n .Rows(\"611:699\").Hidden = True\n .Range(\"B610\").Select\n End Select\n\n End With\nEnd Sub\n\nRem Wire Transfer Agreement Section\nSub EntryB5004()\n With wsDataEntry\n .Activate\n .Rows(\"5005:5011\").Hidden = True\n .Range(\"B5004\").Select\n Select Case LCase(.Range(\"B5004\"))\n Case Is = \"entity\"\n .Rows(\"5007:5011\").Hidden = False\n .Range(\"B5007\").Select\n Case Is = \"individual(s)\"\n .Rows(\"5005:5006\").Hidden = False\n .Range(\"B5005\").Select\n End Select\n End With\nEnd Sub\n\nRem Recurring Wire Transfer Request Section\nSub EntryB5104()\n With wsDataEntry\n .Activate\n .Rows(\"5111:5114\").Hidden = True\n .Range(\"B5105\").Select\n Select Case LCase(.Range(\"B5104\"))\n Case Is = \"yes\"\n .Rows(\"5111:5114\").Hidden = False\n .Range(\"B5105\").Select\n Case Is = \"no\"\n .Rows(\"5111:5114\").Hidden = True\n .Range(\"B5105\").Select\n End Select\n End With\nEnd Sub\n\nSub EntryB5118()\n With wsDataEntry\n .Activate\n Select Case LCase(.Range(\"B5118\"))\n Case Is = \"domestic\"\n .Rows(\"5119:5131\").Hidden = False\n .Rows(\"5132:5199\").Hidden = True\n .Rows(5150).Hidden = False\n .Range(\"B5120\").Select\n Case Is = \"international\"\n .Rows(\"5119:5131\").Hidden = True\n .Rows(\"5132:5149\").Hidden = False\n .Rows(\"5151:5199\").Hidden = True\n .Range(\"B5133\").Select\n Case Is &lt;&gt; \"international\", \"domestic\"\n .Rows(\"5119:5199\").Hidden = True\n .Range(\"B5118\").Select\n End Select\n End With\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T12:32:04.137", "Id": "455395", "Score": "0", "body": "It's awesome that you refactored the code using almost the same method I came up with. I did use a function for the domestic and international because I wanted to try my hand at creating a function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T16:29:01.013", "Id": "455450", "Score": "0", "body": "@ZackE Thanks for accepting my answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T16:32:41.713", "Id": "455451", "Score": "0", "body": "They were both great answers. I wish I could have accepted them both but your answer was inline with what I did to refactor the code myself outside a couple of additions i wanted to make. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T12:25:07.040", "Id": "233060", "ParentId": "232999", "Score": "2" } } ]
{ "AcceptedAnswerId": "233060", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:04:10.180", "Id": "232999", "Score": "3", "Tags": [ "vba", "excel" ], "Title": "Inherited Code - Worksheet_Change Event Code" }
232999
<p>Given a vector of maps:</p> <pre><code>(def my-list [{:a 1 :b 2 :c 3} {:a 1 :b 5 :c 6} {:a 7 :b 8 :c 12} {:a 10 :b 11 :c 12}]) </code></pre> <p>and a blacklist:</p> <pre><code>(def blacklist [{:a 1 :c 3} {:a 10 :c 12}]) </code></pre> <p>the expected output is:</p> <pre><code>[{:a 1 :b 5 :c 6} {:a 7 :b 8 :c 12}] </code></pre> <p>I came up with:</p> <pre><code>(defn not-excluded? [blacklist item] (not-any? (fn [exclusion-item] (and (= (:a item) (:a exclusion-item)) (= (:c item) (:c exclusion-item)))) blacklist)) (filter (partial not-excluded? blacklist) my-list) </code></pre> <p>but there is probably a more idiomatic Clojure way.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T15:01:02.857", "Id": "455273", "Score": "0", "body": "I don't Clojure very well, but requiring `:a` and `:c` to be hardcoded in the function doesn't look like a good solution. Have you considered passing those as arguments instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T15:54:25.163", "Id": "455277", "Score": "0", "body": "Yeah, that's one thing, that can be improved for sure. " } ]
[ { "body": "<p>We want to exclude from the vector (more generally a sequence) the maps of which any map in the blacklist is a sub-map. Let's define a function that tests whether its first argument is a sub-map of its second argument:</p>\n\n<pre><code>(defn submap? [a b]\n (every? (fn [[k v]] (= v (b k))) a))\n</code></pre>\n\n<p>For instance,</p>\n\n<pre><code>=&gt; (map #(submap? {1 2} %) [{} {1 1} {1 2}])\n(false false true)\n</code></pre>\n\n<p>So far, so good. Let's use <code>submap?</code> to define function <code>clean</code> that takes a blacklist and a sequence of maps as arguments, excluding any supermaps of any map in the blacklist from the sequence:</p>\n\n<pre><code>(defn clean [blacklist ms]\n (filter\n (fn [m] (not-any? #(submap? % m) blacklist))\n ms))\n</code></pre>\n\n<p>For example, </p>\n\n<pre><code>=&gt; (clean blacklist my-list)\n({:a 1, :b 5, :c 6} {:a 7, :b 8, :c 12})\n</code></pre>\n\n<hr>\n\n<p><code>submap?</code> could be careful about absent keys. If you have <code>nil</code> values, you need to fix this. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T16:47:37.097", "Id": "237444", "ParentId": "233000", "Score": "2" } } ]
{ "AcceptedAnswerId": "237444", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T14:41:36.900", "Id": "233000", "Score": "2", "Tags": [ "clojure" ], "Title": "Filtering vector of maps based on a blacklist" }
233000
<p>Yes I know context managers are a much better way to do this, but I spent four hours working on implementing a switch construct using generic decorators, and I'd like to hear feedback on how I did. I'll do it with context managers tomorrow. </p> <p>&nbsp;<br> I don't think I qualify as a beginner anymore (I'm looking to start getting paid to write Python soon), and I would appreciate guidance on best practices.</p> <hr> <p><strong>My Code</strong></p> <pre class="lang-py prettyprint-override"><code>"""Module to implement C style switch functionality using decorators. Functions: `switch_construct`: Returns functions that provide the required functionality and provides a closure for said functions. """ __all__ = ["switch", "case", "break_"] import operator as op def switch_construct(): """Forms a closure to store the meta data used by the switch construct. Vars: `closure` (list): List to store dictionaries containing metadata for each `switch` instance. * The dictionary contains two keys: "control" and "halt". - "control": the value governing the current switch instance. `case` blocks are tested against this value. - `halt`: value is used to implement break functionality. &gt; `True`: break after execution of current function. &gt; Default: `False`. Returns: tuple: A tuple of functions (`switch`, `case`, `break_`) defined in the function's scope. """ closure = [] def switch(input_): """Sets the metadata for the current `switch` block. Args: `input` (object): The value governing the switch construct. Returns: `function`: A decorator for the function enclosing the switch block. """ nonlocal closure def decorator(func): closure.append({"control": input_, "halt": False}) # Add the metadata to closure. # Sets `control` to `input_` and `halt` to `False` for each `switch` block. def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.switch_index = len(closure)-1 # Assign the `switch_index` attribute to the decorated function for using when retrieving switch construct metadata. return wrapper return decorator def case(value, enclosing, test = op.eq): """Returns a decorator which executes decorated function only if its `value` argument satisfies some test. Args: `value` (object): value used to test whether the decorated function should be executed. `enclosing` (function): enclosing function corresponding to the current switch block. `test` (function): test that should be satisfied before decorated function is executed. - Default value is `op.eq`. - Returns `bool`. Returns: function: A decorator for the function corresponding to the case block. """ def decorator(func): nonlocal closure index = enclosing.switch_index return_value = None if test(value, closure[index]["control"]) and not closure[index]["halt"]: return_value = func() return return_value return decorator def break_(enclosing): """Used to indicate that the switch construct should break after execution of the current function.""" nonlocal closure closure[enclosing.switch_index]["halt"] = True return None return case, switch, break_ case, switch, break_ = switch_construct() @switch(2) def func(): """Sample use case of the switch construct.""" @case(1, func) def _(num=10): print(num + 1) @case(2, func) def _(num=10): print(num + 2) break_(func) @case(3, func, op.gt) def _(num=10): print(num + 3) func() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T15:23:15.703", "Id": "455274", "Score": "4", "body": "Interesting. I'm somewhat surprised it works, but it's definitely interesting." } ]
[ { "body": "<p>I wish I had enough practice with decorators to be able to comment on most of this. I've never really <em>needed</em> to play with them, so I've kind of neglected them beyond simple memoization toys. This looks pretty cool, but I think all I can comment on are a few things along with the low-hanging PEP fruit since no-ones jumped on that yet :)</p>\n\n<pre><code>len(closure)-1\n</code></pre>\n\n<p>This should <a href=\"https://www.python.org/dev/peps/pep-0008/#other-recommendations\" rel=\"noreferrer\">have spaces in there</a>:</p>\n\n<blockquote>\n <p>Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, &lt;, >, !=, &lt;>, &lt;=, >=, in, not in, is, is not), Booleans (and, or, not).</p>\n</blockquote>\n\n<p>It doesn't explicitly mention <code>-</code>, but the \"No:\" examples after that bit above suggest that it should use spaces as well.</p>\n\n<p>And on the other end,</p>\n\n<pre><code>test = op.eq\n</code></pre>\n\n<p><em>Shouldn't</em> use spaces (from the link above again):</p>\n\n<blockquote>\n <p>Don't use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter.</p>\n</blockquote>\n\n<hr>\n\n<p><code>break_</code> doesn't need a <code>return None</code> in there. That's implicit.</p>\n\n<hr>\n\n<p>Some of what you're documenting with doc-strings could be documented in other arguably cleaner ways.</p>\n\n<p>For example, in <code>switch_construct</code> you have:</p>\n\n<pre><code>* The dictionary contains two keys: \"control\" and \"halt\".\n - \"control\": the value governing the current switch instance. `case` blocks are tested against this value.\n - `halt`: value is used to implement break functionality. \n &gt; `True`: break after execution of current function.\n &gt; Default: `False`.\n</code></pre>\n\n<p>You have a dictionary that should only take on certain keys. This sounds more like a job for a <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"noreferrer\"><code>dataclass</code></a> instead of a dictionary:</p>\n\n<pre><code>from dataclasses import dataclass\n\n@dataclass\nclass SwitchMetadata:\n \"\"\"- \"control\": the value governing the current switch instance. `case` blocks are tested against this value.\n - `halt`: value is used to implement break functionality.\n \"\"\"\n\n control: str\n halt: bool = False # Makes the constructor allow halt to default to False\n\n. . .\n\nclosure.append(SwitchMetadata(input_))\n\n. . .\n\nif test(value, closure[index].control) and not closure[index].halt\n\n. . .\n\nclosure[enclosing.switch_index].halt = True\n</code></pre>\n\n<p>This gets rid of the need for string dictionary lookups and gives some type safety. Both of these decrease the chance you'll make silly typos since both allow for static checking by the IDE. The class definition also clearly communicates to the reader what the structure holds and what types the data should be.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T03:16:50.113", "Id": "455347", "Score": "0", "body": "Thanks a lot for the answer. I've actually read PEP 8 in its entirety, so my stylistic deviations weren't due to ignorance. I wrote `test = op.eq` because I found that more readable, but I would change it in the updated version of the code. PEP 8 provides no recommendation for the operators not listed there (they use both `a ∆ b` and `a∆b` as examples of how to write code (`∆` being an arbitrary binary operator not in the above list). The `dataclass` recommendation was greatly appreciated, and I've refactored my code to use one." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T23:13:53.030", "Id": "233028", "ParentId": "233001", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T15:10:17.657", "Id": "233001", "Score": "10", "Tags": [ "python", "functional-programming" ], "Title": "C-style `switch` statement implementation using decorators" }
233001
<p>I have the following code for separating out overlapping rectangles vs. non-overlapping rectangles in C++ 11:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;opencv/cv.h&gt; #include &lt;opencv/highgui.h&gt; #include &lt;opencv/cxcore.h&gt; #include &lt;math.h&gt; #include &lt;array&gt; int main() { auto detected = get_detected(); std::vector &lt;Rect&gt; singles; std::vector &lt;Rect&gt; overlaps; for (auto rect_1: detected) { bool isSingle = false; for (auto rect_2: detected) { if (rect_1 == rect_2) { continue; } bool intersects = ((rect_1 &amp; rect_2).area() &gt; 0); if (intersects) { isSingle = false; break; } } if (isSingle) { singles.push_back(rect_1); } else { overlaps.push_back(rect_1); } } } </code></pre> <p>How do I make this cleaner? I'm thinking of doing <code>singles.push_back(std::move(rect_1));</code>, but I'm not sure if that's a good idea.</p> <p>I would love some guidance in the right direction.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T17:45:41.903", "Id": "455301", "Score": "1", "body": "Where is `get_detected()` defined?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T18:21:21.430", "Id": "455303", "Score": "2", "body": "This looks like it has a bug, you never set `isSingle` to true." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T11:33:03.897", "Id": "455386", "Score": "0", "body": "If you have many rectangles then you probably want to use a data structure that is dedicated to your problem instead of lists. See for example [this SO post](https://stackoverflow.com/questions/39131196/data-structure-for-determining-intersection-of-rectangle-with-a-larger-set-of-re)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:16:06.800", "Id": "455406", "Score": "0", "body": "You can get rid of the loop spaghetti introduced by the usage of `break` and `continue` with an iterator-based outer loop and replacing the inner loop with `std::find_if(i, end(), predicate)`. I had a nice spelled answer but unfortunately this question get closed before I could post. **That** would be clean code." } ]
[ { "body": "<h2>Bug</h2>\n<pre><code> if (intersects) {\n isSingle = false;\n break;\n }\n</code></pre>\n<p>This looks like a bug. The variable <code>isSingle</code> is already false. Setting it to false here does nothing.</p>\n<h2>Code Review:</h2>\n<p>You use <code>std::vector</code> but don't include its header.</p>\n<pre><code> std::vector &lt;Rect&gt; overlaps;\n</code></pre>\n<p>You should fix that.</p>\n<hr />\n<p>References and Const correctness.</p>\n<p>This is a big part of C++.</p>\n<ol>\n<li><p>If you are not modifying an object, prefer to use reference than making a copy of an object.</p>\n</li>\n<li><p>Prefer const references over normal references to prevent accidental modification.</p>\n<p>for (auto rect_1: detected) {</p>\n</li>\n</ol>\n<p>Here you are making a copy of the object from the array detected into the object <code>rect_1</code>. Personally I would use a const reference to prevent the overhead of a copy:</p>\n<pre><code>for (auto const&amp; rect_1: detected) {\n</code></pre>\n<hr />\n<p>The code looks mostly fine:</p>\n<p>I think the only bug is here:</p>\n<pre><code> if (rect_1 == rect_2) {\n continue;\n }\n</code></pre>\n<p>This tells you if two rectangles are equivalent not if they are the same rectangle. If you have two distinct but otherwise identical rectangle then by my logic they would overlap and thus not be in the single's list.</p>\n<p>So you need a way to determine if these are the same object. Personally I would do that by changing your <code>for</code> loops to use references and then comparing the objects' addresses.</p>\n<pre><code> for (auto const&amp; rect_1: detected) {\n ^^^^^^\n ...\n for (auto const&amp; rect_2: detected) {\n ^^^^^^\n if ( &amp; rect_1 == &amp; rect_2) {\n ^^^ ^^^\n continue;\n }\n\n test(rect_1, rect_2);\n</code></pre>\n<p>Your other alternative is to make sure you never compare an object with itself. This also brings into mind that you do twice as many comparisons as you need to. You compare every rectangle against every other rectangle. But if <code>A &amp; B</code> overlap then we already know that <code>B &amp; A</code> will overlap.</p>\n<pre><code>for(std::size_t loop = 0l; loop &lt; detected.size(); ++loop) {\n for(auto check = loop + 1; check &lt; detected.size(); ++check) {\n test(detected[loop], detected[check]);\n</code></pre>\n<hr />\n<blockquote>\n<p>in the code below &quot;...object addresses&quot; -- aren't <code>rect_1</code> and <code>rect_2</code> references already? If so, why can't we just do <code>if (rect_1 == rect_2)</code></p>\n</blockquote>\n<p>No. Because the <code>==</code> is supposed to compare the equality (is the state the same) of two objects. It is not supposed to be a test of equivalence (is it the same object).</p>\n<p>Note: You can declare <code>operator==</code> to test if the objects are the same but that would be terrible practice and would cause a lot of issues with people expecting the normal operation. So don't do that. The above statement is said assuming you are following the normal idioms of the language.</p>\n<p>I assume you are coming from a Java like background. The term <em>reference</em> in C++ has a different meaning than in Java. A reference means another name for an object (they are not like Java references (which in C++ we would call <em>pointers</em>). So a reference is another name for an object but the test <code>operator==</code> will compare if the two objects' state are the same (not if they are the same object).</p>\n<blockquote>\n<p>Also, if I use <code>auto const&amp;</code>, I would have to change my return type to <code>vector&lt;Rect&amp;&gt;</code>...is that idiomatic? I think the OpenCV API expects <code>vector&lt;Rect&gt;</code></p>\n</blockquote>\n<p>No. You can pass a reference to the vector and it will copy the object into the vector. You don't want to hold references in a vector.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T17:30:10.257", "Id": "455297", "Score": "0", "body": "in the code below \"...object addresses\" -- aren't `rect_1 `and `rect_2` references already? If so, why can't we just do `if (rect_1 == rect_2)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T17:35:13.250", "Id": "455299", "Score": "0", "body": "Also, if I use `auto const&`, I would have to change my return type to `vector<Rect&>`...is that idiomatic? I think the opencv api expects vector<Rect>" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T18:32:00.183", "Id": "455305", "Score": "0", "body": "@nz_21 Added some state to the question. As those comments are hard to answer in a comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T10:28:31.163", "Id": "455380", "Score": "0", "body": "This answer is nice but doesn’t fix the glaring bug in the code. It’s just rearranging the deck chairs, as it were. (I’m also not a big fan of the suggestion to use index-based loops over iterators.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T15:56:04.277", "Id": "455439", "Score": "0", "body": "@KonradRudolph which bug did i not suggest a fix for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T16:04:17.880", "Id": "455442", "Score": "0", "body": "It will never find single rectangles, since `isSingle` is never set to `true`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T17:47:07.783", "Id": "455463", "Score": "0", "body": "@KonradRudolph lol. Yes. That is so true." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T17:16:18.617", "Id": "233011", "ParentId": "233002", "Score": "11" } }, { "body": "<p>Prefer <code>&lt;cstdio&gt;</code> to <code>&lt;stdio.h&gt;</code> and <code>&lt;cmath&gt;</code> to <code>&lt;math.h&gt;</code> in C++ code. You will probably never need the C compatibility headers unless you're writing headers that must also be included in C code. The compatibility headers are less useful in C++ code, because they declare everything in the global namespace rather than neatly in <code>std</code>.</p>\n\n<p>Prefer not including headers at all when you don't use them (as is the case here). Unnecessary includes waste the compiler's time and the reader's brainpower.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T20:32:05.587", "Id": "233019", "ParentId": "233002", "Score": "6" } } ]
{ "AcceptedAnswerId": "233011", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T15:27:15.957", "Id": "233002", "Score": "3", "Tags": [ "c++", "opencv" ], "Title": "Merging rectangles in C++" }
233002
<p>I am working on a PHP MVC project for my portfolio. Its an web app where you can store contacts (email and phone number). I am having trouble with filtering contacts based on filter form that has 3 options <a href="https://ibb.co/8dJbSWd" rel="nofollow noreferrer">https://ibb.co/8dJbSWd</a></p> <p>I wrote code that works fine but I am sure there is better way of doing this. Here is the code that I wrote for solving this problem.</p> <pre><code>public function filterContacts($user_id, $group, $email, $phone){ $query = 'SELECT * FROM contacts WHERE user_id = :user_id '; //Nothing is selected if($group == '0' &amp;&amp; $email == '' &amp;&amp; $phone == ''){ $this-&gt;db-&gt;query($query . ' ORDER BY name'); $this-&gt;db-&gt;bind(':user_id', $user_id); return $this-&gt;db-&gt;resultSet(); //Everything is selected } else if ($group !== '0' &amp;&amp; $email !== '' &amp;&amp; $phone !== ''){ $query .= 'AND contact_group = :group AND email != "" AND phone_number != ""'; $this-&gt;db-&gt;query($query . 'ORDER BY name'); $this-&gt;db-&gt;bind(':user_id', $user_id); $this-&gt;db-&gt;bind(':group', $group); return $this-&gt;db-&gt;resultSet(); //Just group } else if ($group !== '0' &amp;&amp; $email == '' &amp;&amp; $phone == ''){ $query .= 'AND contact_group = :group '; $this-&gt;db-&gt;query($query . 'ORDER BY name'); $this-&gt;db-&gt;bind(':user_id', $user_id); $this-&gt;db-&gt;bind(':group', $group); return $this-&gt;db-&gt;resultSet(); //Just email } else if ($group == '0' &amp;&amp; $email !== '' &amp;&amp; $phone == ''){ $query .= 'AND email != "" '; $this-&gt;db-&gt;query($query . 'ORDER BY name'); $this-&gt;db-&gt;bind(':user_id', $user_id); return $this-&gt;db-&gt;resultSet(); //Just phone } else if ($group == '0' &amp;&amp; $email == '' &amp;&amp; $phone !== ''){ $query .= 'AND phone_number != "" '; $this-&gt;db-&gt;query($query . 'ORDER BY name'); $this-&gt;db-&gt;bind(':user_id', $user_id); return $this-&gt;db-&gt;resultSet(); //Group and email } else if($group !== '0' &amp;&amp; $email !== '' &amp;&amp; $phone == ''){ $query .= 'AND contact_group = :group AND email != ""'; $this-&gt;db-&gt;query($query . 'ORDER BY name'); $this-&gt;db-&gt;bind(':user_id', $user_id); $this-&gt;db-&gt;bind(':group', $group); return $this-&gt;db-&gt;resultSet(); //Group and phone number } else if($group !== '0' &amp;&amp; $email == '' &amp;&amp; $phone !== ''){ $query .= 'AND contact_group = :group AND phone_number != ""'; $this-&gt;db-&gt;query($query . 'ORDER BY name'); $this-&gt;db-&gt;bind(':user_id', $user_id); $this-&gt;db-&gt;bind(':group', $group); return $this-&gt;db-&gt;resultSet(); //Email and phone number } else if($group == '0' &amp;&amp; $email !== '' &amp;&amp; $phone !== ''){ $query .= 'AND phone_number != "" AND email != ""'; $this-&gt;db-&gt;query($query . 'ORDER BY name'); $this-&gt;db-&gt;bind(':user_id', $user_id); return $this-&gt;db-&gt;resultSet(); } } </code></pre> <p>As you can see I used a lot of if statements to make different queries in Contact model which is possible because i have only 3 filtering options but I cannot imagine doing this with 10 options.</p> <p><strong>So I was wondering is there a better way of solving this?</strong></p> <p>Here is link to my github repository if you want to see rest of the code <a href="https://github.com/Smiley-dev/Phonebook-demo" rel="nofollow noreferrer">https://github.com/Smiley-dev/Phonebook-demo</a></p>
[]
[ { "body": "<p>The entire long conditional is definitely worth to be decomposed and consolidated.</p>\n\n<p>The main mechanics of optimization is based on 3 aspects:</p>\n\n<ul>\n<li><p>determining a common logic/behavior that needs to be unified. In your case such a common fragment is:</p>\n\n<pre><code>$this-&gt;db-&gt;query($query . 'ORDER BY name');\n$this-&gt;db-&gt;bind(':user_id', $user_id);\nreturn $this-&gt;db-&gt;resultSet();\n</code></pre></li>\n<li><p>considering only populated fields</p></li>\n<li>collecting <em>bindings</em> for particular fields</li>\n</ul>\n\n<hr>\n\n<p>The final optimized function becomes as below:</p>\n\n<pre><code>public function filterContacts($user_id, $group, $email, $phone){\n\n $query = 'SELECT * FROM contacts WHERE user_id = :user_id';\n $bindings = [':user_id':=&gt; $user_id];\n\n if ($group !== '0') {\n $query .= ' AND contact_group = :group';\n $bindings[':group'] = $group;\n } \n if ($email !== '') {\n $query .= ' AND email != \"\"';\n }\n if ($phone !== '') {\n $query .= ' AND phone_number != \"\"';\n }\n\n $this-&gt;db-&gt;query($query . ' ORDER BY name');\n foreach ($bindings as $k =&gt; $v) {\n $this-&gt;db-&gt;bind($k, $v);\n }\n\n return $this-&gt;db-&gt;resultSet();\n}\n</code></pre>\n\n<hr>\n\n<p>In case if your DB clent <code>$this-&gt;db</code> allows to pass an array of bindings you can just replace the loop with <code>$this-&gt;db-&gt;bind($bindings);</code> (check your DB client interface)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:04:36.707", "Id": "455418", "Score": "1", "body": "Thank you a lot. I think I finally wrote a clean and flexible solution" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T19:30:28.393", "Id": "233017", "ParentId": "233006", "Score": "3" } }, { "body": "<p>I must say, I don't find your method to be very scalable because every time you want to add an additional column filter, you will need to add another function argument. Furthermore, what happens when you want to express a different sorting direction or entertain a more sophisticated sorting algorithm with multiole columns? Right now you have four arguments:</p>\n\n<pre><code>public function filterContacts($user_id, $group, $email, $phone) {\n</code></pre>\n\n<p>This is relatively inflexible. </p>\n\n<p>In the future, if you want to add <code>$status</code>, <code>$mobile</code>, <code>$state</code>, <code>$shoeSize</code>, <code>$bloodType</code>, <code>$birthYear</code> ...you get my point... your method declaration will be threatening to exceed (if not blowing out) <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">the recommended line width limits</a>.</p>\n\n<p>What I recommend is that you design your method <em>now</em> to embrace the possibility of change (so that you won't need to do a major refactor when it is much, much bigger).</p>\n\n<pre><code>public function getContacts($filterBy = [], $orderBy = []) {\n ...\n}\n</code></pre>\n\n<p>Then before your controller calls this function, you determine which qualifying filters and sorting settings are to be passed in and you contruct two strictly formatted arrays which will be consumed by the new model method.</p>\n\n<p>The advantage of setting default values in the method declaration is that you can request a full table dump if you pass no arguments from the controller or you can send <code>$filterBy</code> and omit <code>$orderBy</code> and everything ticks along smoothly with no unnecessary script bloat.</p>\n\n<p>Initially, you may want a simple associative array to port this data, but as your method requirement become more articulate, you may need to develop a multidimensional array structure -- mercifully, I'll avoid dragging you down that rabbit hole for now.</p>\n\n<p>As for the guts of the new method, for utility (until you have a compelling reason to specifically name the result set columns or you need to JOIN tables), just use <code>SELECT *</code> and <code>FROM contacts</code>.</p>\n\n<p>Then implement a battery of checks as you traverse your filtering array on the key (column reference) - value (filtering data value for the column) pairs and insert <code>?</code> placeholders into the sql statement and build a flat array of parameters to be fed into the <code>execute()</code> call (no need for bind calls).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T09:35:56.407", "Id": "455376", "Score": "0", "body": "Ofc it was me. the other answer is so incomparably better and seeing this one accepted is so frustrating that I just cant help it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T09:40:45.583", "Id": "455378", "Score": "0", "body": "There are other ways to improve SE site content than downvoting. You know I'll listen to what you have to say. If you are just having a classic, venomous YCS moment, I understand -- I've seen it many times before. Obviously I didn't spend so much of my volunteer time writing up this answer because I wanted to poison the knowledge pool. I can at least appreciate your courage to comment with your downvote -- so few do. I will absorb your unconstructive negativity and harbor no vengeful thoughts. I respect your best qualities and pity your foibles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:04:04.420", "Id": "455417", "Score": "0", "body": "Thank you a lot. I think I finally wrote a clean and flexible solution" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T22:06:39.833", "Id": "233024", "ParentId": "233006", "Score": "0" } }, { "body": "<p>At the end I wrote something like this</p>\n\n<p><strong>Controler method</strong></p>\n\n<pre><code>public function filter(){\n\n if ($_SERVER['REQUEST_METHOD'] == 'POST'){\n\n $filters = $_POST;\n\n $contacts = $this-&gt;contactModel-&gt;getContacts($_SESSION['user_id'], $filters);\n\n $data = [\n 'contacts' =&gt; $contacts\n ];\n\n $this-&gt;view('contacts/table', $data);\n }\n\n }\n</code></pre>\n\n<p><strong>Model method</strong></p>\n\n<pre><code>public function getContacts($user_id, $filterBy = []){\n\n\n $query = 'SELECT * FROM contacts WHERE user_id = :user_id ';\n $bindings = [':user_id' =&gt; $user_id];\n\n if(!empty($filterBy)){\n\n if($filterBy['group'] !== '0'){\n $query .= 'AND contact_group = :group ';\n $bindings[':group'] = $filterBy['group'];\n }\n if($filterBy['email'] !== 'false'){\n $query .= 'AND email != \"\" ';\n }\n if($filterBy['phone'] !== 'false'){\n $query .= 'AND phone_number != \"\" ';\n }\n\n if($filterBy['search'] !== ''){\n $query .= 'AND name LIKE :search ';\n $bindings[':search'] = '%' . $filterBy['search'] . '%';\n }\n }\n\n $this-&gt;db-&gt;query($query);\n foreach ($bindings as $key =&gt; $value){\n $this-&gt;db-&gt;bind($key, $value);\n }\n\n return $this-&gt;db-&gt;resultSet();\n\n }\n</code></pre>\n\n<p>It works fine and it seems good enough for me. Thanks a lot for your help</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T07:12:40.837", "Id": "455501", "Score": "0", "body": "`if(!empty($filterBy)){` is superfluous. you can remove this condition and it wouldn't change anything." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:11:41.930", "Id": "233070", "ParentId": "233006", "Score": "0" } } ]
{ "AcceptedAnswerId": "233024", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T16:34:30.207", "Id": "233006", "Score": "0", "Tags": [ "php", "mysql", "mvc" ], "Title": "Filtering data from MYSQL database based on parameters passed with POST request" }
233006
<p>I'm learning racket and did simple code challenge in a <a href="https://github.com/togakangaroo/daily-programmer/tree/master/matrix-sum-of-region" rel="nofollow noreferrer">literate programming style</a> with org mode</p> <p>The problem:</p> <blockquote> <p>Given a matrix of integers and the top left and bottom right coordinates of a rectangular region within the matrix, find the sum of numbers falling inside the rectangle.</p> </blockquote> <pre><code>1 2 3 4 5 6 7 8 9 0 1 2 </code></pre> <p>should give <code>24</code> for locations <code>(1 1)-(3 2)</code> as that is the sum of the submatrix</p> <pre><code>6 7 8 0 1 2 </code></pre> <p><a href="https://github.com/togakangaroo/daily-programmer/tree/master/matrix-sum-of-region#org4406919" rel="nofollow noreferrer">Here is my final implementation</a></p> <pre class="lang-lisp prettyprint-override"><code>(require math/array) (struct location (column row)) (define (sum-matrix-region matrix start end) (define slice-spec (list (:: (location-row start) (add1 (location-row end))) (:: (location-column start) (add1 (location-column end))))) (define sliced (array-slice-ref matrix slice-spec)) (array-all-sum sliced)) (sum-matrix-region (array #[#[1 2 3 4] #[5 6 7 8] #[9 0 1 2]]) (location 1 1) (location 3 2)) </code></pre> <p>Is that good? Idiomatic? Anything I could have done better?</p> <p>I'm aware that for literate programming I can provide variables via tables but <a href="https://github.com/wallyqs/ob-racket" rel="nofollow noreferrer">the only racket-supporting org plugin</a> I found doesn't support that.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T16:41:00.313", "Id": "233007", "Score": "2", "Tags": [ "racket" ], "Title": "Sum of matrix region in racket" }
233007
Use this tag for questions involving code that is consuming a GraphQL API. Note that a GraphQL schema isn't reviewable on its own.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T16:44:12.597", "Id": "233009", "Score": "0", "Tags": null, "Title": null }
233009
<p>The code is doing everything that I need it to. It's taking much too long though upwards of a couple minutes to complete the macro. Does anyone know how I code optimize this VBA code to run quicker? I'm new to VBA and I'm not quite sure how to proceed. This code will be running on roughly 35,000 lines of data.</p> <pre><code>Public Sub matchRow() Dim dumpSheet, referencesheet, outputSheet As Worksheet Dim startRow, outputRow, tempDumpRow, tempActiveRow, referenceRowCount, finishedreferenceIndex As Integer Dim finishedreference() As String Dim isExist As Boolean 'Set sheets Set dumpSheet = Sheets("Dump") Set referencesheet = Sheets("Active Directory") Set outputSheet = Sheets("Output") 'Set start row of each sheet for data startRow = 5 outputRow = 5 'Get row count from Active Depository sheet referenceRowCount = referencesheet.Range("B5:D5").End(xlDown).Row 'Set index finishedreferenceIndex = 5 'Re-define array ReDim finishedreference(5 To referenceRowCount - 1) 'Set the start row tempDumpRow = startRow 'Here I looped with OR state, you can modify it to AND start if you want Do While dumpSheet.Range("B" &amp; tempDumpRow) &lt;&gt; "" Or dumpSheet.Range("C" &amp; tempDumpRow) &lt;&gt; "" Or dumpSheet.Range("D" &amp; tempDumpRow) &lt;&gt; "" 'Reset exist flag isExist = False 'loop all row in Active Depository sheet For tempActiveRow = 5 To referenceRowCount Step 1 'If row is not finished for checking. If UBound(Filter(finishedreference, tempActiveRow)) &lt; 0 Then 'If all cell are equal If dumpSheet.Range("B" &amp; tempDumpRow) = referencesheet.Range("B" &amp; tempActiveRow) And _ dumpSheet.Range("C" &amp; tempDumpRow) = referencesheet.Range("C" &amp; tempActiveRow) And _ dumpSheet.Range("D" &amp; tempDumpRow) = referencesheet.Range("D" &amp; tempActiveRow) Then 'Set true to exist flag isExist = True 'Store finished row finishedreference(finishedreferenceIndex) = tempActiveRow finishedreferenceIndex = finishedreferenceIndex + 1 'exit looping Exit For End If End If Next tempActiveRow 'Show result outputSheet.Range("B" &amp; outputRow) = dumpSheet.Range("B" &amp; tempDumpRow) outputSheet.Range("C" &amp; outputRow) = dumpSheet.Range("C" &amp; tempDumpRow) outputSheet.Range("D" &amp; outputRow) = dumpSheet.Range("D" &amp; tempDumpRow) If isExist Then outputSheet.Range("E" &amp; outputRow) = "" Else outputSheet.Range("E" &amp; outputRow) = "Item found in ""Dump"" but not in ""Active Directory""" End If 'increase output row outputRow = outputRow + 1 'go next row tempDumpRow = tempDumpRow + 1 Loop 'loop all row in Active Depository sheet For tempActiveRow = 5 To referenceRowCount Step 1 'If row is not finished for checking. If UBound(Filter(finishedreference, tempActiveRow)) &lt; 0 Then 'Show result outputSheet.Range("B" &amp; outputRow) = referencesheet.Range("B" &amp; tempActiveRow) outputSheet.Range("C" &amp; outputRow) = referencesheet.Range("C" &amp; tempActiveRow) outputSheet.Range("D" &amp; outputRow) = referencesheet.Range("D" &amp; tempActiveRow) outputSheet.Range("E" &amp; outputRow) = "Item found in ""Active Directory"" but not in ""Dump""" 'increase output row outputRow = outputRow + 1 End If Next tempActiveRow End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T19:23:05.693", "Id": "455310", "Score": "1", "body": "Could you add detail to explain what your code does?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T19:29:10.933", "Id": "455311", "Score": "0", "body": "@IEatBagels Yes, the code is taking Names, IDs, and Departments and comparing it against a directory of all active employees. The code will then output Name, ID,Department, and add whether the employee is found in one list or the other. If the employee is in both lists then there is no message in the output" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T20:22:51.033", "Id": "455318", "Score": "1", "body": "My immediate suggestion is to look through previous Code Reviews for VBA and pick out some constant themes - apply those themes to your code and then resubmit for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T20:26:10.410", "Id": "455319", "Score": "1", "body": "Key themes to look for are `Option Explicit`, declaring variables on one line (hint: `Dim dumpSheet, referencesheet, outputSheet As Worksheet` does not do what you think it does), explicitly using default actions (e.g. `Range(x).Value=\"\"` instead of `Range(x) = \"\"`) and declaring variables near where you use them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T20:29:48.483", "Id": "455320", "Score": "1", "body": "Reading the previous reviews you will see many examples of using arrays to improve performance. The reason I mention all this is because while there are many people here happy to review code and provide advice, we are not a free refactoring or rewriting service. Your main question \"Someone suggested loading data as variant arrays as opposed to ranges. I'm stuck.\" implies that you are looking for specific help, not a review. There are also many examples of using arrays instead of ranges on StackOverflow. Remember to filter searches with '[vba]'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T21:55:03.757", "Id": "455329", "Score": "1", "body": "Using `SQL` is great for these type of set based comparisons. You can use ADO in Excel if you wish, although it plays nicer in an actual database. I'd recommend checking that out though!" } ]
[ { "body": "<p>This is the sample dataset I created. The OP's code suggests that the Active Directory tab has an extra row.</p>\n\n<p><a href=\"https://i.stack.imgur.com/3eQv4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3eQv4.png\" alt=\"Sample Dataset\"></a></p>\n\n<p><strong>Always Use Worksheets CodeNames Whenever Possible</strong></p>\n\n<p>Referencing worksheets by their code names will avoid naming conflicts while working with multiple workbooks and changing the worksheet name will not break any code. </p>\n\n<ul>\n<li>Sheets(\"Active Directory\") -> wsActiveDirectory</li>\n<li>Sheets(\"Dump\")-> wsDump</li>\n<li>Sheets(\"Output\") -> wsOutput</li>\n</ul>\n\n<h2>Use Constants for Magic Numbers</h2>\n\n<p>Using constants for values that should only be set once will make your code easier to read and maintain. Constants will also throw an error if you try to change their values.</p>\n\n<p>Before</p>\n\n<blockquote>\n<pre><code>startRow = 5\noutputRow = 5\n</code></pre>\n</blockquote>\n\n<p>After</p>\n\n<blockquote>\n <p></p>\n</blockquote>\n\n<p>Const startRow As Long = 5, outputRow As Long = 5</p>\n\n<h2>Matching Lists</h2>\n\n<p>Dictionaries are optimised for fast lookups. Using a Scripting.Dictionary will match the values will easily make the code run 100 times faster. </p>\n\n<p>The trick is to create a composite key for all fields. Note: make sure to use a delimiter.</p>\n\n<blockquote>\n <p>1;Towney;Research and Development</p>\n</blockquote>\n\n<pre><code>Private Function getKey(ByVal rowIndex As Long, ByRef Target As Range) As String\n getKey = Target.Cells(rowIndex, 1) &amp; \";\" &amp; Target.Cells(rowIndex, 2) &amp; \";\" &amp; Target.Cells(rowIndex, 3)\nEnd Function\n</code></pre>\n\n<h2>SQL Solution</h2>\n\n<p>As Ryan Wildry stated \"Using SQL is great for these type of set based comparisons.\" but this can be a little tricky. The way I did it is I pasted my datasets into an Access Database as tables and use the Query Designer to help me write the code.</p>\n\n<blockquote>\n<pre><code>SELECT Dump.ID, Dump.Name, Dump.Department, \"Item found in \"\"Dump\"\" but not in \"\"Active Directory\"\"\" AS [Found]\nFROM Dump\nWHERE (((Exists (SELECT NULL\n FROM [Active Directory]\n WHERE ([Active Directory].ID = Dump.ID) AND ([Active Directory].Name = Dump.Name) AND ([Active Directory].Department = Dump.Department)\n))=False));\nUNION ALL SELECT [Active Directory].ID, [Active Directory].Name, [Active Directory].Department, \"Item found in \"\"Active Directory\"\" but not in \"\"[Active Directory]\"\"\" AS [Found]\nFROM [Active Directory]\nWHERE (((Exists (SELECT NULL\n FROM [Dump]\n WHERE ([Active Directory].ID = Dump.ID) AND ([Active Directory].Name = Dump.Name) AND ([Active Directory].Department = Dump.Department)\n))=False));\n</code></pre>\n</blockquote>\n\n<p>I then aliased the tables to make it easier to replace the table names with the Excel Table Definition.</p>\n\n<blockquote>\n<pre><code> SELECT t1.Name, t1.ID, t1.Department, 'Item found in \"Dump\" but not in \"Active Directory\"' AS [Found]\n FROM [Dump$B4:E23] As t1\n WHERE (((Exists (SELECT NULL\n FROM [Active Directory] As t2\n WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)\n ))=False))\n UNION ALL\n SELECT t1.Name, t1.ID, t1.Department, 'Item found in \"Active Directory\" but not in \"Dump\"' AS [Found]\n FROM [Active Directory$B4:E20] As t1\n WHERE (((Exists (SELECT NULL\n FROM [Dump] As t2\n WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)\n ))=False))\n</code></pre>\n</blockquote>\n\n<p>Now that I had the SQL working, I replaced the messages and created a single <code>Select</code> statement that I could modify to handle both selecting record in Dump and not in Active Directory or selecting records in Active Directory that are not in Dump.</p>\n\n<blockquote>\n<pre><code>SELECT t1.ID, t1.Name, t1.Department, \"Message\" AS [Found]\nFROM [Dump] As t1\nWHERE (((Exists (SELECT NULL\n FROM [Active Directory] As t2\n WHERE (t2.ID = t1.ID) AND (t2.Name = t1.Name) AND (t2.Department = t1.Department)\n))=False));\n</code></pre>\n</blockquote>\n\n<h2>Sub FindUnmatchedRowsCopyFromRecordset()</h2>\n\n<p>Create a recordset and use <code>Range.CopyFromRecordset</code> to transfer the records.</p>\n\n<p>Sample SQl:</p>\n\n<blockquote>\n<pre><code>SELECT t1.Name, t1.ID, t1.Department, 'Item found in \"Dump\" but not in \"Active Directory\"' AS [Found]\nFROM [Dump$B4:E23] As t1\nWHERE (((Exists (SELECT NULL\n FROM [Active Directory$B4:E20] As t2\n WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)\n))=False))\nUNION ALL\nSELECT t1.Name, t1.ID, t1.Department, 'Item found in \"Active Directory\" but not in \"Dump\"' AS [Found]\nFROM [Active Directory$B4:E20] As t1\nWHERE (((Exists (SELECT NULL\n FROM [Dump$B4:E23] As t2\n WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)\n))=False))\n</code></pre>\n</blockquote>\n\n<h2>Sub FindUnmatchedRowsAppend()</h2>\n\n<p>This is a slightly more complicated technique that appends the records directly to the Output tab.</p>\n\n<p>Sample SQl:</p>\n\n<blockquote>\n<pre><code>INSERT INTO [Output$B4:E4] SELECT t3.* FROM (SELECT t1.Name, t1.ID, t1.Department, 'Item found in \"Dump\" but not in \"Active Directory\"' AS [Found]\nFROM [Dump$B4:E23] As t1\nWHERE (((Exists (SELECT NULL\n FROM [Active Directory$B4:E20] As t2\n WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)\n))=False))\nUNION ALL\nSELECT t1.Name, t1.ID, t1.Department, 'Item found in \"Active Directory\" but not in \"Dump\"' AS [Found]\nFROM [Active Directory$B4:E20] As t1\nWHERE (((Exists (SELECT NULL\n FROM [Dump$B4:E23] As t2\n WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)\n))=False))) as t3\n</code></pre>\n</blockquote>\n\n<h2>Code</h2>\n\n<pre><code>Option Explicit\n\nSub FindUnmatchedRowsAppend()\n Dim conn As Object\n Set conn = getThisWorkbookConnection\n conn.Open\n\n DeleteOutputResults\n Dim OutputDef As String\n OutputDef = getTableDefinition(wsOutput)\n\n Dim SQL As String\n SQL = \"INSERT INTO \" &amp; OutputDef &amp; \" SELECT t3.* FROM (\" &amp; getOutputResultQuery &amp; \") as t3\"\n\n conn.Execute SQL\n conn.Close\nEnd Sub\n\nPublic Sub FindUnmatchedRowsCopyFromRecordset()\n Dim conn As Object\n Set conn = getThisWorkbookConnection\n conn.Open\n Dim SQL As String\n SQL = getOutputResultQuery\n\n Dim rs As Object\n Set rs = conn.Execute(SQL)\n\n DeleteOutputResults\n wsOutput.Range(\"B5\").CopyFromRecordset rs\n\n conn.Close\n\nEnd Sub\n\nPrivate Function getOutputResultQuery() As String\n Dim ActiveDirectoryDef As String\n ActiveDirectoryDef = getTableDefinition(wsActiveDirectory)\n\n Dim DumpDef As String\n DumpDef = getTableDefinition(wsDump)\n\n Const BaseSQl As String = \"SELECT t1.Name, t1.ID, t1.Department, '@Message' AS [Found]\" &amp; vbNewLine &amp; _\n \"FROM [xlTable1] As t1\" &amp; vbNewLine &amp; _\n \"WHERE (((Exists (SELECT NULL\" &amp; vbNewLine &amp; _\n \" FROM [xlTable2] As t2\" &amp; vbNewLine &amp; _\n \" WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)\" &amp; vbNewLine &amp; _\n \"))=False))\"\n\n Dim SelectDump As String\n SelectDump = Replace(BaseSQl, \"[xlTable1]\", DumpDef)\n SelectDump = Replace(SelectDump, \"[xlTable2]\", ActiveDirectoryDef)\n SelectDump = Replace(SelectDump, \"@Message\", \"Item found in \"\"Dump\"\" but not in \"\"Active Directory\"\"\")\n\n Dim SelectAD As String\n SelectAD = Replace(BaseSQl, \"[xlTable1]\", ActiveDirectoryDef)\n SelectAD = Replace(SelectAD, \"[xlTable2]\", DumpDef)\n SelectAD = Replace(SelectAD, \"@Message\", \"Item found in \"\"Active Directory\"\" but not in \"\"Dump\"\"\")\n\n Dim SQL As String\n SQL = SelectDump &amp; vbNewLine &amp; \"UNION ALL\" &amp; vbNewLine &amp; SelectAD\n\n getOutputResultQuery = SQL\nEnd Function\n\nPrivate Sub DeleteOutputResults()\n Dim Target As Range\n With wsOutput\n Set Target = .Range(\"B4:E4\", .Cells(.Rows.Count, \"B\").End(xlUp))\n Target.Offset(1).ClearContents\n End With\nEnd Sub\n\nPrivate Function getTableDefinition(ws As Worksheet) As String\n Dim Target As Range\n Select Case ws.Name\n Case wsActiveDirectory.Name, wsDump.Name\n With ws\n Set Target = .Range(\"B4:E4\", .Cells(.Rows.Count, \"B\").End(xlUp))\n End With\n If ws Is wsActiveDirectory Then\n Rem Remove Summary Row\n Set Target = Target.Resize(Target.Rows.Count - 1)\n End If\n Case wsOutput.Name\n With ws\n Set Target = .Range(\"B4:E4\", .Cells(.Rows.Count, \"B\").End(xlUp))\n End With\n End Select\n\n getTableDefinition = getTableDefinitionFromRange(Target)\nEnd Function\n\nPrivate Function getThisWorkbookConnection() As Object\n Dim conn As Object\n Set conn = CreateObject(\"ADODB.Connection\")\n With conn\n .Provider = \"Microsoft.ACE.OLEDB.12.0\"\n .ConnectionString = \"Data Source=\" &amp; ThisWorkbook.FullName &amp; \";\" &amp; _\n \"Extended Properties=\"\"Excel 12.0 Xml;HDR=YES\"\";\"\n End With\n\n Set getThisWorkbookConnection = conn\nEnd Function\n\nPrivate Function getTableDefinitionFromRange(Target As Range) As String\n Dim SheetName As String\n SheetName = Target.Parent.Name\n Dim Address As String\n Address = Target.Address(RowAbsolute:=False, ColumnAbsolute:=False)\n getTableDefinitionFromRange = \"[\" &amp; SheetName &amp; \"$\" &amp; Address &amp; \"]\"\nEnd Function\n</code></pre>\n\n<h2>Download Link</h2>\n\n<p><a href=\"https://drive.google.com/open?id=1BsEQUp6PpjdX3whzu9bMajzdboj5WAry\" rel=\"nofollow noreferrer\">ADDump.xlsm</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T22:00:55.903", "Id": "233089", "ParentId": "233014", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T18:24:54.647", "Id": "233014", "Score": "1", "Tags": [ "performance", "array", "vba", "excel" ], "Title": "Comparing information to a directory of active enployees" }
233014
<p>I need to be able to cancel a long running query programmatically through our application. The code below will kick off a long running query and give control back to the main thread. At any arbitrary time, a user could choose to cancel the query. It both cancels the Task as well as cancels the query in SQL Server. I can check the status of the query in SQL Server with <code>select * from sys.query_store_runtime_stats</code> to verify that the query was in fact aborted. This is important as I need to make sure it's not just canceled in the app but in the database as well.</p> <p>The code below does this, but I'm hung up on the line where I <code>Register</code> the <code>cmd.Cancel</code> method with the <code>cancellationToken</code>, <code>cancellationToken.Register(cmd.Cancel);</code> Is there a potential issue since I'm referencing a variable created inside the scope of the Task.Run from the Main method(outside the <code>Task.Run</code> scope)?</p> <p>Also, I'm including the <code>cmd.Cancel</code> bit so that the SQL query actually gets cancelled and not just the task that kicked it off. Is there a better way to ensure that the long running SQL query currently being executed in the database is aborted? (again, the code below does this, just wondering if there is a better solution for cancelling a SQL query from the c# code that initiated the SQL query)</p> <p>I'm using .NET Core 3.1 preview 3 and SQL Server 2017 with the code posted below.</p> <pre><code>using Microsoft.Data.SqlClient; using System; using System.Threading; using System.Threading.Tasks; public class Program { public static void Main(string[] args) { var tokenSource = new CancellationTokenSource(); var cancellationToken = tokenSource.Token; Task.Run(async () =&gt; { await using var cn = new SqlConnection(CONNECTION_STRING); await using var cmd = new SqlCommand(LONG_RUNNING_SQL, cn); cancellationToken.Register(cmd.Cancel); // is this bad?? await cn.OpenAsync(cancellationToken); await using var reader = await cmd.ExecuteReaderAsync(cancellationToken); while (await reader.ReadAsync()) { } }, cancellationToken); Console.WriteLine("Press z+&lt;Enter&gt; to Stop"); while (true) { if (Console.Read() == 'z') { tokenSource.Cancel(); break; } } } private const string CONNECTION_STRING = "server=.;database=scratch;trusted_connection=true;"; private const string LONG_RUNNING_SQL = @" Declare @start bigint, @end bigint Select @start=1, @end=999999 ;With NumberSequence( Number ) as ( Select @start as Number union all Select Number + 1 from NumberSequence where Number &lt; @end ) Select * From NumberSequence Option (MaxRecursion 0) "; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T19:21:30.347", "Id": "455309", "Score": "2", "body": "Hello Chris, could you give us more details regarding your code?" } ]
[ { "body": "<p><strong>1) You can listen for requests for your application to close without making your own loop</strong>, and without having to push the logic of your application into another task</p>\n\n<pre><code>var cts = new CancellationTokenSource();\nAppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) =&gt; cts.Cancel();\nConsole.CancelKeyPress += (sender, eventArgs) =&gt; { cts.Cancel(); eventArgs.Cancel = true; };\n</code></pre>\n\n<p>So you don't need <code>Task.Run</code> anymore. This is also a better, more consistent check for closing that is better implemented than anything you can hand roll in a main method. </p>\n\n<p>(fyi. Unless you choose to leak these (and know what that means) you'll need to dispose cts and unregistered the handlers)</p>\n\n<p><strong>2) I almost certain passing a cancellation token to ExecuteReaderAsync is sufficient to cancel the query</strong>. You can verify this, but I think that cmd.Cancel for for people using ExecuteReader (non-async), which doesn't have a cancellationtoken.</p>\n\n<p><strong>3) Some other comments.</strong> It looks like you're not actually reading anything, is this code incomplete? A simple while loop is also probably not a great event loop (eg a delay would be good) but you don't need to worry about that anyway.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-11T12:41:26.583", "Id": "233866", "ParentId": "233016", "Score": "0" } }, { "body": "<blockquote>\n<p>It both cancels the <code>Task</code> as well as cancels the query in SQL Server. I can check the status of the query in SQL Server with <code>select * from sys.query_store_runtime_stats</code> to verify that the query was in fact aborted. This is important as I need to make sure it's not just canceled in the app but in the database as well.</p>\n</blockquote>\n<p>Baaaack up a few steps. Your strategy to rely on proof of query completion by looking in a secondary table seems strange to me. If your long-running query were an <code>update</code>, <code>insert</code> etc., you would want to consider</p>\n<ul>\n<li>Running your query in a transaction that does not have any kind of auto-commit enabled</li>\n<li>Only committing at the end, once you're sure that there will be no desire for cancellation</li>\n<li>If cancellation occurs before the <code>commit</code>, then you can be sure that the query was cancelled with no effect on the database</li>\n</ul>\n<p>But that's not required, because your long-running query is only a <code>select</code>. Is there a specific reason that you don't trust <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.cancel?view=dotnet-plat-ext-5.0&amp;viewFallbackFrom=netcore-3.1\" rel=\"nofollow noreferrer\">Cancel</a> to do what it's designed to do? Doing the <code>query_store_runtime_stats</code> check manually as a part of development testing is fine, as long as you aren't baking it in programmatically.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T16:37:51.967", "Id": "254312", "ParentId": "233016", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T19:07:47.163", "Id": "233016", "Score": "2", "Tags": [ "c#", ".net", "sql-server", "async-await", "ado.net" ], "Title": "Cancel Long Running Query using Cancellation Token AND SqlCommand.Cancel()" }
233016
<p>I have a class method that is set up to make requests to an API and I'm having issues handling the possible errors that could arise by trying to communicate with that server. The idea is if an error were to pop up, then it would call on itself until either it no longer needs to (because it worked), or it reaches a limit I set up for it; in this case, I would want it to just simply raise an exception that would be caught somewhere else in the code. What I don't know is how to properly return the response if it crapped out the first time it made the call and had to call on itself from the <code>except</code> block.</p> <p>I'm not 100% clear if this actually gets the job done. Additionally, I dont know if this is the best way to do it. I know a possible suggestion is to make error handling more specific, given the <code>requests</code> library myriad exceptions, but I figured that any exception should just be handled by trying X amount of time and then quitting if it doesn't work.</p> <pre class="lang-py prettyprint-override"><code>def getRequest(self, endpoint, attempts): baseUrl = self.baseUrl url = baseUrl + endpoint if self.expirationT &lt;= datetime.datetime.now(): self.token, self.expirationT = self.auth(client_id, client_secret) else: pass try: response = requests.get(url, auth = BearerAuth(self.token)) response.raise_for_status() except: if attempts &lt; 20: time.sleep(3) response = self.getRequest(endpoint, attempts + 1) return response else: raise Exception else: return response </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T21:18:31.207", "Id": "455327", "Score": "0", "body": "could you illustrate how to do it with a loop?" } ]
[ { "body": "<blockquote>\n <p>I know a possible suggestion is to make error handling more specific, given the requests library myriad exceptions, but I figured that any exception should just be handled by trying X amount of time and then quitting if it doesn't work.</p>\n</blockquote>\n\n<p>I disagree here. Not just <em>any</em> exception should be handled. It's possible to have typo'd a bug into your code inside the <code>try</code>, and you definitely don't want <code>try</code> masking a bug.</p>\n\n<p>If you check the source (or documentation), you'll see that the <code>requests</code> exceptions all seem to inherit from <code>RequestException</code>. If you really want to handle every possible request exception the same, I would catch the base class <code>RequestException</code> instead. I still don't think this is a good idea though without doing any logging. There may very well be a <code>RequestException</code> that gets thrown at some point which indicates that you accidentally gave the request bad data, not that there was a problem with the request being carried out using good data. I'd check the docs for the methods used and figure out what exact exceptions you want to retry on.</p>\n\n<hr>\n\n<p>This also doesn't need to be recursion. In this case, nothing bad will likely happen because you have a limit of 20 retries, which isn't enough to exhaust the stack any sane case. If you ever increase that limit up to 1000 though, you may run into real problems.</p>\n\n<p>I think this could be done pretty easily using a <code>while True</code> loop. The first two lines of the function seem to be essentially constants, so they don't need to be recomputed every time. Everything under those lines though can be stuck in a loop.</p>\n\n<pre><code>def getRequest(self, endpoint, max_attempts=20, retry_delay=3):\n baseUrl = self.baseUrl\n url = baseUrl + endpoint\n\n attempts = 0\n while True:\n if self.expirationT &lt;= datetime.datetime.now():\n self.token, self.expirationT = self.auth(client_id, client_secret)\n\n try:\n response = requests.get(url, auth=BearerAuth(self.token))\n response.raise_for_status()\n return response\n\n except requests.RequestException as e:\n attempts += 1\n\n if attempts &lt; max_attempts:\n time.sleep(retry_delay)\n\n else:\n raise RuntimeError(\"Max number of retires met.\")\n\n # Or to preserve in the trace the original problem that caused the error:\n # raise RuntimeError(\"Max number of retires met.\") from e\n</code></pre>\n\n<p>Things to note:</p>\n\n<ul>\n<li><p>To retry now, instead of manually recursing, I'm just letting control fall out of the <code>except</code> so that the <code>while</code> can restart again.</p></li>\n<li><p>Instead of <code>attempts</code> being a parameter, I just made it a local variable which is incremented inside of the <code>except</code>.</p></li>\n<li><p>I'm throwing a more specialized exception with an informative error message. Throwing the generic <code>Exception</code> makes life more difficult for the users of your code. Ideally, they should be able to pick and choose what exceptions they handle and when. Throwing <code>Exception</code> though forces them to catch your errors. <code>RuntimeError</code> isn't really the best exception here, but I couldn't think of a good built-in one for this purpose. You may want to make a custom exception for this case:</p>\n\n<pre><code>class TooManyRetries(Exception):\n pass\n\n. . .\n\nraise TooManyRetries(\"Max number of retires met.\")\n</code></pre></li>\n<li><p>I got rid of the <code>else: pass</code>. That isn't necessary.</p></li>\n<li><p>You had two \"magic numbers\": <code>20</code> and <code>3</code> to mean the max number of attempts and the retry delay. I don't think it's a good idea to have those hard coded though. What if you want to change either at some point? You'd have to edit the code. I made them parameters of the function, defaulting to the values that you had. If you don't specify them, the behavior will be as you had before, but now they can be easily changed as needed.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T06:04:55.140", "Id": "455359", "Score": "0", "body": "I know OP had it the same. But maybe it would make more sense if number of attempts started at max And continually decrease it to zero. And have `while attempts > 0`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T09:09:07.233", "Id": "455515", "Score": "0", "body": "You should use `except requests.RequestException as err:raise RuntimeError from err`, so that the traceback shows the original problem as well. Either that or re-raise the original." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T17:05:47.897", "Id": "455587", "Score": "0", "body": "@Gloweye Whoops, you're right. I'll update that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T22:30:37.453", "Id": "233026", "ParentId": "233020", "Score": "3" } }, { "body": "<p>I agree with <a href=\"https://codereview.stackexchange.com/a/233026/98493\">the other answer</a> by <a href=\"https://codereview.stackexchange.com/users/46840/carcigenicate\">@Carcigenicate</a>. Putting this into a loop instead of using a recursive design makes it a lot easier to understand. However, the explicit <code>while</code> loop can be simplified even further by using a <code>for</code> loop instead. This makes it even more readable, IMO.</p>\n\n<pre><code>def get_request(self, end_point, max_attempts=20, retry_delay=3):\n \"\"\"Get the page at `self.base_url + end_point`.\n If the request fails due to a request error, retry up to `max_attempts` times,\n with a delay of `retry_delay` seconds.\n \"\"\"\n url = self.base_url + endpoint\n for _ in range(max_attempts):\n if self.expiration_time &lt;= datetime.datetime.now():\n self.token, self.expiration_time = self.auth(client_id, client_secret)\n try:\n response = requests.get(url, auth=BearerAuth(self.token))\n response.raise_for_status()\n return response\n except requests.RequestException:\n time.sleep(retry_delay)\n raise RuntimeError(f\"Maximum number of retries ({max_attempts}) reached.\")\n</code></pre>\n\n<p>In addition, Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using <code>lower_case</code> for functions and variables and <code>PascalCase</code> only for classes.</p>\n\n<p>You should also add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> to document your functions, as I have done for this method.</p>\n\n<p>You might also want to add some <a href=\"https://docs.python.org/3/library/logging.html\" rel=\"nofollow noreferrer\">logging</a> to this, so you can debug it if necessary:</p>\n\n<pre><code>import logging\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(\"Requests\")\n\n...\n\ndef get_request(self, end_point, max_attempts=20, retry_delay=3):\n \"\"\"Get the page at `self.base_url + end_point`.\n If the request fails due to a request error, retry up to `max_attempts` times,\n with a delay of `retry_delay` seconds.\n \"\"\"\n url = self.base_url + endpoint\n for attempt in range(max_attempts):\n if self.expiration_time &lt;= datetime.datetime.now():\n self.token, self.expiration_time = self.auth(client_id, client_secret)\n try:\n response = requests.get(url, auth=BearerAuth(self.token))\n response.raise_for_status()\n return response\n except requests.RequestException:\n logger.exception(\"Attempt %s out of %s failed for URL %s\",\n attempt + 1, max_attempts, url)\n time.sleep(retry_delay)\n raise RuntimeError(f\"Maximum number of retries ({max_attempts}) reached.\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:24:04.057", "Id": "233066", "ParentId": "233020", "Score": "3" } }, { "body": "<p>The entire question essentially spins around and calls for a good <em>\"Retry/MaxRetry nextwork requests\"</em> strategy.</p>\n\n<p>And just for this we have a flexible and reach <em>Retry</em> configuration - <a href=\"https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#urllib3.util.Retry\" rel=\"nofollow noreferrer\"><code>urllib3.util.Retry</code></a>, which in combination with well-known <a href=\"https://2.python-requests.org/en/master/\" rel=\"nofollow noreferrer\"><code>requests</code></a> lib provides granular control over the conditions under which we retry a request.</p>\n\n<p>Among a bunch of options it provides:</p>\n\n<blockquote>\n <p>class <strong><em>urllib3.util.Retry</em></strong>(total=10, connect=None, read=None,\n redirect=None, status=None, method_whitelist=frozenset(['HEAD',\n 'TRACE', 'GET', 'PUT', 'OPTIONS', 'DELETE']), status_forcelist=None,\n backoff_factor=0, raise_on_redirect=True, raise_on_status=True,\n history=None, respect_retry_after_header=True,\n remove_headers_on_redirect=frozenset(['Authorization']))</p>\n</blockquote>\n\n<p>I'll mention just some crucial ones:</p>\n\n<ul>\n<li><code>total</code>. Total number of retries to allow.</li>\n<li><code>status_forcelist(iterable)</code>. A set of integer <em>HTTP</em> status codes that we should force a retry on. <br>In my sample scheme below I used all error HTTP codes to be considered here. But you can restrict that iterable by passing the argument with selected codes like <code>status_forcelist=(500, 502, 503, 504)</code>.</li>\n<li><p><code>backoff_factor</code>. A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a second try without a delay). <code>urllib3</code> will sleep for:</p>\n\n<pre><code>{backoff factor} * (2 ** ({number of total retries} - 1))\n</code></pre>\n\n<p>seconds. If the backoff_factor is <code>0.1</code>, then <code>sleep()</code> will sleep for <code>[0.0s, 0.2s, 0.4s, …]</code> between retries. It will never be longer than <code>Retry.BACKOFF_MAX</code>. <br>This would be a more \"thought-out\" alternative to a constant delay.</p></li>\n</ul>\n\n<hr>\n\n<p>To establish the above Retry/MaxRetry strategy we run through the following steps:</p>\n\n<ul>\n<li>creating instance of <code>Retry</code> component with the needed options</li>\n<li>creating <a href=\"https://2.python-requests.org//en/latest/api/#requests.adapters.HTTPAdapter\" rel=\"nofollow noreferrer\"><code>requests.adapters.HTTPAdapter</code></a> adapter instance with passing in created <code>Retry</code> component as its <code>max_retries</code> parameter: <code>HTTPAdapter(max_retries=self._retry)</code></li>\n<li>creating requests session with <code>self.session = requests.Session()</code> and mounting it to a base url (<code>self.session.mount(self.base_url, self._adapter)</code>). You can mount session to multiple base urls/prefixes.</li>\n</ul>\n\n<p>Since you posted an instance method <code>def getRequest(self, ...</code> I assume that that's the context of some API client/wrapper.\nBelow is a generic sample scheme of using the described strategy. So you can easily adjust/extend your API client class appropriately (and get rid of loops or recursion in \"Retry\" intention).</p>\n\n<pre><code>import requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.exceptions import RetryError\nfrom urllib3.exceptions import MaxRetryError\nfrom urllib3.util.retry import Retry\nimport datetime\n\n\n# .... your constants/variables\n\nclass MyAPIClient:\n ERROR_CODES = tuple(code for code in requests.status_codes._codes if code &gt;= 400)\n\n def __init__(self, base_url, max_retries=5, backoff_factor=0.2):\n self.base_url = base_url\n self._max_retries = max_retries\n self._retry = Retry(total=max_retries,\n backoff_factor=backoff_factor,\n status_forcelist=MyAPIClient.ERROR_CODES)\n self._adapter = HTTPAdapter(max_retries=self._retry)\n\n self.session = requests.Session()\n self.session.mount(self.base_url, self._adapter)\n\n def get_request(self, endpoint):\n url = self.base_url + endpoint\n\n if self.expirationT &lt;= datetime.datetime.now():\n self.token, self.expirationT = self.auth(client_id, client_secret)\n\n try:\n response = self.session.get(url, auth=BearerAuth(self.token))\n except (MaxRetryError, RetryError) as ex:\n # optional actions/logging here. Otherwise - try/except can be just eliminated\n raise\n return response\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T21:40:56.990", "Id": "233088", "ParentId": "233020", "Score": "2" } } ]
{ "AcceptedAnswerId": "233026", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T21:14:18.150", "Id": "233020", "Score": "3", "Tags": [ "python", "python-3.x", "error-handling" ], "Title": "Recursive Error Handling in Python with a limited amount of tries" }
233020
<p>I am learning Go by writing <a href="https://github.com/Shpota/go-angular/blob/master/server/app.go" rel="noreferrer">a simple CRUD REST API</a> using gotilla/mux and Gorm. </p> <p>I would like to get some feedback on <a href="https://github.com/Shpota/go-angular" rel="noreferrer">the application code</a> and on unit tests in particular. Please suggest me what to improve, what to do better, what not to do and generally tell me what comes to your mind.</p> <pre><code>func TestGetAllStudents(t *testing.T) { app := initApp() st := student{ID: "id-1", Age: 20, Name: "John Doe"} app.db.Save(st) req, _ := http.NewRequest("GET", "/students", nil) r := httptest.NewRecorder() handler := http.HandlerFunc(app.getAllStudents) handler.ServeHTTP(r, req) checkStatusCode(r.Code, http.StatusOK, t) checkContentType(r, t) checkBody(r.Body, st, t) } func TestAddStudent(t *testing.T) { app := initApp() var rqBody = toReader(`{"name":"John Doe", "age":20}`) req, _ := http.NewRequest("POST", "/students", rqBody) r := httptest.NewRecorder() handler := http.HandlerFunc(app.addStudent) handler.ServeHTTP(r, req) checkStatusCode(r.Code, http.StatusCreated, t) checkContentType(r, t) checkProperties(firstStudent(app), t) } func TestUpdateStudent(t *testing.T) { app := initApp() app.db.Save(student{ID: "id-1", Age: 25, Name: "Peter Doe"}) var rqBody = toReader(`{"name":"John Doe", "age":20}`) req, _ := http.NewRequest("PUT", "/students/id", rqBody) req = mux.SetURLVars(req, map[string]string{"id": "id-1"}) r := httptest.NewRecorder() handler := http.HandlerFunc(app.updateStudent) handler.ServeHTTP(r, req) checkStatusCode(r.Code, http.StatusOK, t) checkContentType(r, t) checkProperties(firstStudent(app), t) } func TestDeleteStudent(t *testing.T) { app := initApp() app.db.Save(student{ID: "id-1", Age: 20, Name: "John Doe"}) req, _ := http.NewRequest("DELETE", "/students/id", nil) req = mux.SetURLVars(req, map[string]string{"id": "id-1"}) r := httptest.NewRecorder() handler := http.HandlerFunc(app.deleteStudent) handler.ServeHTTP(r, req) checkStatusCode(r.Code, http.StatusOK, t) checkContentType(r, t) checkDbIsEmpty(app.db, t) } func initApp() App { db, _ := gorm.Open("sqlite3", ":memory:") db.AutoMigrate(&amp;student{}) return App{db: db} } func firstStudent(app App) student { var all []student app.db.Find(&amp;all) return all[0] } func toReader(content string) io.Reader { return bytes.NewBuffer([]byte(content)) } func checkStatusCode(code int, want int, t *testing.T) { if code != want { t.Errorf("Wrong status code: got %v want %v", code, want) } } func checkContentType(r *httptest.ResponseRecorder, t *testing.T) { ct := r.Header().Get("Content-Type") if ct != "application/json" { t.Errorf("Wrong Content Type: got %v want application/json", ct) } } func checkProperties(st student, t *testing.T) { if st.Name != "John Doe" { t.Errorf("Name should match: got %v want %v", st.Name, "Peter Doe") } if st.Age != 20 { t.Errorf("Age should match: got %v want %v", st.Age, 20) } } func checkBody(body *bytes.Buffer, st student, t *testing.T) { var students []student _ = json.Unmarshal(body.Bytes(), &amp;students) if len(students) != 1 { t.Errorf("Wrong lenght: got %v want 1", len(students)) } if students[0] != st { t.Errorf("Wrong body: got %v want %v", students[0], st) } } func checkDbIsEmpty(db *gorm.DB, t *testing.T) { var students []student db.Find(&amp;students) if len(students) != 0 { t.Errorf("Student has not been deleted") } } </code></pre> <p>Here are the concerns I already have (not sure, how relevant they are):</p> <ul> <li>I didn't manage to mock DB, that's why I am using an in-memory DB</li> <li>The verification code was too verbose, I extracted it into separate functions. Is it something you would do?</li> <li>I didn't manage to test negative scenarios (as a result of the first concern).</li> <li>I don't like having to call <code>mux.SetURLVars</code> to inject a path variable. How to do this better?</li> <li>I didn't manage to test the code that initializes Mux routers</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T13:52:47.153", "Id": "455891", "Score": "1", "body": "I'll spend some time reviewing this, but there's a lot to say about this, for sure. I'm leaving this comment here to find this question reasonably fast tonight once I'm done with work" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T09:01:00.730", "Id": "455997", "Score": "0", "body": "@EliasVanOotegem I would love to see your feedback :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:30:30.193", "Id": "456893", "Score": "0", "body": "I didn't spot your list of concerns when I typed up the first part of my review. I'm assuming my answer addresses your first and third concerns (mocking DB). The concern regarding `mux.SetURLVars` probably can be mitigated through the use of `httptest`. As for initialising the mux routers: that's the job of the mux maintainers. Their unit tests should cover that, you don't have to write tests ensuring that a third party package works as documented. I'll add this to my answer, to keep track of what I've addressed and what I haven't yet" } ]
[ { "body": "<p>Here are some notes I made while reading your code.</p>\n\n<p>For a real-world code review, code should be correct, maintainable, reasonably efficient, and, most importantly, readable.</p>\n\n<p>Writing code is a process of stepwise refinement.</p>\n\n<p>Start by looking at two similar methods.</p>\n\n<p><code>go-angular/server/app.go</code>:</p>\n\n<pre><code>func (a *App) addStudent(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n s := student{}\n err := json.NewDecoder(r.Body).Decode(&amp;s)\n s.ID = uuid.New().String()\n if err != nil {\n sendErr(w, http.StatusBadRequest, err.Error())\n } else {\n err = a.db.Save(&amp;s).Error\n if err != nil {\n sendErr(w, http.StatusInternalServerError, err.Error())\n } else {\n w.WriteHeader(http.StatusCreated)\n }\n }\n}\n\nfunc (a *App) updateStudent(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n s := student{}\n err := json.NewDecoder(r.Body).Decode(&amp;s)\n if err != nil {\n sendErr(w, http.StatusBadRequest, err.Error())\n } else {\n s.ID = mux.Vars(r)[\"id\"]\n err = a.db.Save(&amp;s).Error\n if err != nil {\n sendErr(w, http.StatusInternalServerError, err.Error())\n }\n }\n}\n</code></pre>\n\n<p>Write them in more readable form.</p>\n\n<pre><code>func (a *App) addStudent(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n var s student\n err := json.NewDecoder(r.Body).Decode(&amp;s)\n if err != nil {\n sendErr(w, http.StatusBadRequest, err.Error())\n return\n }\n s.ID = uuid.New().String()\n err = a.db.Save(&amp;s).Error\n if err != nil {\n sendErr(w, http.StatusInternalServerError, err.Error())\n return\n }\n w.WriteHeader(http.StatusCreated)\n}\n\nfunc (a *App) updateStudent(w http.ResponseWriter, r *http.Request) {\n w.Header().Set(\"Content-Type\", \"application/json\")\n var s student\n err := json.NewDecoder(r.Body).Decode(&amp;s)\n if err != nil {\n sendErr(w, http.StatusBadRequest, err.Error())\n return\n }\n s.ID = mux.Vars(r)[\"id\"]\n err = a.db.Save(&amp;s).Error\n if err != nil {\n sendErr(w, http.StatusInternalServerError, err.Error())\n return\n }\n w.WriteHeader(http.StatusOK)\n}\n</code></pre>\n\n<p>Write more readable code.</p>\n\n<blockquote>\n <p><a href=\"https://github.com/golang/go/wiki/CodeReviewComments#indent-error-flow\" rel=\"nofollow noreferrer\">Go Code Review Comments: Indent Error\n Flow</a>.</p>\n \n <p>Try to keep the normal code path at a minimal indentation, and indent\n the error handling, dealing with it first. This improves the\n readability of the code by permitting visually scanning the normal\n path quickly.</p>\n</blockquote>\n\n<p>Use <code>var</code> to declare variables that are decoding targets. They have zero value(s).</p>\n\n<pre><code>var s student\n</code></pre>\n\n<p>Don't do things before they are necessary.</p>\n\n<pre><code>s.ID = uuid.New().String()\n</code></pre>\n\n<p>The <code>s.ID</code> value is discarded in <code>addStudent</code> if there is an error in decoding. Wait until it is needed, as you did in <code>updateStudent</code>.</p>\n\n<p>In <code>addStudent</code> you returned a status.</p>\n\n<pre><code>w.WriteHeader(http.StatusCreated)\n</code></pre>\n\n<p>Return a status in <code>updateStudent</code>.</p>\n\n<pre><code>w.WriteHeader(http.StatusOK)\n</code></pre>\n\n<p>And so on.</p>\n\n<p>Make sure that your <code>app.go</code> code is good before worrying about testing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T08:13:42.707", "Id": "455369", "Score": "0", "body": "Thank you for the review (+1). I will apply your suggestions soon. I don't set status to `StatusOK` because the framework does it implicitly (the status will be OK even if it is not specified). As for tests, it took me some time to figure out how to restructure the code to make it actually \"testable\" (see [this PR](https://github.com/Shpota/go-angular/pull/5/files)). I would say the easier it is to test the code the better the code is. I would appreciate if you also took a look on the tests." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T00:51:12.697", "Id": "233033", "ParentId": "233021", "Score": "4" } }, { "body": "<p>You can simplify your build and allow for easier <strong>integration tests*</strong> with a <code>docker-compose.yml</code> file. </p>\n\n<pre><code>version: \"3.7\"\nservices:\n webapp:\n build: .\n ports: \n - 8080:8080\n depends_on:\n - db\n environment:\n - DB_PASS='your-strong-pass'\n db:\n image: postgres:11.5\n environment:\n - POSTGRES_USER=go\n - POSTGRES_PASSWORD=your-strong-pass\n - POSTGRES_DB=go\n</code></pre>\n\n<p>Just add it to the root of your application and run the command <code>docker-compose up --build</code>.<br>\n <em>To use it for tests, you can have a different <code>docker-compose</code> file with a command to run integration tests.</em></p>\n\n<ul>\n<li>Note that integration tests are not unit tests.<br>\nWith unit testing, you are testing functions in the purest form you can achieve.<br>\nWith integration tests you are running your program while mocking the outside world (databases, file systems, ...) and check if the output of your program (or the exposed APIs) is as you expect.<br>\n<strong>Both kinds of tests are important</strong> as they test different things.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T00:19:35.597", "Id": "456704", "Score": "1", "body": "If the error message contains `\"}`, you are screwed. The sensible way to produce JSON is `json.Marshal`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T07:34:36.587", "Id": "456713", "Score": "0", "body": "Thank you (+1). It looks better with docker-compose, I'll rework it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T08:45:35.683", "Id": "456714", "Score": "0", "body": "@RolandIllig didn't think about it. I removed this suggestion from my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:44:54.320", "Id": "456895", "Score": "1", "body": "Just to point an important takeway from this answer is, and maybe @Eyal could place some more emphasis on this, is that you're running *integration tests*, rather than *unit tests*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T16:31:01.383", "Id": "456901", "Score": "1", "body": "@EliasVanOotegem per your suggestion, I updated my answer with an emphasis and explanation about unit and integration tests." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T23:16:07.900", "Id": "233611", "ParentId": "233021", "Score": "2" } }, { "body": "<p>OK, so a bit later than I expected, but here's some comments I have. I'll try to address the concerns you list to a reasonable degree:</p>\n\n<ul>\n<li>I didn't manage to mock DB, that's why I am using an in-memory DB</li>\n</ul>\n\n<p>This should be covered by the big section titled <em>\"This is not a unit test\"</em></p>\n\n<ul>\n<li>The verification code was too verbose, I extracted it into separate functions. Is it something you would do?</li>\n</ul>\n\n<p>I've also hinted at creating a package for this, so yes, this is most certainly something I'd separate out. Having said that, you might want to do some googling to find packages that generate validation code. A quick search came up with <a href=\"https://github.com/thedevsaddam/govalidator\" rel=\"nofollow noreferrer\">this <code>govalidator</code> package</a>. I've not used it myself, so I can't vouch for it, but there's plenty of packages out there that will allow you to write something like this:</p>\n\n<pre><code>type CreateUserRequest struct {\n Name string `validate:type=\"string\";min_len=5;regex=\"[A-Za-Z ]+\"`\n Age int `validate:min=\"18\";max=\"120\"`\n}\n</code></pre>\n\n<p>The syntax and example validation is completely made-up, so you'll have to see for yourself what you want and what makes sense.</p>\n\n<ul>\n<li>I didn't manage to test negative scenarios (as a result of the first concern).</li>\n</ul>\n\n<p>Like you said, this ties in with your first concern, and my breakdown of that problem addresses this, too.</p>\n\n<ul>\n<li>I don't like having to call <code>mux.SetURLVars</code> to inject a path variable. How to do this better?</li>\n</ul>\n\n<p>The golang standard library provides you with the <code>net/http/httptest</code> package, which probably can help you out with this. This is something I've not discussed yet, but I'm likely to revisit this review with some more details on this.</p>\n\n<ul>\n<li>I didn't manage to test the code that initializes Mux routers</li>\n</ul>\n\n<p>As mentioned in the comment I left: you shouldn't unit-test external packages. You should choose a dependency based on functionality, maturity, community support, performance, etc... depending on your needs, the weight you give each to of these factors can vary. Generally speaking, <code>gorilla.Mux</code>is a widely used, mature, and battle tested package. You can rely on the router component being well tested. It's not the user's job of a package to unit-test a dependency. That's a bit like trying to write unit-tests covering golang's standard library functions. That's the job of the people maintaining those packages. If you can test that requests to a given route land you in the correct handler function (which you can), then you know the routes have been configured correctly.</p>\n\n<p>Anyway: here's the actual code-review:</p>\n\n<h2>This is not a unit test</h2>\n\n<p>What you have is not a unit test. Plain and simple. A unit test is a type of test where you test the logic inside a given package. You want to control the input entirely so you can see if you're getting the desired output. Your tests rely on stuff like the database to function. In a real unit test, all dependencies that aren't essential to the business logic inside the code you're testing (which should be all dependencies) should be mocked.</p>\n\n<p>Looking at the code itself, there's fairly little in the way of business logic to test, but assuming you'll build on what you have, you might want to change the structure of things somewhat.</p>\n\n<h3>Separate into packages</h3>\n\n<p>It's good practice to move all the direct DB interactions into its own package. That will allow you to test the more complex logic without needing to setup an in-memory database all the time, and test basic stuff with arbitrary data. Let's assume you want'a CAS (Check And Set) or Upsert type functionality at some point. Let's create a type that has the logic to validate/check student data, and can call on the DB to store/update the records:</p>\n\n<pre><code>package persistence\n\n// DB interface we need, the package USING the dependency declares the interface it needs\ntype DB interface {\n Save(*Student) error\n GetByID(id string) (*Student, error)\n Update(*Student) error // this could be handled by Save,but you'll see why I'm making the destinction\n}\n\n// Logger interface, this should be an application wide thing, and needn't be an interface per package, but I'm including it here for completeness\ntype Logger interface {\n Debug(... interface{})\n Info(... interface{})\n Warn(... interface{})\n Err(... interface{})\n Fatal(... interface{})\n}\n\n// CAS I'm bad at naming things, but you get the gist\ntype CAS struct {\n db DB\n log Logger\n}\n\nvar (\n // NameEmptyErr one of many predefined errors validation can return\n NameEmptyErr = errors.New(\"name for student missing\")\n IDAlreadySetErr = errors.New(\"new student record already has an ID, call Update/Upsert\")\n PersitenceErr = errors.New(\"failed to persist data\")\n)\n\n// New returns a new CAS validator, pass in dependencies here (DI)\nfunc New(log Logger, db DB) *CAS {\n return &amp;CAS{\n db: db,\n log: log,\n }\n}\n\n// CASStudent validates the student record, and if everything checks out, the record is stored\nfunc (c *CAS) CASStudent(student *Student) error {\n if student.Name == \"\" {\n return NameEmptyErr\n }\n // add all validation here\n if student.ID != \"\" {\n return IDAlreadySetErr\n }\n // validation complete, store. Let the db layer handle ID's\n // we're passing a pointer to the data, so the ID can be set on the object\n if err := c.db.Save(student); err != nil {\n c.log.Err(err)\n return PersistenceErr\n }\n return nil\n}\n</code></pre>\n\n<p>Great, now how does this help you get closer to mocking dependencies? Does this mean you have to manually create test types for all the interfaces you need to mock? Well actually, no. Thankfully, there's tools that can auto-generate all the mocks you need. If you update the interfaces, just running a single command will update the mocks to conform to the new interfaces. The best tool for this in my experience is <a href=\"https://github.com/golang/mock\" rel=\"nofollow noreferrer\">gomock and mockgen</a>. It's fantastically easy to use, just add a single line of comments above the interfaces you need mocking:</p>\n\n<pre><code>package persistence\n\n//go:generate go run github.com/golang/mock/mockgen -destination mocks/db_mock.go -package mocks github.com/your/repo/persistence DB\ntype DB interface{}\n\n//go:generate go run github.com/golang/mock/mockgen -destination mocks/logger_mock.go -package mocks github.com/your/repo/persistence Logger\ntype Logger interface{}\n</code></pre>\n\n<p>to generate the code, in your repo, simply run <code>go generate ./...</code>, and all mocks for all packages will be generated and you'll find the mocks for a given package under <code>path/to/package/mocks</code>. The mock package name will be <code>package mocks</code>.</p>\n\n<h3>Cool, let's write a unit test</h3>\n\n<p>So we have a package that takes care of validation, and uses mockable dependencies, let's set about writing a unit test for our new <code>persistence</code> package:</p>\n\n<pre><code>package persistence_test // yes, we're changing the package name\n\nimport (\n \"testing\"\n\n \"github.com/your/repo/persistence\" // import the package to test\n \"github.com/your/repo/persistence/mocks\" // import the mocks\n\n \"github.com/golang/mocks/gomock\" // you'll see why I'm using these\n \"github.com/stretchr/testify/assert\"\n)\n\ntype testCAS struct {\n *persistence.CAS // the type we're testing\n ctrl *gomock.Controller\n db *mocks.MockDB\n log *mocks.MockLogger\n}\n\n// this func sets up everything we need to run a test with mocks\nfunc getCAS(t *testing.T) testCas {\n ctrl := gomock.NewController(t)\n db := mocks.NewDBMock(ctrl)\n log := mocks.NewLoggerMock(ctrl)\n return testCas{\n CAS: persistence.New(log,db),\n ctrl: ctrl,\n db: db,\n log: log,\n }\n}\n\nfunc TestCASStudentSuccessSimple(t *testing.T) {\n cas := getCAS(t)\n defer cas.Finish()\n id := \"id set by mock\"\n student := &amp;persistence.Student{\n Name: \"this needs to be set\",\n }\n // if our code is correct, we're expecting exactly 1 call to db.Save\n // for this test we don't want it to return an error, so job done\n // the DB package is going to set the ID, so we'll set up the mock to do the same\n cas.db.EXPECT().Save(student).Times(1).Return(nil).Do(func(s *persitence.Student) {\n s.ID = id // set the id to the var above\n })\n // Now let's call the code we want to test:\n err := cas.CASStudent(student)\n assert.NoError(t, err) // ensure no errors were returned\n assert.Equal(t, id, student.ID) // the id should now be set\n}\n\n// Finish isn't required, but I add it for convenience, instead of writing foo.ctrl.Finish()\nfunc (c *testCas) Finish() {\n c.ctrl.Finish()\n}\n</code></pre>\n\n<p>Great! Now That's a unit test. The only actual code we're executing is found in the persistence package, and it's only testing the unit of code that validates the data, and passes it on for storage. The added benefit of this is that you don't have to rewrite a bunch of test should you decide to change the underlying storage solution to, say, a key-value store, or some other DB. The interfaces can remain unchanged, so you can swap out a package, safe in the knowledge that all code will still behave as expected as long as the interface they're expecting is implemented. If there is a bug, you'll just know the bug is found in the package you're replaced the old one with, and nowhere else.</p>\n\n<h3>Just for fun, let's try a more complex test:</h3>\n\n<pre><code>func TestCASComplex(t *testing.T) {\n cas := getCas(t)\n defer cas.Finish()\n // data contains the test-cases, expect contains the errors we may expect\n data := map[strign]*persistence.Student{\n \"noName\": {}, // no name set, we expect validation to fail\n \"idSet\": {\n Name: \"name is set\",\n ID: \"but so is ID\",\n },\n \"dbFail\": {\n Name: \"this is fine\",\n },\n }\n expect := map[string]error{\n \"noName\": persistence.NameEmptyErr,\n \"idSet\": persistence.IDAlreadySetErr,\n \"dbFail\": persistence.PersistenceErr,\n }\n // the first 2 calls won't call the DB/logger, only the last one will:\n dbErr := errors.New(\"db error\")\n // you can change gomock.Any() with the data[\"dbFail\"] value\n cas.db.EXPECT().Save(gomock.Any()).Times(1).Return(dbErr)\n cas.log.EXPECT().Err(dbErr).Times(1) // the error from the db should be logged\n for k, student := range data {\n expErr := expect[k] // get the error we're expecting\n optionalID := student.ID // get ID before the call\n err := cas.Save(student)\n assert.Error(t, err) // make sure an error is returned\n assert.Equal(t, expErr, err) // and check if it's the error we're expecting\n assert.Equal(t, optionalID, student.ID) // make sure the ID wasn't changed\n }\n}\n</code></pre>\n\n<p>So with these 2 example test functions, we're covering all possible code-paths in the <code>CASStudent</code> function:</p>\n\n<ul>\n<li>The student name is missing</li>\n<li>the student already has an ID</li>\n<li>the student data is valid and stored successfully</li>\n<li>The student data is valid, but the DB failed</li>\n</ul>\n\n<p>Neat!</p>\n\n<h3>Important note/rant on interfaces</h3>\n\n<p>A common thing to see people do, especially when they're coming from another language that is more, shall we say, <em>\"traditionally OO\"</em>, is to declare the interface for any given component/type in the package where the interface is implemented. In golang, the opposite approach is the way to go. A packackage handling DB interactions returns a \"raw\" type that can be passed to one or more types that depend on it. Each of these users might need different parts of the API this DB type exposes. If all of them use the same, big, interface, chances of tightly coupled code increase, and it becomes a lot harder to swap out dependencies on the fly (or even refactor on a package-by-package basis). Go's ducktype interfaces are a very powerful tool in your armory here. I've purposefully declared the <code>Logger</code> and <code>DB</code> interfaces in the <code>persistence</code> package above. Basic SOLID principles apply here (IoC and Liskov substitution principle specifically).</p>\n\n<p>A simple example:</p>\n\n<pre><code>package \"contacts\"\n\ntype addressBook struct {\n data map[string]Address\n}\n\nfunc NewAddressbook(addresses ...Address) *addressBook {\n a := addressBook{\n data: map[string]Address{}, // or make(map[string]Address, len(addresses)\n }\n for _, addr := range addresses {\n a[addr.Person.Name] = addr\n }\n return &amp;a\n}\n\nfunc (a *addressBook) Add(addr Address) {\n a.data[addr.Person.Name] = addr\n}\n\nfunc (a addressBook) Find(name string) (*Address, error) {\n if addr, ok := a.data[name]; ok {\n return &amp;addr, nil\n }\n return nil, AddressNotFoundErr\n}\n</code></pre>\n\n<p>Now this is all pretty clear, but what if I were to change the <code>NewAddressbook</code> func to return an interface that I defined in this package. The interface would, naturally, have to contain all exported functions, so it'd look like this:</p>\n\n<pre><code>type Addressbook interface {\n Add(Address)\n Find(string) (*Address, error)\n}\n</code></pre>\n\n<p>The package that's writing to the addressbook, then, will require its dependency to implement a <code>Find</code> function, too, but it simply never uses it. That's code-smell at best. In practice, it's a matter of time before some developer gets lazy, and implements something in that package real quick (e.g. a <code>Upsert</code> type call) using the <code>Find</code> function. This function, however, is using a value receiver, not a pointer receiver, and thus you've introduced a potential data-race.</p>\n\n<p>The same problem presents itself when you use this interface in the package responsible for displaying the addressbook data: it now has write access to the data. It shouldn't. Even back in the 70s, K&amp;R knew this wasn't right, and used the <code>const</code> qualifier to protect people against themselves.</p>\n\n<p>For these reasons (and separation of concern, modularity, testability, sanity, unicorn happiness, ...) the package writing should declare an interface only specifying the <code>Add()</code> func, and the display package should only specify the <code>Find()</code> function. If you change the addressbook from an in-memory map to a DB backed store, and want to write custom filters for the representation layer, you're likely to end up with the read and write dependencies being provided by different packages anyway.</p>\n\n<p>Sorry for the tangent, but it's a giant pet-peeve of mine. I've seen countless people implement a single, giant interface rather than being sensible. Trust me, it's a lot easier to find your way in a codebase when you open a file, and just see an explicit definition of all the interfaces that package/type depends on, instead of seeing a ton of imports, pointing you towards 1001 interfaces, and then having to through the code to work out which <em>parts</em> of the interfaces the code you're working on actually relies on. (rant over)</p>\n\n<h2>Cosmetics</h2>\n\n<p>Now lists like the ones above are nice to keep track of what you're testing. Wouldn't it be nice to have a way to have lists like that in our unit test? Thankfully, you can. Instead of having a <code>data</code> and <code>expect</code> map, or a <code>TestX</code> function per case, I tend to group tests per function like this:</p>\n\n<pre><code>func TestCASStudent(t *testing.T) {\n t.Run(\"Student name is missing\", studentNameMissing)\n t.Run(\"Student ID already set\", studentIDSet)\n t.Run(\"Student CAS success\", studentCASSuccess)\n t.Run(\"Student valid, DB error\", studentDBError)\n}\n</code></pre>\n\n<p>Then it's a simple matter of implementing the functions one by one.</p>\n\n<h2>Further reading/later update</h2>\n\n<p>I'm going to leave you with this to digest for now. I'll probably revisit this answer at a later date, because there's still stuff I haven't gotten to. For now, though, I'll point you to <a href=\"https://golang.org/pkg/net/http/httptest/\" rel=\"nofollow noreferrer\">the standard <code>httptest</code> package</a>, which could be useful when testing HTTP requests :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T15:52:55.167", "Id": "456897", "Score": "0", "body": "Thank you! I couldn't even expect such a detailed review. This is definitely something I need to work on for some time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T16:00:01.690", "Id": "456898", "Score": "2", "body": "Thanks, once again. I have just started a new bounty - I will reward your answer once the bounty ends :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T10:16:24.887", "Id": "233674", "ParentId": "233021", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T21:15:55.780", "Id": "233021", "Score": "7", "Tags": [ "unit-testing", "go", "rest", "orm" ], "Title": "Unit testing a REST API in Go" }
233021
<p>I've made a function that outputs the highest and lowest values from a string containing a space-separated list of numbers.</p> <p>For example, if given <code>"123 956 334 421 -543"</code>, my function returns <code>123, -543</code>.</p> <pre><code> def high_and_low(numbers): m = [int(i) for i in numbers.split()] h = max(m) n = [int(i) for i in numbers.split()] l = min(n) return h, l r = high_and_low(input("Enter numbers: ")) print(r[0], r[1]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T23:34:49.660", "Id": "455336", "Score": "1", "body": "Why do you need to do `n = [int(i) for i in numbers.split()]` a second time? Won't be `l = min(m)` just fine?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T23:38:46.243", "Id": "455337", "Score": "8", "body": "Why is `123` the maximum? Isn't `956`, `334`, and `421` all larger?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T03:40:54.760", "Id": "455350", "Score": "1", "body": "not easier on the coder: [min&max with no more than 1.5n comparisons](http://pythonfiddle.com/minmax/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T06:16:53.843", "Id": "455360", "Score": "0", "body": "I agree with @AJNeufeld, this doesn’t make any sense." } ]
[ { "body": "<h2>Duplicate Code</h2>\n\n<p>These lines of code:</p>\n\n<pre><code> m = [int(i) for i in numbers.split()]\n n = [int(i) for i in numbers.split()]\n</code></pre>\n\n<p>assign the same result to the variables <code>m</code> and <code>n</code>. This results in double the needed work being performed. The <code>numbers</code> string is being split twice, and all the terms are being converted from strings to integers twice.</p>\n\n<p>You only need the first line:</p>\n\n<pre><code> m = [int(i) for i in numbers.split()]\n</code></pre>\n\n<p>Or expressed more functionally:</p>\n\n<pre><code> m = list(map(int, numbers.split()))\n</code></pre>\n\n<h2>Directly return values</h2>\n\n<p>You do not need to assign values to variables before returning them. You can simply return the calculations:</p>\n\n<pre><code> return max(m), min(m)\n</code></pre>\n\n<h2>Variable Names</h2>\n\n<p><code>m</code>, <code>h</code>, <code>n</code>, and <code>l</code> are terrible variable names. They convey almost no meaning. The reader might be able to guess <code>h</code> represents the high value, and <code>l</code> represents the low value, but make it easier on them; use <code>low</code> and <code>high</code> as the variable names. Perhaps <code>nums</code> or <code>values</code> instead of <code>m</code>. As mentioned above, <code>n</code> is not needed.</p>\n\n<h2>Reworked code</h2>\n\n<p>Here is one possible refactoring of your <code>high_and_low</code> function:</p>\n\n<pre><code>def high_and_low(numbers):\n\n values = list(map(int, numbers.split()))\n return max(values), min(values)\n</code></pre>\n\n<h2>Type Hints and Docstrings</h2>\n\n<p>You can additionally help the reader (and method caller) by providing type hints and docstrings:</p>\n\n<pre><code>from typing import Tuple\n\ndef high_and_low(numbers: str) -&gt; Tuple[int, int]:\n \"\"\"\n Parse a string of space separated integers and return the\n highest and lowest integers found in the string.\n\n &gt;&gt;&gt; high_and_low(\"123 956 334 421 -543\")\n (956, -543)\n \"\"\"\n\n values = list(map(int, numbers.split()))\n return max(values), min(values)\n</code></pre>\n\n<p>In a Python REPL, the user can type <code>help(high_and_low)</code> to get usage information for the function (the <code>\"\"\"docstring\"\"\"</code> of the function).</p>\n\n<p>The Python <code>doctest</code> module can extract <code>&gt;&gt;&gt;</code> lines from the <code>\"\"\"docstring\"\"\"</code> and execute them, and compare the output with the line(s) which follow, to ensure the function behaves as described.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>aneufeld$ python3.8 -m doctest -v high_and_low.py \nTrying:\n high_and_low(\"123 956 334 421 -543\")\nExpecting:\n (956, -543)\nok\n1 items had no tests:\n high_and_low\n1 items passed all tests:\n 1 tests in high_and_low.high_and_low\n1 tests in 2 items.\n1 passed and 0 failed.\nTest passed.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T06:17:46.120", "Id": "455361", "Score": "2", "body": "Why the `list(map())` instead of a clean and pythonic list comprehension? Aside from that, nice solution! Good to see people encouraging the use of type annotations and tests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:51:38.387", "Id": "455430", "Score": "1", "body": "@AlexanderCécile Because it was 2 characters shorter :-) Some people prefer functional programming. I showed the list compression version and the functional version two lines apart; I was not advocating (strongly) for one over the other." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T05:31:39.553", "Id": "233047", "ParentId": "233027", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T22:38:11.573", "Id": "233027", "Score": "-1", "Tags": [ "python" ], "Title": "Find minimum and maximum in a string with spaces" }
233027
<p>I'm learning C++, data structures and algorithms and decided to implement some sorting algorithms using generic iterators instead of array indices. </p> <p>This post contains code for insertion sort and other three variants: insertion sort with binary search, insertion sort with interpolation search and shell sort. As implied by the name, the first two variants uses a binary search and an interpolation search, respectively, instead of linearly search for the correct place to insert the key. Shell sort is a well known variant that sorts elements at distant positions and then successively reduces this distance.</p> <p>Also, I decided to measure the running time and would like to known if my approach is correct. The results were consistent with the theoretical results that I was expecting after reading an algorithm book, but is there any best practice regarding time measurement that I'm missing?</p> <p>I'm compiling with flags g++ -std=c++17 -g -Wall -Wextra -pedantic-errors I executed the code using valgrind, but it was <em>much</em> slower, so I only used arrays of maximum size 1000 when running with valgrind.</p> <p>I'm learning C++ through a C++11 book and trying to learn C++14 and C++17 best practices on the fly. I appreciate any advice on how make it more compatible with modern best practices. </p> <p><strong>Sorting.h</strong></p> <pre><code>#ifndef SORTING_H #define SORTING_H #include &lt;iterator&gt; #include &lt;functional&gt; namespace algorithms { template&lt;typename RandomIt, typename Compare = std::less&lt;&gt;&gt; void insertion_sort(RandomIt first, RandomIt last, Compare compare = Compare{}); template&lt;typename RandomIt, typename Compare = std::less&lt;&gt;&gt; void binary_insertion_sort(RandomIt first, RandomIt last, Compare compare = Compare{}); // Only works for numeric types template&lt;typename RandomIt, typename Compare = std::less&lt;&gt;&gt; void interpolation_insertion_sort(RandomIt first, RandomIt last, Compare compare = Compare{}); template&lt;typename RandomIt, typename Compare = std::less&lt;&gt;&gt; void shell_sort(RandomIt first, RandomIt last, Compare compare = Compare{}); // namespace detail is used for implementation details: not intended for external usage namespace detail { template&lt;typename RandomIt, typename Compare, typename T = typename std::iterator_traits&lt;RandomIt&gt;::value_type&gt; RandomIt binary_search(RandomIt first, RandomIt last, const T&amp; target, Compare compare); template&lt;typename RandomIt, typename Compare, typename T = typename std::iterator_traits&lt;RandomIt&gt;::value_type&gt; RandomIt interpolation_search(RandomIt first, RandomIt last, const T&amp; target, Compare compare); template&lt;typename RandomIt, typename SearchFunction, typename Compare&gt; void insertion_sort(RandomIt first, RandomIt last, SearchFunction search, Compare compare); } } #include "Sorting.inl" #endif // SORTING_H </code></pre> <p><strong>Sorting.inl</strong></p> <pre><code>namespace algorithms { /* The standard version of insertion_sort does not delegate the common work for detail::insertion_sort because it would incur in a unnecessary cost of a linear search to find the correct position and then an iteration to move elements. Instead, it can search the right position and move elements on a single pass. */ template&lt;typename RandomIt, typename Compare&gt; void insertion_sort(RandomIt first, RandomIt last, Compare compare) { if (first != last) { for (auto it = first + 1; it != last; ++it) { auto key = std::move(*it); auto backward_it = it; for ( ; backward_it != first &amp;&amp; compare(key, *(backward_it - 1)); --backward_it) { *(backward_it) = std::move(*(backward_it - 1)); } *backward_it = std::move(key); } } } template&lt;typename RandomIt, typename Compare&gt; void binary_insertion_sort(RandomIt first, RandomIt last, Compare compare) { detail::insertion_sort(first, last, detail::binary_search&lt;RandomIt, Compare&gt;, compare); } template&lt;typename RandomIt, typename Compare&gt; void interpolation_insertion_sort(RandomIt first, RandomIt last, Compare compare) { detail::insertion_sort(first, last, detail::interpolation_search&lt;RandomIt, Compare&gt;, compare); } template&lt;typename RandomIt, typename Compare&gt; void shell_sort(RandomIt first, RandomIt last, Compare compare) { if (first != last) { int h = 1; auto range_size = last - first; // Compute Knuth Sequence while (h &lt; range_size / 3) { h = 3 * h + 1; } while (h &gt; 0) { auto h_sequence_first = first + h; for (auto it = h_sequence_first; it != last; ++it) { auto key = std::move(*it); auto backward_it = it; for ( ; backward_it &gt;= h_sequence_first &amp;&amp; compare(key, *(backward_it - h)); backward_it -= h) { *(backward_it) = std::move(*(backward_it - h)); } *backward_it = std::move(key); } h = h / 3; } } } namespace detail { template&lt;typename RandomIt, typename Compare, typename T = typename std::iterator_traits&lt;RandomIt&gt;::value_type&gt; RandomIt binary_search(RandomIt first, RandomIt last, const T&amp; target, Compare compare) { while (first &lt; last) { auto distance = last - first; auto middle = first + (distance / 2); if (*middle == target) { return middle; } else if (compare(*middle, target)) // less than target { first = middle + 1; } else { last = middle; } } return first; } template&lt;typename RandomIt, typename Compare, typename T = typename std::iterator_traits&lt;RandomIt&gt;::value_type&gt; RandomIt interpolation_search(RandomIt first, RandomIt last, const T&amp; target, Compare compare) { while (first &lt; last) { auto&amp; left = *first; auto&amp; right = *(last - 1); if (compare(target, left)) { return first; } else if (compare(right, target)) { return last; } auto middle = first + (double(last - 1 - first)) * ((double(target) - double(left)) / (double(right) - double(left))); if (*middle == target) { return middle; } else if (compare(*middle, target)) // less than target { first = middle + 1; } else { last = middle; } } return first; } template&lt;typename RandomIt, typename SearchFunction, typename Compare&gt; void insertion_sort(RandomIt first, RandomIt last, SearchFunction search, Compare compare) { if (first != last) { for (auto it = first + 1; it != last; ++it) { auto correct_position = search(first, it, *it, compare); auto key = std::move(*it); for (auto backward_it = it; backward_it != correct_position; --backward_it) { *backward_it = std::move(*(backward_it - 1)); } *correct_position = std::move(key); } } } } } </code></pre> <p><strong>test.cpp</strong></p> <pre><code>#include &lt;array&gt; #include &lt;cassert&gt; #include &lt;iostream&gt; #include &lt;random&gt; #include &lt;vector&gt; #include "Sorting.h" template&lt;typename T&gt; using Matrix = std::vector&lt;std::vector&lt;T&gt;&gt;; template&lt;typename T, typename Compare&gt; void assert_equal(const std::vector&lt;T&gt;&amp; vector1, std::vector&lt;T&gt; vector2, Compare compare) { // vector1 is assumed to be already sorted // vector2 is passed by copy to prevent changing the original vector std::sort(vector2.begin(), vector2.end(), compare); assert(vector1 == vector2); } template&lt;typename T, typename Compare&gt; void assert_sorted(const std::vector&lt;T&gt;&amp; vector, Compare compare) { assert(std::is_sorted(vector.begin(), vector.end(), compare)); } template&lt;typename T, typename Function, typename Compare = std::less&lt;&gt;&gt; void test_sort(const Matrix&lt;T&gt;&amp; original, Function function, Compare compare = Compare{}) { for (const auto&amp; vector : original) { std::vector&lt;T&gt; to_sort { vector }; function(to_sort, compare); assert_sorted(to_sort, compare); assert_equal(to_sort, vector, compare); } } template&lt;typename T&gt; void test_sorting_algorithms(const Matrix&lt;T&gt;&amp; original) { test_sort(original, [](auto&amp; vector, auto compare) { algorithms::insertion_sort(vector.begin(), vector.end(), compare); }); test_sort(original, [](auto&amp; vector, auto compare) { algorithms::insertion_sort(vector.begin(), vector.end(), compare); }, std::greater&lt;&gt;()); test_sort(original, [](auto&amp; vector, auto compare) { algorithms::binary_insertion_sort(vector.begin(), vector.end(), compare); }); test_sort(original, [](auto&amp; vector, auto compare) { algorithms::binary_insertion_sort(vector.begin(), vector.end(), compare); }, std::greater&lt;&gt;()); test_sort(original, [](auto&amp; vector, auto compare) { algorithms::interpolation_insertion_sort(vector.begin(), vector.end(), compare); }); test_sort(original, [](auto&amp; vector, auto compare) { algorithms::interpolation_insertion_sort(vector.begin(), vector.end(), compare); }, std::greater&lt;&gt;()); test_sort(original, [](auto&amp; vector, auto compare) { algorithms::shell_sort(vector.begin(), vector.end(), compare); }); test_sort(original, [](auto&amp; vector, auto compare) { algorithms::shell_sort(vector.begin(), vector.end(), compare); }, std::greater&lt;&gt;()); } int main() { Matrix&lt;int&gt; original; original.emplace_back(std::initializer_list&lt;int&gt;{}); // empty vector original.emplace_back(std::initializer_list&lt;int&gt;{ 1, 3, 5, 7, 9 }); // already sorted original.emplace_back(std::initializer_list&lt;int&gt;{ 9, 7, 5, 3, 1 }); // reverse sorted original.emplace_back(std::initializer_list&lt;int&gt;{ 1, 3, 1, 5, 1 }); // repeated elements original.emplace_back(std::initializer_list&lt;int&gt;{ 9, 9, 9, 9, 9 }); // unique elements // randomly generated data std::random_device random_device; std::mt19937 mt(random_device()); std::uniform_int_distribution&lt;int&gt; distribution(-100, 100); std::array&lt;int, 7&gt; vector_sizes = {{ 1, 2, 3, 5, 10, 100, 500 }}; std::vector&lt;int&gt; temp; for (auto size: vector_sizes) { for (int i = 0; i &lt; size; ++i) { temp.push_back(distribution(mt)); } original.emplace_back(std::move(temp)); } test_sorting_algorithms(original); std::cout &lt;&lt; "End of Test\n"; } </code></pre> <p><strong>time_comparison.cpp</strong></p> <pre><code>#include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;cassert&gt; #include &lt;chrono&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include "Sorting.h" template&lt;typename Fstream&gt; void open_file(Fstream&amp; stream, const std::string&amp; path) { stream.close(); stream.clear(); stream.open(path); if (!stream) { std::cerr &lt;&lt; "Error: could not find file at specified path - " &lt;&lt; path &lt;&lt; "\n"; } } template&lt;typename T&gt; void fill_vector(std::vector&lt;T&gt;&amp; vector, std::ifstream&amp; stream) { vector.clear(); T data; while (stream &gt;&gt; data) { vector.emplace_back(data); } } template&lt;typename F, typename... Args&gt; auto measure_time(F&amp;&amp; function, Args&amp;&amp;... args) { auto start = std::chrono::high_resolution_clock::now(); function(std::forward&lt;Args&gt;(args)...); auto end = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(end - start); } template&lt;typename F&gt; void execution_time(const std::string&amp; filename, F&amp;&amp; function) { const std::array&lt;std::string, 6&gt; sorting_condition = {{ "Sorted", "90%Sorted", "75%Sorted", "HalfSorted", "ReverseSorted", "Random" }}; const std::array&lt;int, 10&gt; sizes = {{ 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 }}; constexpr int experiments = 100; std::vector&lt;int&gt; to_sort; to_sort.reserve(10000); std::ifstream input_file; std::ofstream output_file; open_file(output_file, filename); for (const auto&amp; sorting: sorting_condition) { output_file &lt;&lt; "Input " &lt;&lt; sorting &lt;&lt; "\n"; for (auto size: sizes) { output_file &lt;&lt; "Size: " &lt;&lt; size &lt;&lt; "\t\t"; open_file(input_file, "./data/" + sorting + std::to_string(size / 1000) + "K.txt"); fill_vector(to_sort, input_file); assert(static_cast&lt;int&gt;(to_sort.size()) == size); std::chrono::microseconds average{ 0 }; for (int i = 0; i &lt; experiments; ++i) { average += measure_time(function, to_sort); } output_file &lt;&lt; std::fixed &lt;&lt; (average / experiments).count() &lt;&lt; "\n"; } output_file &lt;&lt; "\n"; assert(std::is_sorted(to_sort.begin(), to_sort.end())); } } int main() { execution_time("Insertion Sort.txt", [](auto&amp; vector) { algorithms::insertion_sort(vector.begin(), vector.end()); }); execution_time("Binary Insertion Sort.txt", [](auto&amp; vector) { algorithms::binary_insertion_sort(vector.begin(), vector.end()); }); execution_time("Interpolation Insertion Sort.txt", [](auto&amp; vector) { algorithms::interpolation_insertion_sort(vector.begin(), vector.end()); }); execution_time("Shell Sort.txt", [](auto&amp; vector) { algorithms::shell_sort(vector.begin(), vector.end()); }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T16:04:56.357", "Id": "455443", "Score": "0", "body": "Personally I would have spread this across 5 questions. There is a lot of hard thinking to do this reiew. Maybe this weekend," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T17:27:27.963", "Id": "455459", "Score": "0", "body": "Would you prefer if I remove the \"time_comparison\" part and post it as another question? Since nobody answered this question yet, I guess that this does not break the rules. However, I would say that Sorting.h/Sorting.inl is tied to test.cpp and the code is somewhat short (at least in comparison to other code that I have post on this site on other opportunities)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T01:04:13.200", "Id": "455487", "Score": "0", "body": "I think I'm used to *interpolation search* with upper and lower bound kept current and not re-determined for the unchanged bound and the index next to the changed one. I see that the source code on en.wikipedia does more comparisons and array accesses, still." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T01:32:03.880", "Id": "455491", "Score": "0", "body": "@greybeard sorry, I didn't understand what you meant. Could you provide a source or example for the interpolation search implementation that you're talking about? My implementation was based on Sedgewick's book and my professor's lecture notes, but I adapted it so that the code returns an iterator to the correct place to insert the key (instead of returning -1 or nullptr, for example)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T23:40:44.233", "Id": "233030", "Score": "3", "Tags": [ "c++", "beginner", "algorithm", "reinventing-the-wheel", "c++17" ], "Title": "Sorting Algorithms in C++ - Insertion Sort and some variants" }
233030
<p>I'm working on a (naïve) algorithm for portfolio optimization using GA. It takes a list of stocks, calculates its expected returns and the covariance between all of them and then it returns the portfolio weights that would produce the highest return of investment given a certain <em>maximum risk</em> the investor is willing to be exposed to.</p> <p>The expected return of the portfolio is calculated multiplying the weight of the stock (a percentage) by that stock's expected return, while the risk is calculated using the matrix equation <code>w^T * Cov * w</code>, where <code>w</code> is the array of weights and <code>Cov</code> is the covariance matrix.</p> <p>I'm having trouble improving performance with my algorithm. I've timed the execution of the different parts of the algorithm and found that the crossing is the part that takes the longest (around 5 seconds per iteration).</p> <h3>geneticAlgorithmPortfolioGenerator.py</h3> <p>This is the main class. The portfolio is generated by calling its <code>generate_portfolio()</code> method after instantiating the class with the maximum risk, the stock returns and the covariance matrix. It runs for <code>generations</code> generations unless it fails to improve after 100 generations, in which case it short-cuts the loop and returns. <strong>This has been the case every time I've executed it</strong>.</p> <pre><code>class Genetic_Algorithm_Portfolio: def __init__(self, max_risk, generations, returns, cov_matrix): ''' Creates a genetic algorithm portfolio generator - population: list of Candidate objects - max_risk: risk constraint the portfolio must meet - generations: number of generations the algorithm will run to create a better solution ''' self.max_risk = max_risk self.generations = generations self.returns = returns self.cov_matrix = cov_matrix def generate_portfolio(self): #print(&quot;Generating portfolio&quot;) # Map solutions so that the Candidate objects also have normalized fitness value and cummulative sum t0 = time.time() random_generator = Random_Portfolio_Generator(5000, self.max_risk, self.returns, self.cov_matrix) t1 = time.time() print(&quot;Time to generate random set: &quot; + str(int(t1 - t0)) + &quot; seconds&quot;) self.initial_population = random_generator.generate_solutions()[0] if len(self.initial_population) == 0: return None self.map_solutions() current_generation = self.initial_population initial_weight = [0]*len(self.initial_population[0].weights) best_solution = Candidate( initial_weight, portfolioUtilities.calculate_return(initial_weight, self.returns), portfolioUtilities.calculate_std(initial_weight, self.cov_matrix) ) # With this initial population, run 100 generations improvements = 100 for i in range(self.generations): t_g0 = time.time() if improvements == 0: print(&quot;No improvements after 100 generations&quot;) break # Next generation will be those selected by the selection method + the 10 best by expected return from the current generation t_s0 = time.time() next_gen_selected = self.next_generation(current_generation) current_generation.sort(key=lambda x: x.expected_return, reverse=True) next_gen_selected = next_gen_selected + current_generation[:10] t_s1 = time.time() print(f&quot;Next generation selection: {str(int(t_s1 - t_s0))} seconds&quot;) # Pair parents t_p0 = time.time() parents = self.pair(next_gen_selected) t_p1 = time.time() print(f&quot;Parents selection: {str(int(t_p1 - t_p0))} seconds&quot;) # Cross them and create the next gen next_gen = [] t_c0 = time.time() for j in range(len(parents)): next_gen = next_gen + self.cross(parents[j]) # Check if you found a better solution next_gen.sort(key=lambda x: x.expected_return, reverse=True) t_c1 = time.time() print(f&quot;Cross: {str(int(t_c1 - t_c0))} seconds&quot;) if len(next_gen) == 0: continue next_gen_best_solution = next_gen[0] if (best_solution.expected_return &lt; next_gen_best_solution.expected_return): best_solution = next_gen_best_solution improvements = 100 else: improvements -= 1 # Next generation is now current generation current_generation = next_gen t_g1 = time.time() print(f&quot;&gt;&gt;&gt; Generation {i} time: {str(int(t_g1 - t_g0))} seconds&quot;) #print(&quot;Done!&quot;) return best_solution </code></pre> <h3>Random solutions</h3> <p>I generate 5000 random solutions simply checking that all weights are above 0 and the risk is under the max risk passed as parameter:</p> <pre><code>lass Random_Portfolio_Generator: def __init__(self, n, max_risk, returns, cov_matrix): self.num_solutions = n self.max_risk = max_risk self.returns = returns self.cov_matrix = cov_matrix def generate_solutions(self): solutions = [] best_solution = [] best_return = float(&quot;-inf&quot;) best_std = 0 seed = 42 counter = 0 attempts = 0 while counter &lt; self.num_solutions and attempts &lt; 1000: random.seed(seed) seed += 1 weights = self.generate_random_weights() solution = Candidate( weights, portfolioUtilities.calculate_return(weights, self.returns), portfolioUtilities.calculate_std(weights, self.cov_matrix) ) if (solution.std &lt;= self.max_risk): attempts = 0 counter +=1 solutions.append(solution) if (solution.expected_return &gt; best_return): best_return = solution.expected_return best_solution = solution best_std = solution.std else: attempts += 1 return solutions, best_solution, best_return, best_std def generate_random_weights(self): n = len(self.returns) arr = [0] * n indexes = list(range(n)) sum = 0; for i in range(n - 1): rand = random.randint(0,1000 - sum) index = random.choice(indexes) indexes.remove(index) sum += rand arr[index] = rand arr[indexes[0]] = 1000 - sum return np.array([x / 1000 for x in arr]) </code></pre> <h3>Selection</h3> <p>My selection method is encapsulated in the <code>next_generation()</code> method, which uses roulette selection by cumulative sum of the expected return of each portfolio. I also sort the current generation by expected return and add the 10 best chromosomes to the next generation.</p> <pre><code> def next_generation(self, current): # Select chromosomes to pair cum_sums = [o.cum_sum for o in self.initial_population] selected = [] for x in range(len(cum_sums)//2): selected.append(self.roulette(cum_sums, np.random.rand())) # In case the roulette picks an index that has already been picked while len(set(selected)) != len(selected): selected[x] = self.roulette(cum_sums, np.random.rand()) return [self.initial_population[int(selected[x])] for x in range(len(self.initial_population)//2)] def roulette(self, cum_sum, chance): veriable = list(cum_sum.copy()) veriable.append(chance) veriable = sorted(veriable) return veriable.index(chance) </code></pre> <h3>Pairing</h3> <p>I pair the next generation by a &quot;next best&quot; approach:</p> <pre><code> def pair(self, generation): # Pairs selected chromosomes by fitness return [generation[i:i + 2] for i in range(0, len(generation), 2)] </code></pre> <h3> Crossing</h3> <p>To cross the pairs, I take a middle point <code>d = (x1 - x2) / 3</code> and add it and subtract it from each parent to create 4 new solutions. I found this method in a paper after finding that the traditional crossing methods ended up always creating invalid solutions (more risk than the max tolerated by the user). I filter those that don't fit that criteria neither:</p> <pre><code> def cross(self, parents): x1 = parents[0].weights x2 = parents[1].weights d = (x1 - x2) / 3 x3 = self.mutate(x1 + d) x4 = self.mutate(x1 - d) x5 = self.mutate(x2 + d) x6 = self.mutate(x2 - d) return sorted(self.judge_candidates([ parents[0], parents[1], Candidate( x3, portfolioUtilities.calculate_return(x3, self.returns), portfolioUtilities.calculate_std(x3, self.cov_matrix) ), Candidate( x4, portfolioUtilities.calculate_return(x4, self.returns), portfolioUtilities.calculate_std(x4, self.cov_matrix) ), Candidate( x5, portfolioUtilities.calculate_return(x5, self.returns), portfolioUtilities.calculate_std(x5, self.cov_matrix) ), Candidate( x6, portfolioUtilities.calculate_return(x6, self.returns), portfolioUtilities.calculate_std(x6, self.cov_matrix) ) ]), key=lambda x: x.expected_return, reverse=True)[:2] def judge_candidates(self, candidates): return list(filter(lambda x: x.std &lt;= self.max_risk and all(i &gt;= 0 for i in x.weights), candidates)) </code></pre> <h3>Mutation</h3> <p>Finally, I mutate two random genes in the chromosome with probability 2% in <code>random.gauss(0, 0.001)</code>.</p> <pre><code> def mutate(self, candidate): if (random.randint(0, 100) &lt;= 2): gene_one = random.randint(0, len(candidate) - 1) gene_two = random.randint(0, len(candidate) - 1) deviation = random.gauss(0, 0.001) candidate[gene_one] += deviation candidate[gene_two] -= deviation return candidate </code></pre> <h3>Utilities</h3> <p>These are the two utility classes I use in this class.</p> Candidate.py <pre><code>import math class Candidate: def __init__(self, weights, expected_return, std): self.weights = weights self.expected_return = expected_return self.std = math.sqrt(std) self.print = f&quot;weights: {self.weights}, return = {self.expected_return}, std = {self.std}&quot; </code></pre> portfolioUtilities.py <pre><code>import numpy as np def calculate_return(weights, returns): return (np.asarray(weights) * returns).sum() def calculate_std(weights, cov_matrix): return np.dot(np.dot(np.asarray(weights), cov_matrix),np.asarray(weights).transpose()) </code></pre> <p>Any ideas or criticisms about what I may be doing wrong?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T01:23:05.667", "Id": "455341", "Score": "1", "body": "@Emma I don't know if I can write LaTeX here, but the problem is: maximize `Sum(i=1, n) w_i * r_i` subjected to `w^T * Cov * w <= max_risk`, `Sum(i=1, n) w_i = 1`, `w_i >= 0`, where `w` is the weight vector, `r_i` is the return for the i-th stock, `Cov` is the covariance matrix between stocks and `max_risk` is the maximum risk the client is willing to tolerate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T02:03:11.957", "Id": "455342", "Score": "3", "body": "I barely know any Python, so it won't risk posting an answer, but I have to say this is probably some of the most readable Python I've ever seen. About the algorithm itself though... your population size (```num_solutions```, 5000) seems _way_ too high. I've found personally that in general, sizes from 20 to 100 work best, or about 10 times your number of dimensions, but I don't know how many dimensions you have here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T02:10:28.970", "Id": "455343", "Score": "2", "body": "Some other things you could try : use other selection methods (again, personally, I've found roulette selection to not be the most efficient in most cases) such as tournament selection, or some custom ones (keep the best n% for crossover,...). They shouldn't be too hard to implement, and they will often provide the most noticeable changes in performance. Finally, you could also try making your mutation rate vary over time, although I would suggest trying this only after you've noticed actual improvements in your algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T08:02:47.600", "Id": "455366", "Score": "0", "body": "@cliesens You are not strictly required to know the programming language as long as you can give feedback with regard to the algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T11:28:59.517", "Id": "455384", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>Few tips:</p>\n\n<ul>\n<li>try hashing fitness function, create dictionary of hashed individuals\nand their fitness values; fitness evaluation is often costly; no reason to evaluate same specimen twice</li>\n<li>don't use <code>roulette</code> selection, you can loose selective pressure, when there's little difference between fitnesses or converge too fast, when there's huge deviation; use <code>tournament</code> selection instead, it doesn't care about fitness distribution and maintains selective pressure well</li>\n<li>GA is rather well suited for parallel computation; exploit that fact; you got nice <code>multiprocessing</code> package in python's standard lib</li>\n<li>try to use hill climber to improve some of the individuals; there was a lot of research about hybrids: simulated annealing, tabu search, FIHC. It depends on your problem and encoding though.</li>\n</ul>\n\n<p>Now most important stuff - vanilla GA is slow, because it searches through space like a blind man. Try to learn about linkage learning (discrete problems) and fitness landscape analysis (continous problems). You'll be able to crash your problem way much faster.\nIf you'd like to know more about it, get some papers, please create separate thread on <a href=\"https://datascience.stackexchange.com/\">https://datascience.stackexchange.com/</a> or <a href=\"https://stats.stackexchange.com/\">https://stats.stackexchange.com/</a>. We can talk there.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T09:44:43.103", "Id": "233052", "ParentId": "233031", "Score": "4" } } ]
{ "AcceptedAnswerId": "233052", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-26T23:46:04.590", "Id": "233031", "Score": "7", "Tags": [ "python", "performance", "machine-learning" ], "Title": "Portfolio optimization using genetic algorithm" }
233031
<p>Sorry if this has been answered to death—I'm working on a pig latin translator for Odin Project. The code below works fine for individual words, but when it receives two words ("eat pie"), the output is nil. Please let me know if I've left out any details. Thanks in advance for any suggestions.</p> <pre><code>def translate(word) consonants = ("b" || "c" || "d" || "f" || "g" || "h" || "j" || "k" || "l" || "m" || "n" || "p" || "q" || "r" || "s" || "t" || "v" || "w" || "x" || "y" || "z") vowels = ("a" || "e" || "i" || "o" || "u") sentence = word.split(" ") sentence.each do |word| if vowels.include?(word[0]) pig = "#{word}ay" elsif consonants.include?(word[0]) c = word[0] pig = word.delete(c).insert(-1, c) + "ay" elsif vowels.include?(word[0]) &amp;&amp; consonants.include?(word[0]) c = word[0] pig = "#{word}ay" + word.delete(c).insert(-1, c) + "ay" elsif word[0].include?("c") &amp;&amp; word[1] == "h" c = word[0..1] pig = word.delete(c).insert(-1, c) + "ay" elsif word[0] == "t" &amp;&amp; word[1] == "h" &amp;&amp; word[2] == "r" c = word[0..2] pig = word.delete(c).insert(-1, c) + "ay" elsif word[0..2].include?("sch") c = word[0..2] pig = word.delete(c).insert(-1, c) + "ay" elsif word[0..1].include?("qu") c = word[0..1] pig = word.delete(c).insert(-1, c) + "ay" elsif word.include?("squ") c = word[0..2] pig = word.delete(c).insert(-1, c) + "ay" end return pig end </code></pre> <p>end</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T03:46:57.170", "Id": "455351", "Score": "3", "body": "Code not working as intended is [not ready for review here](https://codereview.stackexchange.com/help/on-topic)." } ]
[ { "body": "<p>Your biggest error is that you're not defining consonants and vowels as arrays of characters, but as a succession of single character joined by OR <code>||</code> conditions:</p>\n\n<pre><code>irb(main):046:0&gt; consonants = (\"b\" || \"c\" || \"d\" || \"f\" || \"g\" || \"h\" || \"j\" || \"k\" || \"l\" || \"m\" || \"n\" || \"p\" || \"q\" || \"r\" || \"s\" || \"t\" || \"v\" || \"w\" || \"x\" || \"y\" || \"z\")\n=&gt; \"b\"\nirb(main):047:0&gt; vowels = (\"a\" || \"e\" || \"i\" || \"o\" || \"u\")\n=&gt; \"a\"\n</code></pre>\n\n<p>so <code>'b'</code> and <code>'a'</code> will be always <code>true</code>, then the rest of strings are ignored.<br>\nThe real way to define <a href=\"https://docs.ruby-lang.org/en/2.0.0/Array.html\" rel=\"nofollow noreferrer\">arrays in ruby</a> is with square braces and separated by comma, like <code>['a', 'b']</code>. For your case, a simplified way to define array of strings is with <code>%w</code>, so you don't need to repeat quotes and comma symbols.</p>\n\n<p>Another problem is, when you iterate your <code>sentence</code> array, at the end of the <code>.each</code> you're returning the first <code>pig</code> word created. Then you should create a pig array or concatenate resulting words to finally return <code>pig</code> out of the loop (this last option is what I'm going to use it).</p>\n\n<pre><code> # these constants will be always the same, so I left them out of the method as\n # freezed constants, so there's no need to define them every time the method is \n # invoked\n CONSONANTS = %w[b c d f g h j k l m n p q r s t v w x y z].freeze\n VOWELS = %w[a e i o u].freeze\n\n # defaulting to an empty string in case no strings are added\n def translate(sentence = '')\n # This is going to start as an empty string\n pig = ''\n # I think there's a naming misconception here. You're receiving a sentence\n # as parameter, which is composed of words. That's why I changed the\n # variable names.\n # Also, I'm calling `.split` without a parameter, as a space is the default.\n words = sentence.split\n words.each do |word|\n if VOWELS.include?(word[0])\n # To every string I'm concatenating the resulting word, which it has a\n # final space to be removed just before to return the result.\n pig &lt;&lt; \"#{word}ay \"\n\n elsif CONSONANTS.include?(word[0])\n c = word[0]\n pig &lt;&lt; word.delete(c).insert(-1, c) + 'ay '\n\n elsif VOWELS.include?(word[0]) &amp;&amp; CONSONANTS.include?(word[0])\n c = word[0]\n pig &lt;&lt; \"#{word}ay\" + word.delete(c).insert(-1, c) + 'ay '\n\n elsif word[0].include?('c') &amp;&amp; word[1] == 'h'\n c = word[0..1]\n pig &lt;&lt; word.delete(c).insert(-1, c) + 'ay '\n\n elsif word[0] == 't' &amp;&amp; word[1] == 'h' &amp;&amp; word[2] == 'r'\n c = word[0..2]\n pig &lt;&lt; word.delete(c).insert(-1, c) + 'ay '\n\n elsif word[0..2].include?('sch')\n c = word[0..2]\n pig &lt;&lt; word.delete(c).insert(-1, c) + 'ay '\n\n elsif word[0..1].include?('qu')\n c = word[0..1]\n pig &lt;&lt; word.delete(c).insert(-1, c) + 'ay '\n\n elsif word.include?('squ')\n c = word[0..2]\n pig &lt;&lt; word.delete(c).insert(-1, c) + 'ay '\n\n end\n end\n # No need to explicitly call `return` as the last value will be what will\n # return this method.\n # Finally calling `.rstrip` to remove trailing space in the final pig word\n pig.rstrip\n end\n</code></pre>\n\n<p>With this, no matter how many words you add it:</p>\n\n<pre><code>irb(main):045:0&gt; translate 'eat a lot of pie'\n=&gt; \"eatay aay otlay ofay iepay\"\n</code></pre>\n\n<p>There's still some space to make improvements in this code, maybe moving part of the logic to new methods, but I leave that to you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T03:19:51.980", "Id": "455348", "Score": "2", "body": "When thinking of a [Good Answer](https://codereview.stackexchange.com/help/how-to-answer), respect that *not all questions can or should be answered here*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T20:51:32.253", "Id": "455475", "Score": "0", "body": "@greybeard oops, newbie mistake. 1st answer here in this S.E. site. I'll keep in mind those rules for the next one. Cheers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T03:41:40.367", "Id": "455495", "Score": "0", "body": "First, sorry for the errant post. Second, thanks for the help, @AlterLagos. That answers a few other basic questions I had in the process as well." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T02:58:12.420", "Id": "233041", "ParentId": "233034", "Score": "0" } } ]
{ "AcceptedAnswerId": "233041", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T01:21:14.993", "Id": "233034", "Score": "-1", "Tags": [ "ruby" ], "Title": "Translator method failing to translate two words" }
233034
<p>The following is a solution to the knapsack problem and supposed to be my entry to this weeks <a href="https://perlweeklychallenge.org/blog/perl-weekly-challenge-036/" rel="nofollow noreferrer">perl challenge</a>. I wonder if this is a good use of dynamic variables or is it too confusing? </p> <p>I use them so I don't have to put the variables <code>$n</code>, <code>@things</code> and <code>@result</code> in all the signatures of the multi-subs and carry them through the recursion.</p> <pre><code>sub MAIN() { my @data = { thing =&gt; 'R', weight =&gt; 1, amount =&gt; 1 }, { thing =&gt; 'B', weight =&gt; 1, amount =&gt; 2 }, { thing =&gt; 'G', weight =&gt; 2, amount =&gt; 2 }, { thing =&gt; 'Y', weight =&gt; 12, amount =&gt; 4 }, { thing =&gt; 'P', weight =&gt; 4, amount =&gt; 10 } ; my ( $v, $w, @t ) = knapsack( 15, 5, @data ); say "Value: $v, Weight: $w"; say "Taken: ", join ",", @t.map: *&lt;thing&gt;; } multi sub knapsack( Int $total-weight, Int $*n, @*things ) { my @*results; my Int $optimal-value = my Int $current-value = knapsack( $total-weight, 0 ); my Int $optimal-weight = my Int $current-weight = @*results[0].pairs.first({ .value eqv $optimal-value }).key // -1; return $optimal-value, $optimal-weight, |gather { # walk the results and find the good ones for ^$*n -&gt; $i { my %d = @*things[ $i ]; my $next-weight = $current-weight - %d&lt;weight&gt;; my $next-value = @*results[ $i + 1; $next-weight ]; with $next-value { if $next-weight &gt;= 0 &amp;&amp; $next-value == $current-value - %d&lt;amount&gt; { take @*things[ $i ]; $current-value -= %d&lt;amount&gt;; $current-weight -= %d&lt;weight&gt;; } } } take @*things[ $*n - 1 ] if $current-value &gt; 0; }; } multi sub knapsack( Int $weight, Int $i where @*results[ $i ; $weight ].defined ) { @*results[ $i ; $weight ] } multi sub knapsack( Int $weight, Int $i where $i &gt;= $*n ) { 0 } multi sub knapsack( Int $weight, Int $i where $i &lt; $*n ) { my $leftover-weight = $weight - @*things[ $i ]&lt;weight&gt;; my $current-value = knapsack( $weight, $i + 1 ); my $next-value = $leftover-weight &gt;= 0 ?? ( @*things[ $i ]&lt;amount&gt; + knapsack( $leftover-weight, $i + 1 ) ) !! 0; @*results[ $i ; $weight ] = ( $current-value, $next-value ).max } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T01:23:16.527", "Id": "233035", "Score": "3", "Tags": [ "knapsack-problem", "raku" ], "Title": "Raku and the Knapsack" }
233035
<p>I am looking at some code that merges boxes:</p> <pre><code>#include &lt;stdio.h&gt; #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/opencv.hpp" #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;stdio.h&gt; #include &lt;tr1/unordered_map&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;dirent.h&gt; using namespace std::tr1; using namespace std; using namespace cv; #define MERGE_THRESHOLD 0.15 #define IOU_THRESHOLD 0.3 vector&lt;Rect&gt; merge_boxes(const vector&lt;Rect&gt; boxes) { // Partitions bounding boxes if IOU is above threshold unordered_map&lt;int, set&lt;int&gt;*&gt; partitions; // Iterate over each pair of boxes for( int i = 0; i &lt; boxes.size(); i++ ) { unordered_map&lt;int,set&lt;int&gt;*&gt;::iterator i_it = partitions.find(i); if (i_it == partitions.end()) { // Insert default partitions set&lt;int&gt;* initial_set = new set&lt;int&gt;(); initial_set-&gt;insert(i); i_it = partitions.insert(pair&lt;int,set&lt;int&gt;*&gt;(i, initial_set)).first; } for (int j = i + 1; j &lt; boxes.size(); j++) { // If IOU is above threshold, we partition them Rect intersection = boxes[i] &amp; boxes[j]; Rect box_union = boxes[i] | boxes[j]; float intersectionArea = intersection.area(); float unionArea = box_union.area(); if ((intersectionArea / unionArea) &gt; MERGE_THRESHOLD) { unordered_map&lt;int,set&lt;int&gt;*&gt;::iterator j_it = partitions.find(j); if (i_it != partitions.end() &amp;&amp; j_it != partitions.end()) { if (i_it-&gt;second != j_it-&gt;second) { // Merge sets if pointers are of different partitions i_it-&gt;second-&gt;insert(j_it-&gt;second-&gt;begin(), j_it-&gt;second-&gt;end()); set&lt;int&gt; temp = *j_it-&gt;second; for (auto index : temp) { // Change all pointers from partition of j to the new merged set partitions[index] = i_it-&gt;second; } } } else if (i_it != partitions.end()) { // Add j to partition i if j is not partitioned i_it-&gt;second-&gt;insert(j); partitions[j] = i_it-&gt;second; } else if (j_it != partitions.end()) { // Add i to partition j if i is not partitioned j_it-&gt;second-&gt;insert(i); partitions[i] = j_it-&gt;second; } } } } vector&lt;Rect&gt; partitioned_boxes; for (auto elem : partitions) { // Check if partition has been processed int n = elem.second-&gt;size(); if (n &gt; 0) { // Find average position, width and height of Rect in partition Point pos = Point(0,0); int width = 0, height = 0; for (auto j : *elem.second) { Rect box = boxes[j]; pos += Point(box.x, box.y); width += box.width; height += box.height; } pos = Point(cvRound(pos.x/n), cvRound(pos.y/n)); width = cvRound(width/n); height = cvRound(height/n); Rect avg_rect = Rect(pos, pos + Point(width, height)); // Clears partition and push average rectangle partitioned_boxes.push_back(avg_rect); elem.second-&gt;clear(); } } return partitioned_boxes; } </code></pre> <p>How do I make this more idiomatic and readable?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T09:38:56.863", "Id": "455377", "Score": "1", "body": "If this post is an update to your previous post, you should be mentioning that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T14:20:32.633", "Id": "455744", "Score": "0", "body": "@M.ars Please do not post your review in comments. Post as an answer instead, even if it's just a few simple points." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T14:29:36.380", "Id": "455745", "Score": "0", "body": "Sorry, someone posted a helpful comment of these nature on a post of mine and I thought it wasn't wrong. I'm not going to repeat that, thanks for the advice." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T01:34:45.687", "Id": "233036", "Score": "0", "Tags": [ "c++", "c++11", "opencv" ], "Title": "Merging rectangles" }
233036
<p>I am currently in between semesters at school and am using that time to improve on my knowledge of C++ classes by making a node class and a linked list class that inherits from the node class. There is a list of areas in need of improvement at the start of the code, but I was also hoping to get some external input on this as well. Once these two classes are more sounds I'm going to implement a stack and queue class as well. I am building this code using Visual Studio 2019 on a Windows 10 operating system, and I do not believe it is optimized for cross-OS use.</p> <p>If you believe that the int <code>main()</code> function I use to test the member functions is necessary to giving accurate feedback, I would be happy to comply.</p> <pre><code>//LinkedList.h #include &lt;stdio.h&gt; #pragma once /*PLACES TO START AND IMPROVE ON CODE Proper ctor and dtor implementation, Replace int data value with template &lt;typename T&gt;, Const Correctness, keep default constructor in protected, ostream operator set_tail() and get_tail() function utilization return node* from back_list() and push_back() */ const int UnkD = 999;//Variable for node() default constructor init //NODE class code from http://cplusplus.com/forum/beginner/194591 class node { protected: int data; node* prev; node* next; public: node() : data(UnkD), prev(nullptr), next(nullptr) { printf(&quot;default node() ctor called... \n&quot;); } //Default Constructor node(const int &amp; d,node* p,node* n): data(d), prev(p), next(n) { printf(&quot;node() ctor with args called... \n&quot;); } //Constructor With Args node(const node&amp; rhs) { printf(&quot;node() copy ctor called... \n&quot;); data = rhs.data; prev = rhs.prev; next = rhs.next; }; //Copy Constructor node &amp; operator = (const node&amp; rhs) { //Copy Operator printf(&quot;Copy Operator&quot;); if (this != &amp;rhs) { data = rhs.data; prev = rhs.prev; next = rhs.next; } return *this; } void set_data(int x) { data = x; } void set_prev(node* node) { prev = node; } void set_next(node* node) { next = node; } int get_data() { return this-&gt;data; } node* get_prev() { return this-&gt;prev; } node* get_next() { return this-&gt;next; } ~node() { printf(&quot;~node() dtor called...\n&quot;); delete[] this; }; }; class LL: public node { private: node* head; node* tail; public: //Class Ctor Functions LL() : head(nullptr), tail(nullptr) { printf(&quot;LL deault constructor \n&quot;); } LL(node* head, node* tail) : head(nullptr), tail(nullptr) { printf(&quot;LL constructor with assignments \n&quot;); } void set_head(node* node) { head = node; } void set_tail(node* node) { tail = node; } node* get_head() { return this-&gt;head; } node* get_tail() { return this-&gt;tail; } //Create and Destroy Fucntions node* create_node(int d); void delete_list(node* list); void delete_selected(node* list, int selection); //Add and Remove Node Functions node* push_front(node* list, node* node); node* push_back(node* list, node* node); node* pop_front(node* list); void pop_back(node* list); void append_before(node* list, node* node, int selection); void append_after(node* list, node* node, int selection); //View List Functions void front_list(node* list); void back_list(node* list); void print_fwd(node* list); void print_bwd(node* list); void list_selected(node* list, int selection); ~LL() { printf(&quot;LL destructor \n&quot;); while (head) { node* tmp = head-&gt;get_next(); delete[] tmp; } } }; //create and destroy functions node* LL::create_node(int d) { return new node{ d, nullptr, nullptr }; } void LL::delete_list(node* list) { while (list) { node* tmp = list; list = list-&gt;get_next(); delete[] tmp; } printf(&quot;List Deleted. \n&quot;); } void LL::delete_selected(node* list, int selection) { int count = 0; while (count != (selection - 1)) { list = list-&gt;get_next(); count++; } node* tmp = list; list = list-&gt;get_prev(); list-&gt;set_next(tmp-&gt;get_next()); list = tmp-&gt;get_next(); list-&gt;set_prev(tmp-&gt;get_prev()); //delete[] tmp; } //add and remove node functions node* LL::push_front(node* list, node* node) { if (!list) { return node; } node-&gt;set_next(list); list-&gt;set_prev(node); list = node; return list; } node* LL::push_back(node* list, node* node) { if (list-&gt;get_next() == nullptr) { list-&gt;set_next(node); node-&gt;set_prev(list); } else { while (list-&gt;get_next()) { list = list-&gt;get_next(); } list-&gt;set_next(node); node-&gt;set_prev(list); } return node; } node* LL::pop_front(node* list) { //node* tmp = list; list = list-&gt;get_next(); list-&gt;set_prev(nullptr); //delete[] tmp; return list; } void LL::pop_back(node* list) { node* tmp; if (list-&gt;get_next() == nullptr) { //tmp = list; list = list-&gt;get_prev(); list-&gt;set_next(nullptr); } else { while (list-&gt;get_next()) { list = list-&gt;get_next(); } //tmp = list; list = list-&gt;get_prev(); list-&gt;set_next(nullptr); } //delete[] tmp; } void LL::append_before(node* list, node* n, int selection) { int count = 0; while (count != (selection - 1)) { list = list-&gt;get_next(); count++; } n-&gt;set_next(list); n-&gt;set_prev(list-&gt;get_prev()); node* tmp = list-&gt;get_prev(); tmp-&gt;set_next(n); list-&gt;set_prev(n); } void LL::append_after(node* list, node* n, int selection) { int count = 0; while (count != (selection - 1)) { list = list-&gt;get_next(); count++; } n-&gt;set_next(list-&gt;get_next()); node* tmp = list-&gt;get_next(); tmp-&gt;set_prev(n); n-&gt;set_prev(list); list-&gt;set_next(n); } //View list functions void LL::front_list(node* list) { if (list-&gt;get_prev() == nullptr) { printf(&quot;The data at the front of the list is %d \n&quot;, list-&gt;get_data()); } else { while (list-&gt;get_prev()) { list = list-&gt;get_prev(); } printf(&quot;The data at the front of the list is %d \n&quot;, list-&gt;get_data()); } } void LL::back_list(node* list) { if (list-&gt;get_next() == nullptr) { printf(&quot;The data at the back of the list is %d \n&quot;, list-&gt;get_data()); } else { while (list-&gt;get_next()) { list = list-&gt;get_next(); } printf(&quot;The data at the back of the list is %d \n&quot;, list-&gt;get_data()); } } void LL::print_fwd(node* list) { int count = 0; while (list) { printf(&quot;count [%d] : %d \n&quot;, count, list-&gt;get_data()); list = list-&gt;get_next(); count++; } } void LL::print_bwd(node* list) { int count = 0; while (list-&gt;get_next()) { list = list-&gt;get_next(); count++; } while (list) { printf(&quot;count [%d] : %d \n&quot;, count, list-&gt;get_data()); list = list-&gt;get_prev(); count--; } } void LL::list_selected(node* list, int selection) { int count = 0; while (count != (selection - 1)) { list = list-&gt;get_next(); count++; } printf(&quot;node %d: [%d] %d \n&quot;, selection, (selection - 1), list-&gt;get_data()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T03:30:04.757", "Id": "455349", "Score": "0", "body": "Welcome to CodeReview@SE. Conventionally, questions are [titled for the task to accomplish](https://codereview.stackexchange.com/help/how-to-ask). (And the first advice as to your code may be that code should tell what everything is there for.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T04:40:52.103", "Id": "455355", "Score": "0", "body": "The copy constructor and copy assignment operators perform shallow copies (both objects will point to the same list data), and the copy assignment leaks memory used by the existing (`this`) object. `delete[] this;` does not belong in a destructor. Correct these bugs, then [edit] your question to include the fixed code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T07:34:14.253", "Id": "455365", "Score": "0", "body": "You should have a look at this question: [My first implementation of a linked list in C++](https://codereview.stackexchange.com/q/125955/507)" } ]
[ { "body": "<h2>Overview</h2>\n\n<p>I don't like that a <code>LL</code> is a <code>node</code>.<br>\nA linked list contains nodes. But the list itself is not a node.</p>\n\n<p>The LL missed the rule of three.</p>\n\n<pre><code>LL x;\nLL y(x); // You did not define a copy constructor\n // But this is still allowed (look up rule of three).\n // Normally this is an advantage. BUT if your class\n // contains RAW owned pointers then this will probably cause UB\n // because both x and y will try and delete the same list.\n</code></pre>\n\n<p>Most of the linked list functionality for manipulating list would break unless used in very specific ways. So these function should all be private and only used internally.</p>\n\n<p>So I think this code is very broken.</p>\n\n<h2>Compiler Warnings:</h2>\n\n<pre><code>x2.cpp:59:14: warning: unused parameter 'head' [-Wunused-parameter]\nLL(node* head, node* tail) : head(nullptr), tail(nullptr) { printf(\"LL constructor with assignments \\n\"); }\n ^^^^ ^^^^\n ^\nx2.cpp:150:11: warning: unused variable 'tmp' [-Wunused-variable]\nnode* tmp;\n ^^^\n</code></pre>\n\n<p>Well the unused arguments look like a bug.<br>\nThe unused variables is just sloppy and should be removed.</p>\n\n<p>But this tells me you compile without warning tunred on. <strong>TURN THE ON NOW</strong>. Not just for this project but make your default projects settings have a higher warning level and you will catch errors like this.</p>\n\n<p>Personally I treat all warnings as errors (There is a flag to do this in VS). I would advice everybody to do the same. C++ warnings are usually a logical error in your thinking. Fix the code so your code is warning free.</p>\n\n<hr>\n\n<h2>Codes Review</h2>\n\n<h3>C Headers?</h3>\n\n<p>Why are we include C headers in C++ code?</p>\n\n<pre><code> #include &lt;stdio.h&gt;\n</code></pre>\n\n<hr>\n\n<h3>Windows specific.</h3>\n\n<pre><code> #pragma once\n</code></pre>\n\n<p>Sure if you don't want anybody else to use your code and never plan on working on other platforms. I would bet most professional developers (OK I guess I don't have any number on \"most\" so its hyperbolic but there are a few (not an insignificant)) use Linux.</p>\n\n<p>Learn to use macro guards (until we add better modules to the language and we can stop using this frail old hangover from the 60s).</p>\n\n<hr>\n\n<h3>Const over constexpr</h3>\n\n<pre><code>const int UnkD = 999;//Variable for node() default constructor init\n</code></pre>\n\n<p>The <code>constexpr</code> has been part of the language for a while now. I think the standard advice is to use <code>contexpr</code> where you can and <code>const</code> if not (when creating global state). </p>\n\n<p>Its good that is non mutable :-)</p>\n\n<h3>Node</h3>\n\n<pre><code>class node {\n</code></pre>\n\n<p>A node of <code>int</code> is not very interesting. You should have <code>templated</code> this. That way the data object could have been any type. OK my following comments may assume you have templated this (as I assume you will in the long term). That makes the review more interesting.</p>\n\n<p>Secondly its sort of standard to name \"user\" types with an upper case first letter. This helps you spot variables and types more easily in the code.</p>\n\n<p>Note: \"sort of\" there is no one true standard. But this is a common practice.</p>\n\n<h3>Constructors</h3>\n\n<p>Stop adding us-less comments.</p>\n\n<pre><code>// Default Constructor (I moved it so you could see it)\nnode() : data(UnkD), prev(nullptr), next(nullptr) { printf(\"default node() ctor called... \\n\"); } \n</code></pre>\n\n<p>I know its a default constructor. Comments rote over time. Unless they are meaningful and useful in some way they will cause confusion when they become out of sync with the code.</p>\n\n<hr>\n\n<p>Less printing in constructors. At least put them in macros for debugging.</p>\n\n<pre><code> node() : data(UnkD), prev(nullptr), next(nullptr)\n {\n #if defined(DEBUG)\n printf(\"default node() ctor called... \\n\");\n #endif\n }\n</code></pre>\n\n<hr>\n\n<p>This one is a tiny bit long for a single line.</p>\n\n<pre><code> node(const int &amp; d,node* p,node* n): data(d), prev(p), next(n) { printf(\"node() ctor with args called... \\n\"); } //Constructor With Args\n</code></pre>\n\n<p>But that's mostly to do with the print. If you take that out I would not have cared that it was one line.</p>\n\n<hr>\n\n<p>You were using the initializer list above. Why have you not used it here?</p>\n\n<pre><code> node(const node&amp; rhs) {\n printf(\"node() copy ctor called... \\n\"); \n data = rhs.data;\n prev = rhs.prev;\n next = rhs.next;\n }; //Copy Constructor Again with the useless comment.\n</code></pre>\n\n<p>Here you have let the members be default constructed then copied over them. OK sure if the data type is <code>int</code> the default construction is going to usually be no action. But think into the future when its not an int type. You are pauing to initialize the data object then the first thing you do in the code is copy over it using the assignment operator. That seems like a waste.</p>\n\n<p>Be consistent and always use the initializer list:</p>\n\n<pre><code> node(const node&amp; rhs)\n : data(rhs.data)\n , prev(rhs.prev)\n , next(rhs.next)\n {\n #if defined(DEBUG)\n printf(\"node() copy ctor called... \\n\"); \n #endif\n };\n</code></pre>\n\n<hr>\n\n<p>Learn the copy and swap idiom.</p>\n\n<pre><code> node &amp; operator = (const node&amp; rhs) { //Copy Operator\n printf(\"Copy Operator\");\n if (this != &amp;rhs) {\n data = rhs.data;\n prev = rhs.prev;\n next = rhs.next;\n }\n return *this;\n }\n</code></pre>\n\n<p>I would have written like this:</p>\n\n<pre><code> node&amp; operator=(node const&amp; rhs)\n {\n node tmp(rhs) // Copy\n rhs.swap(*this); // Swap\n // Note there is no test for self assignment.\n // This will help because you have no test\n // Optimizes the normal behavior (usually not a self assignment)\n // Does pessimism because self assignment (but that is so rare not a concern)\n return *this;\n }\n void swap(node&amp; other) noexcept\n {\n using std::swap;\n swap(data, other.data);\n swap(prev, other.prev);\n swap(next, other.next);\n }\n friend void swap(node&amp; lhs, node&amp; rhs)\n {\n lhs.swap(rhs);\n }\n</code></pre>\n\n<hr>\n\n<p>Why did you leave out the move semantics for a node?</p>\n\n<pre><code> node(node&amp;&amp; rhs) noexcept\n : data{}\n , prev(nullptr)\n , next(nullptr)\n {\n rhs.swap(*this);\n }\n node&amp; operator=(node&amp;&amp; rhs) noexcept\n {\n rhs.swap(*this); \n return *this;\n }\n</code></pre>\n\n<h3>Why is the destructor not next to constructor?</h3>\n\n<pre><code> ~node() { printf(\"~node() dtor called...\\n\"); delete[] this; };\n</code></pre>\n\n<p>Place the construction/destruction all in the same place. So you can see it all works together.</p>\n\n<h3>Getters/Setters</h3>\n\n<p>Normally I say these are bad. But property bag so a resonable implementation. Though I would not particularly bother myself here.</p>\n\n<pre><code> void set_data(int x) { data = x; }\n</code></pre>\n\n<p>If you had templatized the data type. Then I would make sure you have a copy and move version of <code>set_data()</code> (snake case!! is this python?).</p>\n\n<p>When returning data you are not modifying the state.</p>\n\n<pre><code> int get_data() { return this-&gt;data; }\n</code></pre>\n\n<p>Thus you method should be marked <code>const</code>. That way if your node is passed by const reference into a function you could still use the fundtion to get the value out.</p>\n\n<p>If you had templatized the data type. Then I would return by reference (and a version for const reference) to avoid an extra copy. Not really an issue when simply returning an int but for larger types returning by value would cause a copy.</p>\n\n<pre><code> int&amp; get_data() { return data; }\n int const&amp; get_data() const { return data; }\n</code></pre>\n\n<hr>\n\n<p>Sure pretty standard.<br>\nWould not bother myself.</p>\n\n<pre><code> void set_prev(node* node) { prev = node; }\n void set_next(node* node) { next = node; }\n node* get_prev() { return this-&gt;prev; }\n node* get_next() { return this-&gt;next; }\n</code></pre>\n\n<h3>Try not to use <code>this-&gt;</code></h3>\n\n<p>You don't need to use <code>this-&gt;</code> in a method. The compiler will get them member (unless you have shadowed it by declaring a local variable of the same name).</p>\n\n<p>BUT shadowing is bad practice. It means you have been lazy in naming your variables and leads to you having to differentiate the two with <code>this-&gt;</code>. The trouble here is that if you use the wrong name the compiler can't tell its the wrong one and thus you get no warnings. If you make sure the names are all distinct you can't make this type of error.</p>\n\n<p>And bonus the compiler will warn you about shadowing.</p>\n\n<hr>\n\n<h2>LL</h2>\n\n<p>LL is not a node.</p>\n\n<pre><code>class LL: public node {\n</code></pre>\n\n<p>The LL contains a list of nodes but is not one itself.</p>\n\n<hr>\n\n<p>Same comments as above on printing.</p>\n\n<pre><code> LL() : head(nullptr), tail(nullptr) { printf(\"LL deault constructor \\n\"); }\n LL(node* head, node* tail) : head(nullptr), tail(nullptr) { printf(\"LL constructor with assignments \\n\"); }\n</code></pre>\n\n<hr>\n\n<p>Same comment as above put the destructor close to the constructor so we can see we are creating and correctly destroying the object in the same area of the file.</p>\n\n<pre><code> ~LL() {\n printf(\"LL destructor \\n\");\n while (head)\n {\n node* tmp = head-&gt;get_next();\n delete[] tmp;\n }\n }\n</code></pre>\n\n<p>That defiantly looks wrong.</p>\n\n<ol>\n<li>There is no removing links for the chain.</li>\n<li>There is no moving of head forward.</li>\n<li>You are using <code>delete[]</code> to delete a single item.</li>\n</ol>\n\n<hr>\n\n<p>You missed the rule of three here.</p>\n\n<p>If you do not define a copy constructor or copy assignment operator then the compiler will generate one for you. The compiler generated version of these functions does a simple shallow copy of the object (which is normally perfect).</p>\n\n<p>But when your object contains RAW pointers this means both object now contain the same pointers. The problem arises when these pointers are owned by the object. This means that the object should be calling delete on the destructor which means both object will call delete on the points (a double delete on a pointer is UB).</p>\n\n<h3>List Interface.</h3>\n\n<p>The internals (or how head/tail are implemented) is an internal part of <code>LL</code> yet here you are leaking the abstraction of <code>node</code> out of the list. </p>\n\n<pre><code> void set_head(node* node) { head = node; }\n void set_tail(node* node) { tail = node; }\n node* get_head() { return this-&gt;head; }\n node* get_tail() { return this-&gt;tail; }\n\n //Create and Destroy Fucntions\n node* create_node(int d);\n void delete_list(node* list);\n void delete_selected(node* list, int selection);\n\n //Add and Remove Node Functions\n node* push_front(node* list, node* node);\n node* push_back(node* list, node* node);\n node* pop_front(node* list);\n void pop_back(node* list);\n void append_before(node* list, node* node, int selection);\n void append_after(node* list, node* node, int selection);\n\n //View List Functions\n void front_list(node* list);\n void back_list(node* list);\n void print_fwd(node* list);\n void print_bwd(node* list);\n void list_selected(node* list, int selection);\n</code></pre>\n\n<p>When interacting with a linked list I would be more inclined to add values of the data type (int until you upgrade node to be templated). I should simply be able to add values to the list and remove values from the list (and retrieve from the ends I suppose).</p>\n\n<p>I definately would not be allowing the customer to crate and pass pointers around.</p>\n\n<p>My interface would have looked like:</p>\n\n<pre><code> void push_front(T const&amp; value); // copy a value to the front.\n void push_front(T&amp;&amp; value); // move a value to the front.\n void push_back(T const&amp; value); // copy a value to the back.\n void push_back(T&amp;&amp; value); // move a value to the back.\n\n T const&amp; get_front() const; // get a const reference to the front\n T&amp; get_front(); // get a reference to the front\n T const&amp; get_back() const; // get a const reference to the front\n T&amp; get_back(); // get a reference to the front\n\n void pop_front(); // pop the front of the list.\n void pop_back(); // pop the back of the list.\n\n bool empty() const; // check if the list is empty.\n std::size_t size() const; // get the size of the list.\n\n // Ignore iterators for version 1 we can do those after you fix up this\n</code></pre>\n\n<h2> // version and make it better.</h2>\n\n<p>This should be a private member.</p>\n\n<pre><code>node* LL::create_node(int d) { return new node{ d, nullptr, nullptr }; }\n</code></pre>\n\n<hr>\n\n<p>This is a bug. Same reason as the destructor.</p>\n\n<pre><code>void LL::delete_list(node* list) {\n while (list)\n {\n node* tmp = list;\n list = list-&gt;get_next();\n delete[] tmp;\n }\n printf(\"List Deleted. \\n\");\n}\n</code></pre>\n\n<p>Note when you have repeated code like this (here and destructor). Then you should be re-using function. Basically the destructor should call this not have the same code repeated. Taht way when you fix an error you only need to fix it in one place.</p>\n\n<hr>\n\n<pre><code> // You are not checking that list does not slip of the end of the list.\n while (count != (selection - 1)) {\n list = list-&gt;get_next();\n count++;\n }\n</code></pre>\n\n<p>If list becomes <code>nullptr</code> then calling <code>get_next()</code> will be UB.</p>\n\n<hr>\n\n<p>Wrong version of delete. </p>\n\n<pre><code> //delete[] tmp;\n</code></pre>\n\n<p>It should be</p>\n\n<pre><code> delete tmp;\n</code></pre>\n\n<hr>\n\n<p>This function assumes that <code>list</code> is the head of the list.</p>\n\n<pre><code>node* LL::push_front(node* list, node* node) {\n if (!list) { return node; }\n\n node-&gt;set_next(list);\n list-&gt;set_prev(node); // If list is not the head this overwrites a value.\n list = node;\n</code></pre>\n\n<p>You also make no effort to update <code>tail</code>. </p>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T19:20:33.077", "Id": "456089", "Score": "0", "body": "Thank you for this detailed review and critique of my code. I will work through this and improve upon my code. Once i do that i will respond with it and hopefully have you critique it once more." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T06:31:29.203", "Id": "233048", "ParentId": "233038", "Score": "2" } } ]
{ "AcceptedAnswerId": "233048", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T02:34:37.437", "Id": "233038", "Score": "0", "Tags": [ "c++", "object-oriented", "linked-list", "inheritance" ], "Title": "C++ linked list inheriting from node class" }
233038
<h1>Raku (previously known as Perl 6)</h1> <p>Raku is a new language in the Perl family (instead of simply being the version after Perl 5). The names "Raku," "Perl 6," and "Raku Perl 6" all refer to the same language, but the preferred name now is Raku.</p> <p>A few of Raku's distinguishing features:</p> <ul> <li>Procedural, object-oriented, and functional programming methodologies all built-in and working seamlessly together</li> <li>Extensive Unicode support from code points to grapheme clusters</li> <li>Grammars (more powerful and useful than regular expressions)</li> <li>Type system</li> <li>Multiple dispatch</li> <li>Introspection</li> <li>Concurrent, parallel, and asynchronous processing support</li> <li>Use of rational numbers to avoid floating-point problems</li> </ul> <p><a href="/questions/tagged/rakudo" class="post-tag" title="show questions tagged &#39;rakudo&#39;" rel="tag">rakudo</a> is a Raku implementation that targets multiple back ends. Currently only the <a href="http://www.moarvm.com" rel="nofollow noreferrer">MoarVM</a> back end is recommended for normal use, but back ends for the Java Virtual Machine and JavaScript are also under <a href="https://github.com/perl6/nqp/tree/master/src/vm" rel="nofollow noreferrer">active development</a>.</p> <p>The Rakudo implementation of Raku shipped <a href="https://perl6advent.wordpress.com/2015/12/25/christmas-is-here/" rel="nofollow noreferrer">a first official release named “коледа”</a> on December 25, 2015. Most of the specification is frozen, and optimizations are ongoing. </p> <h3>Official links</h3> <ul> <li><a href="http://perl6intro.com/" rel="nofollow noreferrer">Introduction to Perl 6</a>, by Naoum Hankache</li> <li><a href="http://perl6.org" rel="nofollow noreferrer">Perl 6 homepage</a></li> <li><a href="http://perl6.org/resources" rel="nofollow noreferrer">Perl 6 resources</a> </li> <li><a href="https://docs.perl6.org" rel="nofollow noreferrer">Perl 6 documentation</a>; temporarily Raku documentation is at <a href="https://rakudocs.github.io" rel="nofollow noreferrer">https://rakudocs.github.io</a> </li> <li><a href="https://doc.perl6.org/language/faq#Why_should_I_learn_Perl_6%3F_What%27s_so_great_about_it%3F" rel="nofollow noreferrer">Why should I learn Perl 6? What's so great about it?</a></li> <li><a href="https://perl6book.com/" rel="nofollow noreferrer">Perl 6 books</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T02:53:43.417", "Id": "233039", "Score": "0", "Tags": null, "Title": null }
233039
For questions relating to the Raku programming language (formerly known as Perl 6).
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T02:53:43.417", "Id": "233040", "Score": "0", "Tags": null, "Title": null }
233040
<p>I was wondering if you could please comment on code quality, correct usage of c++17 constructs, stl/c++ compliant api, performance, or anything else that you might find relevant.</p> <p>Also do you think that this class should be move assignable/constructible? What would be a good approach to go about implementing say, copy-and-swap on this without hurting the <code>timer::Timer::consume</code> function too much?</p> <p>main.cc:</p> <pre><code>#include &lt;unistd.h&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include "timer.h" int main() { timer::Timer t; auto t1 = t.schedule( std::chrono::steady_clock::now() + std::chrono::seconds(1), []() { std::cout &lt;&lt; "hello 1 after a sec" &lt;&lt; std::endl; }); auto t2 = t.schedule( std::chrono::steady_clock::now() + std::chrono::seconds(3), [](int n) { std::cout &lt;&lt; "hello " &lt;&lt; n &lt;&lt; " after "&lt;&lt; n &lt;&lt; std::endl; }, 3); auto t3 = t.schedule( std::chrono::steady_clock::now() + std::chrono::seconds(2), [](const std::string&amp; s) { std::cout &lt;&lt; "hello " &lt;&lt; s &lt;&lt; " after " &lt;&lt; s &lt;&lt; std::endl; }, "2"); t1.get().join(); t2.get().join(); t3.get().join(); t.stop(); return 0; } </code></pre> <p>timer.h:</p> <pre><code>#ifndef TIMER_H_ #define TIMER_H_ #include &lt;queue&gt; #include &lt;tuple&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;utility&gt; #include &lt;thread&gt; #include &lt;functional&gt; #include &lt;condition_variable&gt; #include &lt;future&gt; namespace timer { class Timer { public: Timer(); template&lt;typename Function, typename... Args&gt; std::future&lt;std::thread&gt; schedule( const std::chrono::steady_clock::time_point tp, Function&amp;&amp; func, Args&amp;&amp;... args) { std::promise&lt;std::thread&gt; pr; auto ret = pr.get_future(); auto callable = std::bind(std::forward&lt;Function&gt;(func), std::forward&lt;Args&gt;(args)...); { std::lock_guard&lt;decltype(m_)&gt; lk(m_); pq_.push(std::move((struct scheduled_task) { .tp = tp, .f = std::move([inner_callable = std::move(callable)] { inner_callable(); }), .pr = std::move(pr) })); cv_.notify_one(); } return ret; } ~Timer(); Timer(const Timer&amp;) = delete; Timer&amp; operator=(const Timer&amp;) = delete; Timer(const Timer&amp;&amp; other) = delete; Timer&amp; operator=(const Timer&amp;&amp; other) = delete; void stop(); private: struct scheduled_task { std::chrono::steady_clock::time_point tp; std::function&lt;void()&gt; f; std::promise&lt;std::thread&gt; pr; }; struct scheduled_task_cmptor { public: bool operator()(const scheduled_task&amp; lhs, const scheduled_task&amp; rhs) const { // return std::get&lt;0&gt;(rhs) &lt; std::get&lt;0&gt;(lhs); return lhs.tp &gt; rhs.tp; } }; std::priority_queue&lt;scheduled_task, std::vector&lt;scheduled_task&gt;, scheduled_task_cmptor&gt; pq_; void consume(); std::atomic&lt;bool&gt; keep_consuming_; std::mutex m_; std::condition_variable cv_; std::thread scheduler_; }; } // namespace timer #endif // TIMER_H_ </code></pre> <p>timer.cc:</p> <pre><code>#include "timer.h" #include &lt;iostream&gt; #include &lt;atomic&gt; #include &lt;utility&gt; namespace timer { Timer::Timer() : keep_consuming_(true), scheduler_(&amp;Timer::consume, this) { } Timer::~Timer() { stop(); } void Timer::consume() { while (keep_consuming_) { { std::unique_lock&lt;decltype(m_)&gt; lk(m_); cv_.wait(lk, [this] { return pq_.size() &gt; 0 || !keep_consuming_; }); } if (!keep_consuming_) { break; } { std::unique_lock&lt;decltype(m_)&gt; lk(m_); cv_.wait_until(lk, pq_.top().tp, [this] { return pq_.top().tp &lt;= std::chrono::steady_clock::now() || !keep_consuming_; }); } if (!keep_consuming_) { break; } { std::lock_guard&lt;decltype(m_)&gt; lk(m_); auto&amp; task = pq_.top(); std::thread t(std::move(task.f)); const_cast&lt;std::promise&lt;std::thread&gt;&amp;&gt;(task.pr).set_value( std::move(t)); pq_.pop(); } } } void Timer::stop() { if (keep_consuming_) { keep_consuming_ = false; cv_.notify_one(); scheduler_.join(); } } } // namespace timer <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T12:45:41.073", "Id": "455396", "Score": "0", "body": "I feel like I'm missing something. What is the advantage of your code over `auto t1 = std::async(std::launch::async, [] { std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << \"hello 1 after a sec\\n\"; });`? It appears to do the same with a lot less code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T15:59:28.297", "Id": "455441", "Score": "0", "body": "Hmm I see your point, two things:\nThe execution flow is not passed off to the environment, meaning I can decide abort the jobs that haven't started by destroying the Timer.\nAlso I think with launching the threads right away we're creating more than optimal (say = total number of tasks) threads at some point of time, as opposed to using a tighter bound of maximum that actually need to exist at the same time." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T03:24:51.930", "Id": "233042", "Score": "0", "Tags": [ "c++", "c++11", "c++17" ], "Title": "Scheduling threads to run at a particular time" }
233042
<p>The code below will scrape data from three APIs. The APIs are for property listings. So, for each listing, I will have one request. There will be around 20000 requests. That's why I use ayncio to make the request. However, I will be banned by their server if I request frequently. So, I use Tor and user-agent to get rid of that.</p> <p>The data I scraped will be stored in MongoDB. </p> <p>I learnt Python by myself. I am wondering if the code can be further improved.</p> <pre><code>import time import math import json from bson import json_util #for import into mongodb from datetime import datetime import requests from stem import Signal from stem.control import Controller from fake_useragent import UserAgent import aiohttp from aiohttp import ClientSession import asyncio from aiohttp_socks import SocksConnector, SocksVer import pandas as pd import pymongo from pymongo import MongoClient #https://boredhacking.com/tor-webscraping-proxy/ #https://www.unixmen.com/run-tor-service-arch-linux/ #https://www.sylvaindurand.org/use-tor-with-python/ #https://stem.torproject.org/faq.html (autheticate) client = pymongo.MongoClient('localhost',37017)# db = client.centaline db_propertyInfo = db.propertyInfo db_propertyDetails = db.propertyDetails db_buildingInfo = db.buldingInfo current_time = datetime.now() propertyInfo = "https://hkapi.centanet.com/api/FindProperty/MapV2.json?postType={}&amp;order=desc&amp;page={}&amp;pageSize={}&amp;pixelHeight=2220&amp;pixelWidth=1080&amp;sort=score&amp;wholeTerr=1&amp;platform=android" propertyDetails = "https://hkapi.centanet.com/api/FindProperty/DetailV2.json?id={}&amp;platform=android" buildingInfo = "https://hkapi.centanet.com/api/PropertyInfo/Detail.json?cblgcode={}&amp;cestcode={}&amp;platform=android" headers = {"User_Agent":UserAgent().random, "Host":"hkapi.centanet.com", "Content-Type":"application/json; charset=UTF-8"} def switchIP(): with Controller.from_port(port = 9051) as controller: controller.authenticate() controller.signal(Signal.NEWNYM) def numOfRecords(postType): switchIP() session = requests.session() session.proxies = {} session.proxies['http'] = 'socks5://localhost:9050' session.proxies['https'] = 'socks5://localhost:9050' data = session.post(propertyInfo.format(postType, 1,1), headers = headers) #page=1 pageSize=1 data = json.loads(data.text) data = data["DItems"] data = pd.DataFrame.from_records(data) totalRecords = data["Count"].sum() print("Total number of records for {}: {}".format(postType, totalRecords)) return totalRecords async def getPropertyInfo(postType, page, pageSize, session): while True: try: async with session.post(propertyInfo.format(postType, page, pageSize), headers = headers) as resp: print("started inserting property info") data = await resp.text() data = json.loads(data) for idx, item in enumerate(data['AItems']): item["DateTime"] = current_time item["Source"] = "centaline" db_propertyInfo.insert_one(item) switchIP() break except Exception as e: print(str(e)) print("Retry Property Info") async def bound_getPropertyInfo(semaphore, postType, page, pageSize, session): async with semaphore: await getPropertyInfo(postType, page, pageSize, session) pageSize = 1 #noOfPages_s = math.ceil(numOfRecords('s')/pageSize) #noOfPages_r = math.ceil(numOfRecords('r')/pageSize) noOfPages_s = 1 noOfPages_r = 0 async def run_info(): tasks = [] socks = 'socks5://localhost:9050' connector = SocksConnector.from_url(socks) semaphore = asyncio.Semaphore(50) async with ClientSession(connector = connector) as session: for page in range(noOfPages_s): task = asyncio.ensure_future(bound_getPropertyInfo(semaphore, 's', page+1, pageSize, session)) tasks.append(task) for page in range(noOfPages_r): task = asyncio.ensure_future(bound_getPropertyInfo(semaphore, 'r', page+1, pageSize, session)) tasks.append(task) response = await asyncio.gather(*tasks) loop = asyncio.get_event_loop() future = asyncio.ensure_future(run_info()) loop.run_until_complete(future) id_list = db_propertyInfo.distinct("ID", {"DateTime": current_time}) cblgcode_list = db_propertyInfo.distinct("CblgCode", {"DateTime": current_time}) cestcode_list = db_propertyInfo.distinct("Cestcode", {"DateTime": current_time}) async def fetch(url, session, socks, db): while True: try: async with session.post(url, headers = headers) as resp: data = await resp.text() switchIP() data = json.loads(data) data["DateTime"] = current_time data["Source"] = "centaline" db.insert_one(data) print("Inserting Data") break return data except Exception as e: print(str(e)) if data.find("Sequence contains no elements") != -1: break else: print(url) print("Retry One Property Details") async def bound_fetch(semaphore, url, session, socks, db): async with semaphore: return await fetch(url, session, socks, db) async def run(): tasks = [] socks = 'socks5://localhost:9050' connector = SocksConnector.from_url(socks) semaphore = asyncio.Semaphore(100) async with ClientSession(connector = connector) as session: for i in id_list: url = propertyDetails.format(i) task = asyncio.ensure_future(bound_fetch(semaphore, url, session, socks, db_propertyDetails)) tasks.append(task) for j,k in zip(cblgcode_list, cestcode_list): url = buildingInfo.format(j,k) task = asyncio.ensure_future(bound_fetch(semaphore, url, session, socks, db_buildingInfo)) tasks.append(task) response = await asyncio.gather(*tasks) loop = asyncio.get_event_loop() future = asyncio.ensure_future(run()) loop.run_until_complete(future) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T08:12:19.773", "Id": "455368", "Score": "1", "body": "Welcome to Code Review! This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T08:22:17.917", "Id": "455370", "Score": "1", "body": "@TobySpeight Modified" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T22:57:25.213", "Id": "455831", "Score": "1", "body": "This code is doing a lot. Depending on how the script is run, it could use `torsocks` which would do the tor routing for you. The script would then be invoked via `torsocks python3 script.py`, then the code for routing to tor could be removed." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T03:33:42.700", "Id": "233043", "Score": "2", "Tags": [ "python", "asynchronous" ], "Title": "Python Async Reqeust using Tor and User-Agent Rotation" }
233043
<p>Here is an earlier attempt to solve the original problem: <a href="https://codereview.stackexchange.com/questions/192657/solving-sierpinski-triangle-in-haskell">Solving Sierpinski Triangle in Haskell</a></p> <p>I was never satisfied with my solution and found it was awkward and twisty. Here is another attempt to solve the same problem using Data.Array and I found that by using mutable arrays the solution becomes much shorter and easy to read. </p> <pre><code>import qualified Data.Array as DA (Array, listArray, (//), assocs) import qualified Data.List as DL (groupBy, intercalate) import qualified Data.Function as DF (on) type Point = (Int, Int) data Triangle = Triangle { up :: Point, height :: Int } deriving Show type Canvas = DA.Array Point Char emptyCanvas maxLevel = DA.listArray ((0, 1-h), (h-1, h-1)) $ repeat '_' where h = 2^maxLevel -- 1*(2^maxLevel) drawTriangle :: Triangle -&gt; Canvas -&gt; Canvas drawTriangle (Triangle (r, c) h) canvas = foldr drawLine canvas $ map line [1..h] where line h = let h' = h-1 in [(r+h', j) | j &lt;- [c-h'..c+h']] drawLine l c = c DA.// map (\p -&gt; (p, '1')) l drawCanvas :: Canvas -&gt; IO () drawCanvas canvas = putStrLn pic where rows = DL.groupBy ((==) `DF.on` (fst . fst)) . DA.assocs pic = DL.intercalate "\n" $ map (map snd) (rows canvas) split hLvl (r, c) = let w = 2^(hLvl-1) in [(r, c), (r+w, c-w), (r+w, c+w)] splitSier maxLevel (sierLevel, ts) = (sierLevel+1, ts') where ts' = ts &gt;&gt;= (split (maxLevel-sierLevel)) mkSierpinski :: Int -&gt; Int -&gt; Canvas mkSierpinski maxLevel sierLevel | maxLevel &gt;= sierLevel = foldr drawTriangle c $ allTriangles | otherwise = c where c = emptyCanvas maxLevel (l', ts') = head $ drop sierLevel $ iterate (splitSier maxLevel) (0, [(0, 0)]) allTriangles = map (\p -&gt; Triangle p (2^(maxLevel-l'))) ts' main = do sierLevel &lt;- readLn drawCanvas $ mkSierpinski 5 sierLevel </code></pre> <p>The idea is to model the canvas by a 2-D array of Characters and attempt to draw easy individual triangles on top of the empty canvas. In this solution it starts with one big triangle and keep splitting to generate Sierpinski pattern. Another solution that I didn't post here attempts to solve it by starting with the smallest triangle at the top, and repeatedly copy what is current on canvas to its lower left corner and lower right corner. Both solutions look very similar at the end. </p> <p>Please let me know if you have suggestions. Thank you in advance. </p>
[]
[ { "body": "<p><code>//</code> is best called with one bulk list because each call incurs one O(n) array copy.</p>\n\n<p>Folds over iterates when you need an index and know its range, it's like for vs. while.</p>\n\n<pre><code>drawCanvas :: Canvas -&gt; IO ()\ndrawCanvas = putStrLn . unlines . map (map snd)\n . DL.groupBy ((==) `DF.on` fst . fst) . DA.assocs\n\nmkSierpinski :: Int -&gt; Int -&gt; Canvas\nmkSierpinski maxLevel sierLevel = emptyCanvas maxLevel DA.//\n [ ((r+h, j), '1')\n | maxLevel &gt;= sierLevel\n , (r, c) &lt;- DF.foldrM split (0, 0) [maxLevel-sierLevel+1..maxLevel]\n , h &lt;- [0..2^(maxLevel-sierLevel)-1]\n , j &lt;- [c-h..c+h]\n ]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T10:11:31.860", "Id": "233055", "ParentId": "233045", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T03:58:29.207", "Id": "233045", "Score": "1", "Tags": [ "beginner", "haskell", "ascii-art" ], "Title": "Using Data.Array to solve Sierpinski in Haskell" }
233045
<p>I am creating back-end for a web-application in Play framework with Java, using Couchbase for storage. This class is saving and fetching <code>User</code> details from Couchbase.</p> <p>My questions are:</p> <ul> <li>Will my DAO implementation work for high volume traffic (thousands of users saving and fetching User details simultaneously)? If not, how can I handle huge traffic? </li> <li>How can it be optimized?</li> </ul> <p><strong>Project details:</strong></p> <ul> <li>scalaVersion: "2.12.4"</li> <li>"com.couchbase.client" % "java-client" % "2.4.2"</li> </ul> <p><strong>Code files:</strong></p> <p><code>AppDaoService</code> interface:</p> <pre><code>import java.util.concurrent.CompletionStage; import com.google.inject.ImplementedBy; @ImplementedBy(AppDaoServiceImpl.class) public interface AppDaoService { public void storeUserData(User user); public CompletionStage&lt;User&gt; getUserData(String userCode); } </code></pre> <p><code>AppDaoServiceImpl</code> class:</p> <pre><code>import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; import com.couchbase.client.java.env.CouchbaseEnvironment; import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; import com.fasterxml.jackson.databind.JsonNode; import com.google.inject.Inject; import com.marriott.exceptions.DataNotFoundException; import com.marriott.exceptions.InternalServerException; import com.typesafe.config.Config; import play.Logger; import play.Logger.ALogger; import play.libs.Json; import play.libs.concurrent.HttpExecutionContext; public class AppDaoServiceImpl implements AppDaoService { private static final ALogger logger = Logger.of(AppDaoServiceImpl.class); private final HttpExecutionContext ec; private final Config config; private Cluster cluster = null; private Bucket bucket = null; private CouchbaseEnvironment env; @Inject public AppDaoServiceImpl(final HttpExecutionContext ec, Config config) { this.config = config; this.ec = ec; env = DefaultCouchbaseEnvironment.builder().build(); cluster = CouchbaseCluster.create(env, config.getString("couchbase.url")); } @Override public void storeUserData(User user) { CompletableFuture.runAsync(() -&gt; { try { bucket = cluster.openBucket(config.getString("couchbase.bucket.name"), config.getString("couchbase.bucket.password")); logger.info("Storing user for userCode: " + user.getUserCode()); String documentId = user.getUserCode() + "_user"; JsonObject jsonObject = JsonObject.fromJson(Json.toJson(user).toString()); bucket.upsert(JsonDocument.create(documentId, jsonObject)); logger.info("Successfully stored userCode: " + user.getUserCode()); } catch (Exception e) { logger.error("Storing userCode: " + user.getUserCode() + " unsuccessful"); throw new InternalServerException(e.getMessage()); } finally { if (!bucket.isClosed()) { bucket.close(); } } }, ec.current()).join(); } @Override public CompletionStage&lt;User&gt; getUserData(String userCode) { return CompletableFuture.supplyAsync(() -&gt; { try { bucket = cluster.openBucket(config.getString("couchbase.bucket.name"), config.getString("couchbase.bucket.password")); logger.info("Fetching user data for userCode:" + userCode); String documentID = userCode + "_user"; JsonDocument retrievedJsonDocument = bucket.get(documentID); if (retrievedJsonDocument != null) { JsonNode json = Json.parse(retrievedJsonDocument.content().toString()); User userData = Json.fromJson(json, User.class); logger.info("Successfully fetched userCode: " + userCode); return userData; } else { logger.error("Fetching userCode:" + userCode + " unsuccessful"); throw new DataNotFoundException("User data not found for userCode: " + userCode); } } catch (Exception e) { throw e; } finally { if (!bucket.isClosed()) { bucket.close(); } } }); } } </code></pre> <p><code>User</code> model class:</p> <pre><code>public class User { private String userCode; private String firstName; private String lastName; private String pinCode; public User(String userCode, String firstName, String lastName, String pinCode) { super(); this.userCode = userCode; this.firstName = firstName; this.lastName = lastName; this.pinCode = pinCode; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPinCode() { return pinCode; } public void setPinCode(String pinCode) { this.pinCode = pinCode; } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-16T14:31:22.793", "Id": "457879", "Score": "0", "body": "This is tagged incorrectly. CouchDB is not Couchbase. I don't have enough reputation here to create a new tag." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T09:20:15.690", "Id": "233051", "Score": "3", "Tags": [ "java", "couchdb" ], "Title": "Playframework Java application, saving user details into Couchbase database" }
233051
<p>This code is used to check <a href="https://wiki.openstreetmap.org/wiki/Key:opening_hours" rel="nofollow noreferrer">opening hours data from OpenStreetMap</a> can be handled by an editor app. In case where opening hours is not too complex data is also turned into an usable form.</p> <p>It is a part of a <a href="https://github.com/westnordost/StreetComplete" rel="nofollow noreferrer">StreetComplete</a> editor app. This specific file will be part of pull request that will add ability to <a href="https://github.com/westnordost/StreetComplete/issues/1651" rel="nofollow noreferrer">resurvey opening hours</a>.</p> <p>Sadly, I had no good idea how to split this file into smaller one so it is quite large with 440 lines. Still, even smallest feedback about part of the code is welcomed - up to and including typos and grammar errors in comments.</p> <p>For context - feature branch for this work, including all changes, is at <a href="https://github.com/westnordost/StreetComplete/compare/master...matkoniecz:resurvey" rel="nofollow noreferrer">https://github.com/westnordost/StreetComplete/compare/master...matkoniecz:resurvey</a></p> <p>Feedback how to split this into smaller parts is also welcomed, but it seemed to me that any subset of this changes will be completely unclear.</p> <p><code>OpeningHoursTagParser.kt</code>:</p> <pre><code>package de.westnordost.streetcomplete.quests.opening_hours import ch.poole.openinghoursparser.* import de.westnordost.streetcomplete.quests.opening_hours.adapter.OpeningMonthsRow import de.westnordost.streetcomplete.quests.opening_hours.adapter.OpeningWeekdaysRow import de.westnordost.streetcomplete.quests.opening_hours.model.CircularSection import de.westnordost.streetcomplete.quests.opening_hours.model.TimeRange import de.westnordost.streetcomplete.quests.opening_hours.model.Weekdays import java.io.ByteArrayInputStream object OpeningHoursTagParser { // returns null for values that are invalid or not representable in // StreetComplete opening hours edit widget // otherwise returns data structure that can be directly used to // initialize this editing widget fun parse(openingHours: String): List&lt;OpeningMonthsRow&gt;? { val rules: ArrayList&lt;Rule&gt; try { val input = ByteArrayInputStream(openingHours.toByteArray()) val parser = OpeningHoursParser(input) rules = parser.rules(false) } catch (e: ParseException) { // parsing failed, value is malformed return null } if (!isRulesetToStreetCompleteSupported(rules)) { // parsable, not handled by StreetComplete return null } return transformStreetCompleteCompatibleRulesetIntoInternalForm(rules) } private fun transformStreetCompleteCompatibleRulesetIntoInternalForm(rules: ArrayList&lt;Rule&gt;): List&lt;OpeningMonthsRow&gt;? { var data = mutableListOf(OpeningMonthsRow()) for (rule in rules) { if (rule.dates != null) { // month based rules, so we need OpeningMonthsRow objects that will be created // and added later rather than a single catch-all row data = mutableListOf() } } for (rule in rules) { var index = 0 val dates = rule.dates if (dates != null) { Assert.assert(dates.size == 1) val start = dates[0].startDate val end = dates[0].endDate ?: start index = getIndexOfOurMonthsRow(data, start.month.ordinal, end.month.ordinal) if (index == -1) { // there is no reusable row matching out entry, we need to create a new one data.add(OpeningMonthsRow(CircularSection(start.month.ordinal, end.month.ordinal))) index = data.size - 1 } } for (time in rule.times!!) { val dayData = daysWhenRuleApplies(rule) data[index].weekdaysList.add(OpeningWeekdaysRow(Weekdays(dayData), TimeRange(time.start, time.end))) } } return data } private fun getIndexOfOurMonthsRow(monthRows: List&lt;OpeningMonthsRow&gt;, startMonth: Int, endMonth: Int): Int { for ((index, row) in monthRows.withIndex()) { if (row.months.start == startMonth) { if (row.months.start == endMonth) { return index } } } return -1 } //returns array that can be used to initialize OpeningWeekdaysRow private fun daysWhenRuleApplies(rule: Rule): BooleanArray { val dayData = BooleanArray(8) { false } Assert.assert(rule.holidays != null || rule.days!!.size &gt;= 0) val days = rule.days if (days != null) { Assert.assert(days.size == 1) val startDay = days[0].startDay val endDay = days[0].endDay ?: startDay // endDay will be null for single day ranges if (startDay &lt;= endDay) { // ranges like Tuesday-Saturday for (day in WeekDay.values()) { if (day &gt;= startDay) { if (day &lt;= endDay) { dayData[day.ordinal] = true } } } } else { // ranges like Saturday-Tuesday for (day in WeekDay.values()) { if (day &lt;= endDay || day &gt;= startDay) { dayData[day.ordinal] = true } } } } val holidays = rule.holidays if (holidays != null) { Assert.assert(holidays.size == 1) Assert.assert(holidays[0].type == Holiday.Type.PH) Assert.assert(holidays[0].offset == 0) Assert.assert(holidays[0].useAsWeekDay) dayData[7] = true } return dayData } // Returns true iff supported by StreetComplete // Returns false otherwise, in cases where it is not directly representable // // It is first checking each rule (parts of opening_hours tag separated by ; sign) // is it possible to recreate it by taking only supported parts // later it checks also some additional limitations imposed by SC private fun isRulesetToStreetCompleteSupported(ruleset: ArrayList&lt;Rule&gt;): Boolean { for (rule in ruleset) { if (reduceRuleToStreetCompleteSupported(rule) == null) { return false } } if (includesMonthsRangeCrossingNewYearBoundary(ruleset)) { // strictly speaking this kind of ranges are supported, but not in an obvious way return false } if (areOnlySomeRulesMonthBased(ruleset)) { // StreetComplete can handle month based rules, but requires all of them to be month based return false } if (rulesAreOverridingOtherRules(ruleset)) { // this kind of opening hours specification likely require fix // anyway, it is not representable directly by SC return false } return true } private fun includesMonthsRangeCrossingNewYearBoundary(ruleset: ArrayList&lt;Rule&gt;): Boolean { for (rule in ruleset) { val dates = rule.dates if (dates != null) { Assert.assert(dates.size == 1) val endDate = dates[0].endDate if (endDate != null) { if (dates[0].startDate.month &gt; endDate.month) { return true } } } } return false } private fun rulesAreOverridingOtherRules(ruleset: ArrayList&lt;Rule&gt;): Boolean { for (checkedRuleIndex in 0 until ruleset.size) { for (competingRuleIndex in 0 until ruleset.size) { if (checkedRuleIndex != competingRuleIndex) { if (ruleset[checkedRuleIndex].dates != null) { Assert.assert(ruleset[competingRuleIndex].dates != null) val checkedRuleDate = ruleset[checkedRuleIndex].dates val competingRuleDate = ruleset[competingRuleIndex].dates Assert.assert(checkedRuleDate!!.size == 1) Assert.assert(competingRuleDate!!.size == 1) val firstDateRange = checkedRuleDate[0] val secondDateRange = competingRuleDate[0] if (areMonthRangesIntersecting(firstDateRange, secondDateRange)) { return areDayRangesIntersecting(ruleset[checkedRuleIndex], ruleset[competingRuleIndex]) } } else { Assert.assert(ruleset[competingRuleIndex].dates == null) return areDayRangesIntersecting(ruleset[checkedRuleIndex], ruleset[competingRuleIndex]) } } } } return false } private fun areDayRangesIntersecting(ruleA: Rule, ruleB: Rule): Boolean { if (areHolidaysIntersecting(ruleA.holidays, ruleB.holidays)) { return true } val daysA = ruleA.days val daysB = ruleB.days if (daysA == null || daysB == null) { return false } Assert.assert(daysA.size == 1) Assert.assert(daysB.size == 1) val weekDayRangeA = daysA[0] val weekDayRangeB = daysB[0] val startA = weekDayRangeA.startDay val endA = weekDayRangeA.endDay ?: startA val startB = weekDayRangeB.startDay val endB = weekDayRangeB.endDay ?: startB val rangeA = CircularSection(startA.ordinal, endA.ordinal) val rangeB = CircularSection(startB.ordinal, endB.ordinal) return rangeA.intersects(rangeB) } private fun areHolidaysIntersecting(firstHolidays: MutableList&lt;Holiday&gt;?, secondHolidays: MutableList&lt;Holiday&gt;?): Boolean { if (firstHolidays == null || secondHolidays == null) { return false } for (holiday in firstHolidays) { for (holidayCompeting in secondHolidays) { Assert.assert(holiday.useAsWeekDay) Assert.assert(holidayCompeting.useAsWeekDay) Assert.assert(holiday.offset == 0) Assert.assert(holidayCompeting.offset == 0) if (holiday.type == holidayCompeting.type) { return true } } } return false } // all info in dates, except months is ignored! private fun areMonthRangesIntersecting(aDateRange: DateRange?, bDateRange: DateRange?): Boolean { if (aDateRange == null || bDateRange == null) { return false } val startA = aDateRange.startDate val endA = aDateRange.endDate ?: aDateRange.startDate val startB = bDateRange.startDate val endB = bDateRange.endDate ?: bDateRange.startDate val rangeA = CircularSection(startA.month.ordinal, endA.month.ordinal) val rangeB = CircularSection(startB.month.ordinal, endB.month.ordinal) return rangeA.intersects(rangeB) } private fun areOnlySomeRulesMonthBased(ruleset: ArrayList&lt;Rule&gt;): Boolean { var rulesWithMonthLimits = 0 for (rule in ruleset) { if (rule.dates != null) { rulesWithMonthLimits += 1 } } if (rulesWithMonthLimits == 0) { return false } if (rulesWithMonthLimits == ruleset.size) { return false } return true } // Reduces rule to a subset supported by StreetComplete // in case of any info that would be lost it returns null // null is also returned in cases where conversion would be necessary // and there is any risk of loss of any data private fun reduceRuleToStreetCompleteSupported(rule: Rule): Rule? { // following are ignored: val returned = emptyRule() val days = rule.days if (days == null &amp;&amp; rule.holidays == null) { // SC requires explicit specification of days of a week or PH // holidays may contain some other holidays, but such cases will // fail a holiday-specific check return null } if (days != null) { val simplifiedWeekDayRanges: MutableList&lt;WeekDayRange&gt; = ArrayList() for (weekDayRange in days) { val simplifiedDateRange = reduceWeekDayRangeToSimpleDays(weekDayRange) ?: return null simplifiedWeekDayRanges.add(simplifiedDateRange) } if (simplifiedWeekDayRanges.size &gt; 1) { //TODO: support also Fr,Sa 11:00-00:00 kind of rules return null } returned.days = simplifiedWeekDayRanges // copy days of the week from the input rule } val dates = rule.dates if (dates != null) { val simplifiedDateRanges: MutableList&lt;DateRange&gt; = ArrayList() for (dateRange in dates) { val simplifiedDateRange = reduceDateRangeToFullMonths(dateRange) ?: return null simplifiedDateRanges.add(simplifiedDateRange) } if (simplifiedDateRanges.size &gt; 1) { // happens with rules such as `Mo-Fr 7:30-18:00, Sa-Su 9:00-18:00` // that are intentionally rejected as are not directly representable in SC // and handling them may result in unexpected silent transformation // what is unwanted return null } returned.setDates(simplifiedDateRanges) } val times = rule.times if (times == null) { // explicit opening hours are required by SC return null } else { val simplifiedTimespans: ArrayList&lt;TimeSpan&gt; = ArrayList() for (time in times) { val simplifiedTimespan = reduceTimeRangeToSimpleTime(time) ?: return null simplifiedTimespans.add(simplifiedTimespan) } // multiple timespans may happen for rules such as "Mo-Su 09:00-12:00, 13:00-14:00" returned.times = simplifiedTimespans } val modifier = rule.modifier if (modifier != null) { val reducedModifier = reduceModifierToAcceptedBySC(modifier) ?: return null returned.modifier = reducedModifier } val holidays = rule.holidays if (holidays != null) { val reducedHolidays = reduceHolidaysToAcceptedBySC(holidays) ?: return null returned.holidays = reducedHolidays } return if (rule == returned) { // original rule is matching reduced rule as no special constructions were used returned } else { // not representable given our limitations null } } private fun reduceModifierToAcceptedBySC(modifier: RuleModifier): RuleModifier? { // public holidays with "off" specified explicitly are incompatible with SC due to // https://github.com/westnordost/StreetComplete/issues/276 // other opening hours using "off" are rare and would require automated conversion // that would drop off part, what may cause issues in weird cases if (modifier.modifier != RuleModifier.Modifier.OPEN) { return null } return modifier } private fun reduceHolidaysToAcceptedBySC(holidays: List&lt;Holiday&gt;): List&lt;Holiday&gt;? { // PH, with set opening hours variant is supported by SC // many other variants are not, holidays list longer than 1 entry // indicates unsupported use if (holidays.size &gt; 1) { return null } val holiday = holidays[0] val returned = Holiday() if (!holiday.useAsWeekDay) { // SC is not supporting "public holidays on Mondays" combinations return null } returned.useAsWeekDay = true if (holiday.type != Holiday.Type.PH) { // SC is not supporting SH return null } returned.type = Holiday.Type.PH return listOf(returned) } // StreetComplete is not supporting offsets, indexing by nth day of week etc // function may return identical or modified object or null // null or modified object indicates that original object was not representable in SC private fun reduceWeekDayRangeToSimpleDays(weekDayRange: WeekDayRange): WeekDayRange? { val returned = WeekDayRange() if (weekDayRange.startDay == null) { // invalid range return null } // returned.endDay may be null for range containing just a single day returned.endDay = weekDayRange.endDay returned.startDay = weekDayRange.startDay return returned } // StreetComplete supports solely date changing based on month // without any support for any other data ranges // function may return identical or modified object or null // null or modified object indicates that original object was not representable in SC private fun reduceDateRangeToFullMonths(dateRange: DateRange): DateRange? { for (date in arrayOf(dateRange.startDate, dateRange.endDate).filterNotNull()) { if (date.isOpenEnded) { return null //TODO: it may be supported by StreetComplete } if (date.weekDayOffset != null) { return null } if (date.dayOffset != 0) { return null } } val newDateRange = DateRange() val startDate = DateWithOffset() startDate.month = dateRange.startDate.month newDateRange.startDate = startDate val endDate = dateRange.endDate if (endDate != null) { // range with just single month will have endDate unset val newEndDate = DateWithOffset() newEndDate.month = endDate.month newDateRange.endDate = newEndDate } return newDateRange } // StreetComplete has no support for times like "from sunrise to sunset" // this function throws away any info over "from hour X to hour Y" // function may return identical or modified object or null // null or modified object indicates that original object was not representable in SC private fun reduceTimeRangeToSimpleTime(timeSpan: TimeSpan): TimeSpan? { val simplifiedTimespan = TimeSpan() if (timeSpan.startEvent != null) { return null } if (timeSpan.endEvent != null) { return null } val startInMinutesSinceMidnight = timeSpan.start if (startInMinutesSinceMidnight &lt; 0) { return null } if (startInMinutesSinceMidnight &gt; 24 * 60) { return null } simplifiedTimespan.start = startInMinutesSinceMidnight val endInMinutesSinceMidnight = timeSpan.end if (endInMinutesSinceMidnight &lt; 0) { return null } simplifiedTimespan.end = endInMinutesSinceMidnight return simplifiedTimespan } private fun emptyRule(): Rule { // workaround needed to construct empty Rule object // proposal to allow creation of Rule objects is at // https://github.com/simonpoole/OpeningHoursParser/pull/24 val input = ByteArrayInputStream("".toByteArray()) val parser = OpeningHoursParser(input) try { val rules = parser.rules(true) return rules[0] } catch (e: ParseException) { e.printStackTrace() throw RuntimeException() } } } </code></pre> <p><code>WorkingAsssert.kt</code></p> <p>Story of this file is a bit embarrassing - I initially used <code>assert</code> and later discovered that it is not working. This probably should be eliminated before PR but I have no good idea for replacement and simply removing asserts seems to be a poor idea for me.</p> <pre><code>package de.westnordost.streetcomplete.quests.opening_hours object Assert { fun assert(conditionAssertedToBeTrue: Boolean) { if(!conditionAssertedToBeTrue) { throw AssertionError() } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T17:09:49.440", "Id": "456071", "Score": "0", "body": "Note to self: I tried +100 bounty with \"if you are unwilling to answer anyway - can you comment? I am unsure is it too long, boring or just there is nobody here who is familiar with Kotlin.\" comment, without triggering a reaction." } ]
[ { "body": "<p>I don't know Kotlin or how OpenStreetMap works so I'm probably the worst person to answer your question but since nobody has answered I'll give it a shot.</p>\n\n<pre><code>var data = mutableListOf(OpeningMonthsRow())\nfor (rule in rules) {\n if (rule.dates != null) {\n // month based rules, so we need OpeningMonthsRow objects that will be created\n // and added later rather than a single catch-all row\n data = mutableListOf()\n }\n}\n</code></pre>\n\n<p>This code seems to be checking if the <code>dates</code> property on a <code>rule</code> is not null and if so set data to a new <code>mutableListOf()</code>. The <code>any()</code> operator could be used to simplify this comparison:</p>\n\n<pre><code>data = if (rules.any { it.rule != null }) mutableListOf() else mutableListOf(OpeningMonthsRow())\n</code></pre>\n\n<p>Which could make it easier to read.</p>\n\n<pre><code>private fun getIndexOfOurMonthsRow(monthRows: List&lt;OpeningMonthsRow&gt;, startMonth: Int, endMonth: Int): Int {\n for ((index, row) in monthRows.withIndex()) {\n if (row.months.start == startMonth) {\n if (row.months.start == endMonth) {\n return index\n }\n }\n }\n return -1\n}\n</code></pre>\n\n<p>This <em>might</em> be a potential bug; <code>row.months.start == startMonth</code> and <code>row.months.start == endMonth</code>; should the second be <code>row.months.end</code>? Additionally, <code>indexOfFirst</code> could be useful here (and use the predicate to match the object's properties.)</p>\n\n<pre><code>private fun isRulesetToStreetCompleteSupported(ruleset: ArrayList&lt;Rule&gt;): Boolean {\n for (rule in ruleset) {\n if (reduceRuleToStreetCompleteSupported(rule) == null) {\n return false\n }\n }\n if (includesMonthsRangeCrossingNewYearBoundary(ruleset)) {\n // strictly speaking this kind of ranges are supported, but not in an obvious way\n return false\n }\n if (areOnlySomeRulesMonthBased(ruleset)) {\n // StreetComplete can handle month based rules, but requires all of them to be month based\n return false\n }\n if (rulesAreOverridingOtherRules(ruleset)) {\n // this kind of opening hours specification likely require fix\n // anyway, it is not representable directly by SC\n return false\n }\n return true\n }\n</code></pre>\n\n<p>I would combine the <code>return false</code> seconds together, and collapse the loop. It could look like (and put comments on each statement):</p>\n\n<pre><code>private fun isRulesetToStreetCompleteSupported(ruleset: ArrayList&lt;Rule&gt;): Boolean {\n return if (ruleset.any { reduceRuleToStreetCompleteSupported(it) == null })\n || includesMonthsRangeCrossingNewYearBoundary(ruleset))\n || areOnlySomeRulesMonthBased(ruleset)\n || rulesAreOverridingOtherRules(ruleset));\n}\n</code></pre>\n\n<p>For <code>rulesAreOverridingOtherRules</code>, it has a triple <code>for</code> loop which can make the logic difficult to follow. This problem can be generalized to finding any overlap between <code>n</code> or more intervals. This link: <a href=\"https://stackoverflow.com/questions/3269434/whats-the-most-efficient-way-to-test-two-integer-ranges-for-overlap\">https://stackoverflow.com/questions/3269434/whats-the-most-efficient-way-to-test-two-integer-ranges-for-overlap</a> gives some generic advice on how to approach such a problem.</p>\n\n<p>I would then genericize the <code>*intersects</code> methods to have a single method which would check if there is an intersection on a generic date interval (or integer) and then create wrappers to convert the months/days/hours into that format.</p>\n\n<p>For <code>emptyRule()</code>, I would remove the try block and just allow the <code>ParseException</code> to be thrown instead, as the stack trace information won't be thrown away.</p>\n\n<p>There are a lot of null checks in the code; maybe the data can be cleaned or checked once and then re-converted into a different format where these checks are not required (e.g. making them a wrapper class that has methods to return object attributes conditionally.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-04T07:30:08.120", "Id": "456191", "Score": "0", "body": "`row.months.start == startMonth and row.months.start == endMonth; should the second be row.months.end` Thanks! This alone was worth posting the question! And despite not knowing anything about OSM you know improved it by a tiny bit!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-04T01:16:39.690", "Id": "233379", "ParentId": "233053", "Score": "1" } } ]
{ "AcceptedAnswerId": "233379", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T09:57:03.637", "Id": "233053", "Score": "3", "Tags": [ "parsing", "validation", "kotlin" ], "Title": "Parsing opening hours, discarding insane ones (part of the OpenStreetMap editor)" }
233053
<p>I have implemented a Merge sort in Python 3, and it works well. If anything needs to be improved, I would appreciate the criticism.</p> <pre><code>def merge_sort(nums): if len(nums) == 1: return middle_index = len(nums) // 2 left_half = nums[:middle_index] right_half = nums[middle_index:] merge_sort(left_half) merge_sort(right_half) i = 0 j = 0 k = 0 while i&lt;len(left_half) and j&lt;len(right_half): if left_half[i] &lt; right_half[j]: nums[k] = left_half[i] i = i + 1 else: nums[k] = right_half[j] j = j + 1 k = k + 1 while i&lt;len(left_half): nums[k] = left_half[i] k = k + 1 i = i + 1 if __name__ == "__main__": nums = [-3,-2,-1,1,2,1,0,-1,-2,-3] merge_sort(nums) print(nums) </code></pre>
[]
[ { "body": "<p>For one you could change your code to non-recursive. Lists in python and recursion don't mix well. In other words, what you did might work fine, but it could work a bit better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T12:41:49.203", "Id": "233062", "ParentId": "233058", "Score": "0" } }, { "body": "<p>Everything I'm going to talk about is in the <code>merge_sort</code> function</p>\n\n<h2>General</h2>\n\n<pre><code>i = 0\nj = 0\nk = 0\n</code></pre>\n\n<p>Can be defined as</p>\n\n<p><code>i = j = k = 0</code></p>\n\n<hr>\n\n<p>You should always leave spaces between operators as per <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> rules</p>\n\n<p><code>i&lt;len(left_half)</code> should be <code>i &lt; len(left_half)</code></p>\n\n<hr>\n\n<p>Use <code>x += y</code> instead of <code>x = x + y</code></p>\n\n<hr>\n\n<p><em>In my opinion</em>, I think using short and concise names such as <code>mid</code> or <code>middle</code> instead of <code>middle_index</code> would be better. If you don't wish to, you can leave it as it!</p>\n\n<hr>\n\n<p>Use <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">type hints</a></p>\n\n<hr>\n\n<p>Add <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a></p>\n\n<hr>\n\n<h2>Bug</h2>\n\n<p>Your function only takes into account the <code>left_half</code> of the array, and ignores what's left in the <code>right_half</code></p>\n\n<p>For example, if <code>nums</code> array was <code>[3, 9, 0]</code>, The array would be <code>[0, 3, 0]</code></p>\n\n<p>This would happen as</p>\n\n<p><code>merge_sort([3])</code> which won't change the <code>left_half</code>\n<code>merge_sort([9, 0])</code> which would make the <code>right_half</code> as <code>[0, 9]</code></p>\n\n<p>Then, </p>\n\n<pre><code>left_half = [3]\nright_half = [0, 9]\n\nnums = [3, 9, 0]\n\ni = 0\nj = 0\nk = 0\n\nFirst, the else statement would be called as 3 &gt; 0.\n\ni = 0\nj = 1\nk = 1\n\nnums = [0, 9, 0]\n\nNext, the if statement would be called as 3 &lt; 9\n\ni = 1\nj = 1\nk = 2\n\nnums = [0, 3, 0]\n\nNow, the while loop will terminate as i = len(left_side)\n\nThen, while i &lt; len(left_side) would immediately terminate as i = len(left_side)\n\n</code></pre>\n\n<p>Did you notice? <code>right_side</code> still has one element <code>9</code> waiting to be traversed, but it never will be.</p>\n\n<p>To fix that, add the following to the end of the function</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>while j &lt; len(right_half):\n nums[k] = right_half[j]\n j += 1\n k += 1\n</code></pre>\n\n<hr>\n\n<h2>Improvement</h2>\n\n<p>Now, instead of using a <code>while</code> loop at all, you can just use <code>a[k:] = left_half[i:] + right_half[j:]</code> to replace both the loops! This is true because one half must be empty and the other half must have the length of <code>n - k</code>.</p>\n\n<hr>\n\n<h2>Performance</h2>\n\n<p>If you are using this function in real time with an array of a really large size, this won't work efficiently.</p>\n\n<p><code>len</code> takes quite a bit of time. To make it even faster, use a parameter <code>length</code> which would be the length of the array</p>\n\n<hr>\n\n<p>The final implementation of the function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from typing import List, Any\n\ndef merge_sort(nums: List[Any], length: int) -&gt; None:\n \"\"\" Uses Merge Sort to sort an array \"\"\"\n\n # Base case\n if length == 1:\n return\n\n mid = length // 2\n\n left, right = mid, length - mid\n\n left_half, right_half = nums[:mid], nums[mid:]\n\n merge_sort(left_half, left)\n merge_sort(right_half, right)\n\n i = j = k = 0\n\n while i &lt; left and j &lt; right:\n if left_half[i] &lt; right_half[j]:\n nums[k] = left_half[i]\n i += 1\n else:\n nums[k] = right_half[j]\n j += 1\n\n k += 1\n\n nums[k:] = left_half[i:] + right_half[j:]\n</code></pre>\n\n<p><em>Note:</em> <code>Any</code> in <code>typing</code> means any datatype is allowed. The function can sort any datatype that is comparable with another element of the same datatype.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T15:51:00.370", "Id": "455436", "Score": "0", "body": "Why is `mid` better than `middle` or `mid_point`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T15:53:19.077", "Id": "455438", "Score": "0", "body": "`middle` would work as well, but not `middle_index` or `mid_point`. I think the sizes are too big, but that's just my opinion!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:18:35.560", "Id": "233064", "ParentId": "233058", "Score": "1" } } ]
{ "AcceptedAnswerId": "233064", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T12:05:45.097", "Id": "233058", "Score": "2", "Tags": [ "python", "python-3.x", "sorting", "mergesort" ], "Title": "Merge sort implementation in python 3" }
233058
<p>I wrote an algorithm that analyzes protein-RNA interactions and I found that the following function is the bottleneck that causes performance issues: </p> <pre><code>import numpy as np #len(protein_sequence)~500, len(rna_sequence)~1500 def affinity_matrix(protein_sequence, rna_sequence): python_matrix = [[] for _ in range(len(protein_sequence))] for i, AA in enumerate(protein_sequence): for base in rna_sequence: python_matrix[i].append(scales[base][AA]) #(Where "scales" is a small dict() with the structure: #scales[base][AA] = float(), with 4 bases and 20 AA, so 80 values total.) return(np.array(python_matrix)) </code></pre> <p>I suspect 2 problems in this code, but I don't know how to solve them:</p> <ol> <li>I am retrieving values from this <code>scales</code> <code>dict</code> millions of times, and it's said calling values from "non-static" data structures like <code>dict()</code> is slow. So how can I make this small dictionary "static" instead? (This dictionary is only created once, while the <code>rna_sequence</code> and <code>protein_sequence</code> will be different each time I call the function.)</li> <li>I am building the matrix at first with pythons tools, and later I convert it into the (faster) NumPy array. Possibly it is faster to directly create it with NumPy, but I am not sure if this is possible.</li> </ol> <p>I am thankful for any tips how to improve this code or references to guides that would help in this case.</p> <p>Here is example data, in case you want to try out the algorithm:</p> <pre><code>rna_sequence = 'ACAGGAGGAGCCGCUCGCUGGCGGCUGAUCCAGCGUCUCCGUGACAGGCACCCUGCUCCGCCGCCACCGCCACCGCCACCGCCACCGUCGCCUUUUCUUCUUCGUCCCGGGCGGUGCGUUCCACUGCUCUGGGGCCGGCGCCGCGCCCAGUCCCGCUUCGGGCCGCAAGCCCCACCGCUCCCCUCCCCGGGCAGGGGCGCCGCGCAGCCCGCUCCCGCCGCCACCUCCUCCCCUGCCGCCCUCCUAGCCGGCAGGAAUUGCGCGACCACAGCGCCGCUCGCGUCGCCCGCAUCAGCUCAGCCCGCUGCCGCUCGGCCCUCGGCACCGCUCCGGGUCCGGCCGCCGCGCGGCCAGGGCUCCCCCUGCCCAGCGCUCCCAGGCCCCGCCACGCGUCGCCGCGCCCAGCUCCAGUCUCCCCUCCCCGGGGUCUCGCCAGCCCCUUCCUGCAGCCGCCGCCUCCGAAGGAGCGGGUCCGCCGCGGGUAACCAUGCCUAGCAAAACCAAGUACAACCUUGUGGACGAUGGGCACGACCUGCGGAUCCCCUUGCACAACGAGGACGCCUUCCAGCACGGCAUCUGCUUUGAGGCCAAGUACGUAGGAAGCCUGGACGUGCCAAGGCCCAACAGCAGGGUGGAGAUCGUGGCUGCCAUGCGCCGGAUACGGUAUGAGUUUAAAGCCAAGAACAUCAAGAAGAAGAAAGUGAGCAUUAUGGUUUCAGUGGAUGGAGUGAAAGUGAUUCUGAAGAAGAAGAAAAAGCUUCUUUUAUUGCAGAAAAAGGAAUGGACGUGGGAUGAGAGCAAGAUGCUGGUGAUGCAGGACCCCAUCUACAGGAUCUUCUAUGUCUCUCAUGAUUCCCAAGACUUGAAGAUCUUCAGCUAUAUCGCUCGAGAUGGUGCCAGCAAUAUCUUCAGGUGUAACGUCUUUAAAUCCAAGAAGAAGAGCCAAGCUAUGAGAAUCGUUCGGACGGUGGGGCAGGCCUUUGAGGUCUGCCACAAGCUGAGCCUGCAGCACACGCAGCAGAAUGCAGAUGGCCAGGAAGAUGGAGAGAGCGAGAGGAACAGCAACAGCUCAGGAGACCCAGGCCGCCAGCUCACUGGAGCCGAGAGGGCCUCCACGGCCACUGCAGAGGAGACUGACAUCGAUGCGGUGGAGGUCCCACUUCCAGGGAAUGAUGUCCUGGAAUUCAGCCGAGGUGUGACUGAUCUAGAUGCUGUAGGGAAGGAAGGAGGCUCUCACACAGGCUCCAAGGUUUCGCACCCCCAGGAGCCCAUGCUGACAGCCUCACCCAGGAUGCUGCUCCCUUCUUCUUCCUCGAAGCCUCCAGGCCUGGGCACAGAGACACCGCUGUCCACUCACCACCAGAUGCAGCUCCUCCAGCAGCUCCUCCAGCAGCAGCAGCAGCAGACACAAGUGGCUGUGGCCCAGGUACACUUGCUGAAGGACCAGUUGGCUGCUGAGGCUGCGGCGCGGCUGGAGGCCCAGGCUCGCGUGCAUCAGCUUUUGCUGCAGAACAAGGACAUGCUCCAGCACAUCUCCCUGCUGGUCAAGCAGGUGCAAGAGCUGGAACUGAAGCUGUCAGGACAGAACGCCAUGGGCUCCCAGGACAGCUUGCUGGAGAUCACCUUCCGCUCCGGAGCCCUGCCCGUGCUCUGUGACCCCACGACCCCUAAGCCAGAGGACCUGCAUUCGCCGCCGCUGGGCGCGGGCUUGGCUGACUUUGCCCACCCUGCGGGCAGCCCCUUAGGUAGGCGCGACUGCUUGGUGAAGCUGGAGUGCUUUCGCUUUCUUCCGCCCGAGGACACCCCGCCCCCAGCGCAGGGCGAGGCGCUCCUGGGCGGUCUGGAGCUCAUCAAGUUCCGAGAGUCAGGCAUCGCCUCGGAGUACGAGUCCAACACGGACGAGAGCGAGGAGCGCGACUCGUGGUCCCAGGAGGAGCUGCCGCGCCUGCUGAAUGUCCUGCAGAGGCAGGAACUGGGCGACGGCCUGGAUGAUGAGAUCGCCGUGUAGGUGCCGAGGGCGAGGAGAUGGAGGCGGCGGCGUGGCUGGAGGGGCCGUGUCUGGCUGCUGCCCGGGUAGGGGAUGCCCAGUGAAUGUGCACUGCCGAGGAGAAUGCCAGCCAGGGCCCGGGAGAGUGUGAGGUUUCAGGAAAGUAUUGAGAUUCUGCUUUGGAGGGUAAAGUGGGGAAGAAAUCGGAUUCCCAGAGGUGAAUCAGCUCCUCUCCUACUUGUGACUAGAGGGUGGUGGAGGUAAGGCCUUCCAGAGCCCAUGGCUUCAGGAGAGGGUCUCUCUCCAGGACUGCCAGGCUGCUGGAGGACCUGCCCCUACCUGCUGCAUCGUCAGGCUCCCACGCUUUGUCCGUGAUGCCCCCCUACCCCCUCACUCUCCCCGUCUCCAUGGUCCCGACCAGGAAGGGAAGCCAUCGGUACCUUCUCAGGUACUUUGUUUCUGGAUAUCACGAUGCUGCGAGUUGCCUAACCCUCCCCCUACCUUUAUGAGAGGAAUUCCUUCUCCAGGCCCUUGCUGAGAUUGUAGAGAUUGAGUGCUCUGGACCGCAAAAGCCAGGCUAGUCCUUGUAGGGUGAGCAUGGAAUUGGAAUGUGUCACAGUGGAUAAGCUUUUAGAGGAACUGAAUCCAAACAUUUUCUCCAGCCGGACAUUGAAUGUUGCUACAAAGGGAGCCUUGAAGCUUUAACAUGGUUCAGGCCCUUGGUGUGAGAGCCCAGGGGGAGGACAGCUUGUCUGCUGCUCCAAAUCACUUAGAUCUGAUUCCUGUUUUGAAAGUCCUGCCCUGCCUUCCUCCUGCCUGUAGCCCAGCCCAUCUAAAUGGAAGCUGGGAAUUGCCCCUCACCUCCCCUGUGUCCUGUCCAGCUGAAGCUUUUGCAGCACUUUACCUCUCUGAAAGCCCCAGAGGACCAGAGCCCCCAGCCUUACCUCUCAACCUGUCCCCUCCACUGGGCAGUGGUGGUCAGUUUUUACUGCAAAAAAAAAAAAAGAAAAAAGAGAAAGAAAAAAAAGAAUGAAUGCAAGCUGAUAGCUGAGACUGUGAGACUGUUUUUGUCCACUCUUCUGAAUCACUGCCACUUGGGUCAGGGACCACAGCCAUUGCCACCCUUGGCCCAUCUCUCUGCGUGCGUGCCUUGAGCACACAUAUAAAAAGUGCCAUGUGCAAUUGUCUUAUCUUUUAUGAUCUAGGCUUUGCCUAGGGAUCACUACUCCUUAACGGGCUGGCUGGGGCAAUGAGGAAAAGCUCCUUUGCUCCUGUAAGGCCAUAAGUGGCUGUUAACAGAUUUUCAAAUGCCUGAAGAGAUUGCUGAGACCUGCUAGAGUCAUAUGUUCGGGGAAUUAAGUCUUUAUCCUAGACAACAAGGUACAGAUGCAAACUGCAGUGUUAUUGGAGGGUCAAUCGGCAAGGAUAUGAUUAUCCCAAAAUGGAGUUCAUCGACCCUAGCUUUCCUUUAGAUUAUAUAUAAAUAAAAGUGCAGUCCUCUUCUAAUGGCCACAGUUGGUUUUCUUGUAGCCCAGAAAGUCCAAAUUAAAGGAAAUAAAUUCAGUUUUAUGUUAGCCUUCCUUGGUGCAUCAGGGUGUCAGUGGAAAUAGGAUCAGGUGGUGUGUGUGUGUGUGUUUUGUGUGUGUGUGUACACAUGUGUUUAUAUAUACAUGUGUGAGGGAAAGUGUGUACAUAUAUGUAGGAUUGUAACCAGACGGAAAAGAACGAGGAUCUCCAGGGUGUUUGAAUCAGCAACAGAUUUGUGUUUUCUAACAUGCAUUUAGUUGGAGAGGCAUGGUUCUGUUUGUUUUGUUUUGAUCUAAUUUGCCAUUGGAAAUAGGUACAGUUACACAGAGAAGGAAGAACCAGGAAAGUGAGAUCCAUGAAACUAAAUGAGCAGCUGUCAGAAUCCAGUGUGGCUGAGCCUACCUAGCUUAUGAAAUCUAACCCAGGGUUCCCUGAGUCCAAGACCACUUAGAUUAUUAAGAUUUUGAACGUCCAGAGGAGUGAAAAGUCUGUUUUCUGACGUAAGCCGGAGCUGAGGAUAAAGCCAGAGGCCAGUGGAUUAGGUGUAUGGAAUGUGGAUGGAGAGGGCUUGUGUGGGAUGUGGCCAGGGAGUGGGUGAGGAAGGCCGCUUCUAAAUGGCCUGUAAAAACUUGAGAUUGGAUAGACGAAAGGAAAUGGAGAAAUUAAAGAAUUGGAGAAACUAGUUAUCUGUGUUGCUGACUUUGGGACCCAUCCAAGACUCCUGCCCUUGGGGUGUUCCAUGGUGGUUUCUUCCUGCCUGGGCGCCACCCUUUCCCCAGUUCAGGCCCUCCCUGGAGGACUAGUUUGUGUAUUGGUAUCCUCCCCAGUGGACCCAAACCAGCGCAUACUUGGUGUGUGGAGAUGGGAGACAAAGGACAGAUCUAGGAGCCUUGAAGGAUCACCAGCCACCGACCCUCCAUCAGGGCCAACUGGGCAGGAAAGGGAACAUUGCAGACCUGAUUUCCCGACGAUGUCACCCUGUCCUCCCUCCUUGCUUCUUGCUCUGCUAACUCAACUCUGCCUUCCUCUUUUUCAUUCUUCUACUCUGCCCUAUAUGGAGGACAAAUGGACACCAGGGGUGCUAACCUUAUUGGUGCCUGCCCCAGCCUACCCCAGGUGCCAGCAGACUCUCGUGCACAGGAGGCUCCCACAGUUAUGGAGCCAGGAAAGAAUUUCUCUGCACUGGAUGGACUGUAUAUUGAGAUUAAAAAUUAUAUUCCUUAUAUUCCUGCUUAUAUCAAUGCUCUCUCUGUAAAACCUCUUCCUAGCCUCAUUUCUCUCAACUGAUCUUGUUUAGGCGUUGUAUUCCUUUUAUUUACUCUUUGCUUGACUGCUUCCUCCUAACCCUCUACCCACUAGCACUCUACUUCCUAAAGCUGUUGUGUCAUUAACUCUGUUGGAUCAACUCUCUGGGAAAAGAUUCUGUUAAUGUAAGUGCACUUACUCCCUGGAUGUUGUCACUAGUCUAGUGGCUUUUGCUAAAUAAACCUUUCUUAUUUCUA' protein_sequence = 'MPSKTKYNLVDDGHDLRIPLHNEDAFQHGICFEAKYVGSLDVPRPNSRVEIVAAMRRIRYEFKAKNIKKKKVSIMVSVDGVKVILKKKKKLLLLQKKEWTWDESKMLVMQDPIYRIFYVSHDSQDLKIFSYIARDGASNIFRCNVFKSKKKSQAMRIVRTVGQAFEVCHKLSLQHTQQNADGQEDGESERNSNSSGDPGRQLTGAERASTATAEETDIDAVEVPLPGNDVLEFSRGVTDLDAVGKEGGSHTGSKVSHPQEPMLTASPRMLLPSSSSKPPGLGTETPLSTHHQMQLLQQLLQQQQQQTQVAVAQVHLLKDQLAAEAAARLEAQARVHQLLLQNKDMLQHISLLVKQVQELELKLSGQNAMGSQDSLLEITFRSGALPVLCDPTTPKPEDLHSPPLGAGLADFAHPAGSPLGRRDCLVKLECFRFLPPEDTPPPAQGEALLGGLELIKFRESGIASEYESNTDESEERDSWSQEELPRLLNVLQRQELGDGLDDEIAV' scales = {'A': {'A': -0.103534, 'C': -0.141027, 'D': -0.057364, 'E': 0.025673, 'F': -0.160025, 'G': 0.155926, 'H': 0.114486, 'I': -0.064125, 'K': 0.058532, 'L': -0.093059, 'M': -0.093239, 'N': 0.211717, 'P': -0.187549, 'Q': 0.286417, 'R': 0.045458, 'S': -0.068299, 'T': -0.256675, 'V': -0.126037, 'W': -0.352338, 'Y': -0.059715}, 'C': {'A': -0.170978, 'C': 0.460587, 'D': 0.011352, 'E': 0.456847, 'F': -0.157944, 'G': 0.209027, 'H': -0.166851, 'I': -0.016438, 'K': 0.093534, 'L': 0.112175, 'M': -0.08656, 'N': 0.439522, 'P': -0.189412, 'Q': -0.031332, 'R': 0.009869, 'S': -0.357084, 'T': -0.360561, 'V': 0.248514, 'W': 0.417484, 'Y': 0.059507}, 'G': {'A': 0.157098, 'C': 0.006956, 'D': 0.047448, 'E': -0.193184, 'F': 0.480436, 'G': -0.279106, 'H': 0.144117, 'I': 0.170305, 'K': -0.186721, 'L': 0.177462, 'M': -0.139056, 'N': -0.225754, 'P': 0.097558, 'Q': -0.085275, 'R': -0.055897, 'S': 0.273463, 'T': 0.166763, 'V': 0.108108, 'W': 0.093968, 'Y': 0.263202}, 'U': {'A': 0.130008, 'C': -0.012462, 'D': 0.005557, 'E': 0.043517, 'F': -0.269202, 'G': -0.031819, 'H': -0.198936, 'I': -0.084679, 'K': 0.096389, 'L': -0.153234, 'M': 0.351179, 'N': -0.215165, 'P': 0.240871, 'Q': -0.065384, 'R': 0.005856, 'S': 0.31803, 'T': 0.264754, 'V': -0.078486, 'W': 0.094917, 'Y': -0.118544}} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T12:47:43.530", "Id": "455397", "Score": "0", "body": "\"*I am loading this dictionary millions of times*\" and \"*So how can I make this small dictionary \"static\" instead?*\" - are you declaring that dict within a `for` loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T12:49:25.670", "Id": "455398", "Score": "0", "body": "No, the dict is only created once. (I don't really know what \"static\" fully means..)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T12:50:21.140", "Id": "455399", "Score": "0", "body": "Ok, then, what does mean your \"I am loading this dictionary millions of times\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T12:52:25.897", "Id": "455400", "Score": "0", "body": "Sorry for my inaccurate language! I mean I retrieve values from it many times. In this function 500*1500 times and I call this function many thousand times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T12:55:13.050", "Id": "455401", "Score": "1", "body": "So the RNA and protein sequences always will be different, but the \"scales\" dictionary is always the same one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:05:47.967", "Id": "455402", "Score": "0", "body": "Is that number `1.1111` intended always be the same for all `rna` keys?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:09:16.943", "Id": "455404", "Score": "0", "body": "In reality it's always a different number with a similar number of decimals. I just didn't want to copy-paste a whole dictionary for reasons of staying compact. Should I provide the real numbers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:10:35.893", "Id": "455405", "Score": "1", "body": "Yes, for this case it's better to post the actual scales with real numbers if they differ" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:18:50.583", "Id": "455408", "Score": "0", "body": "I see. I just did." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:08:56.313", "Id": "455421", "Score": "1", "body": "And the last question please, how do \"performance issues\" appear? time perfromance, memory? What's your current perf. statistics on your environment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:09:46.230", "Id": "455423", "Score": "0", "body": "Only time. Thanks in advance!" } ]
[ { "body": "<h3><em>Boosting performance</em></h3>\n\n<p>The initial approach creates a 2-dimensional list of empty lists beforehand and performs 2 538 096 expensive <code>list.append</code> operations.</p>\n\n<p>To make it go faster and more efficiently we'll go through 2 steps:</p>\n\n<ul>\n<li>schedule a generator/iterator yielding a sequence of all the needed values</li>\n<li>generate <code>numpy</code> array from the scheduled <em>generaor</em> with convenient <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html\" rel=\"nofollow noreferrer\"><code>numpy.fromiter</code></a> routine and immediately giving a new shape to the array with <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html\" rel=\"nofollow noreferrer\"><code>numpy.reshape</code></a> routine (assuming that <code>len(protein_sequence)</code> points to number of <em>rows</em> and <code>len(rna_sequence)</code> is a number of <em>columns</em>)</li>\n</ul>\n\n<hr>\n\n<p>The final optimized <strong><code>affinity_matrix</code></strong> function:</p>\n\n<pre><code>def affinity_matrix(protein_sequence, rna_sequence):\n it = (scales[base][prot] for prot in protein_sequence for base in rna_sequence)\n return np.fromiter(it, dtype=float).reshape(len(protein_sequence), len(rna_sequence))\n</code></pre>\n\n<hr>\n\n<p>Let's move to tests. I've renamed the old function to <code>affinity_matrix_old</code> for comparison.</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; timeit('affinity_matrix_old(protein_sequence, rna_sequence)', setup='from __main__ import affinity_matrix_old, protein_sequence, rna_sequence', number=10)\n3.1148553189996164\n&gt;&gt;&gt; timeit('affinity_matrix(protein_sequence, rna_sequence)', setup='from __main__ import affinity_matrix, protein_sequence, rna_sequence', number=10)\n1.9052914250059985\n</code></pre>\n\n<hr>\n\n<p>The resulting array looks as:</p>\n\n<pre><code>&gt;&gt;&gt; affinity_matrix(protein_sequence, rna_sequence)\narray([[-0.093239, -0.08656 , -0.093239, ..., -0.08656 , 0.351179,\n -0.093239],\n [-0.187549, -0.189412, -0.187549, ..., -0.189412, 0.240871,\n -0.187549],\n [-0.068299, -0.357084, -0.068299, ..., -0.357084, 0.31803 ,\n -0.068299],\n ...,\n [-0.064125, -0.016438, -0.064125, ..., -0.016438, -0.084679,\n -0.064125],\n [-0.103534, -0.170978, -0.103534, ..., -0.170978, 0.130008,\n -0.103534],\n [-0.126037, 0.248514, -0.126037, ..., 0.248514, -0.078486,\n -0.126037]])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:50:55.547", "Id": "455428", "Score": "0", "body": "Great, from now on I will try to avoid append() as much as possible! And the dict() is ok? I thought of something like converting all RNA and protein sequences to vectors of integers. Then maybe I can transform the scale-dict to a 2d Numpy array? Would that be much faster?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T15:33:25.847", "Id": "455434", "Score": "0", "body": "@KaPy3141, I would say for this case - your `scales` dict is good. Whatever structure it would be transformed to - that structure still will be indexed **2 538 096** times due to 2 input factors `protein_sequence/rna_sequence`. Let's say if I collapse your dict into 1-level structure like `scales_1d = {(base, k): num for base, rna_data in scales.items() for k, num in rna_data.items()}` (having compound keys) - that will run slower. As another way: if we transform the dict into a dataframe `scales_pd = pd.DataFrame(scales)` - that would be even more slower." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:35:12.163", "Id": "233072", "ParentId": "233061", "Score": "8" } }, { "body": "<p>It is likely not the dictionary look-up that kills your performance here, and more those nested <code>for</code> loops. <a href=\"https://www.youtube.com/watch?v=EEUXKG97YRw\" rel=\"noreferrer\">Python is known for its notoriously slow (<code>for</code>) loops</a>.</p>\n\n<p>Since my numpy fu is a little bit weak lately, short of writing the code in C(++), I could only come up with an improvement using a nested list comprehension:</p>\n\n<pre><code>def affinity_matrix_lc(protein_sequence, rna_sequence):\n python_matrix = [[scales[base][item] for base in rna_sequence]\n for item in protein_sequence]\n\n return np.array(python_matrix)\n</code></pre>\n\n<p>Conceptually it is very similar to <a href=\"https://codereview.stackexchange.com/a/233072/92478\">RomanPerekhrest's version</a>, but slightly easier to see what's going on I would say.</p>\n\n<p>The list comprehension reduces the runtime of your example by about 30% here on my machine, with on-par performance to the one from Roman.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>%timeit affinity_matrix_op(protein_sequence, rna_sequence) # your original code\n409 ms ± 3.79 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\n%timeit affinity_matrix_rp(protein_sequence, rna_sequence) # RomanPerekhrest's version\n277 ms ± 5.63 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\n%timeit affinity_matrix_lc(protein_sequence, rna_sequence) \n275 ms ± 2.06 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n\n<h2>Edit - int version at OP's request:</h2>\n\n<p>I cobbled up a version of your code that first performs a translation to a vector of <code>int</code>s for both inputs. The look-up then uses numpy's indexing and broadcasting features to get the affinity matrix:</p>\n\n<pre><code>RNA_MAPPING = {'U': 0, 'G': 1, 'C': 2, 'A': 3}\nPROTEIN_MAPPING = {\n 'R': 0,'A': 1,'S': 2,'D': 3,'Q': 4,'N': 5,'W': 6,'V': 7,'L': 8,'K': 9,\n 'H': 10,'E': 11,'C': 12,'G': 13,'Y': 14,'P': 15,'M': 16,'I': 17,'T': 18,\n 'F': 19\n}\nLUT = np.array([\n [ 0.005856, 0.130008, 0.31803 , 0.005557, -0.065384, -0.215165,\n 0.094917, -0.078486, -0.153234, 0.096389, -0.198936, 0.043517,\n -0.012462, -0.031819, -0.118544, 0.240871, 0.351179, -0.084679,\n 0.264754, -0.269202],\n [-0.055897, 0.157098, 0.273463, 0.047448, -0.085275, -0.225754,\n 0.093968, 0.108108, 0.177462, -0.186721, 0.144117, -0.193184,\n 0.006956, -0.279106, 0.263202, 0.097558, -0.139056, 0.170305,\n 0.166763, 0.480436],\n [ 0.009869, -0.170978, -0.357084, 0.011352, -0.031332, 0.439522,\n 0.417484, 0.248514, 0.112175, 0.093534, -0.166851, 0.456847,\n 0.460587, 0.209027, 0.059507, -0.189412, -0.08656 , -0.016438,\n -0.360561, -0.157944],\n [ 0.045458, -0.103534, -0.068299, -0.057364, 0.286417, 0.211717,\n -0.352338, -0.126037, -0.093059, 0.058532, 0.114486, 0.025673,\n -0.141027, 0.155926, -0.059715, -0.187549, -0.093239, -0.064125,\n -0.256675, -0.160025]\n])\n\ndef affinity_matrix_int(protein_sequence, rna_sequence):\n protein_sequence_int = np.array(\n [PROTEIN_MAPPING[i] for i in protein_sequence], dtype=int\n ).reshape(-1, 1)\n rna_sequence_int = np.array(\n [RNA_MAPPING[i] for i in rna_sequence], dtype=int\n ).reshape(1, -1)\n return LUT[rna_sequence_int, protein_sequence_int]\n</code></pre>\n\n<p>I then checked the correctness of the implementation using</p>\n\n<pre><code>&gt;&gt;&gt; np.allclose(\n affinity_matrix_int(protein_sequence, rna_sequence),\n affinity_matrix_op(protein_sequence, rna_sequence)\n )\nTrue\n</code></pre>\n\n<p>And did another round of timing:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>%timeit affinity_matrix_int(protein_sequence, rna_sequence) \n10.9 ms ± 36.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n</code></pre>\n\n<p>To answer your question in the comments: It turns out, this is quite a bit faster ;-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:55:02.660", "Id": "455431", "Score": "0", "body": "Great, I didn't know one-liners are actually faster. This improved my programing in general, not just for this example! Thanks! And would it improve the performance if I converted the RNA and protein sequence data-sets to vektors of integers? Then maybe I could use a numpy 2d matrix instead of the scales-dict? Would that make it much faster?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:57:46.590", "Id": "455432", "Score": "0", "body": "Should the frequent AA be represented by low or high integers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T15:44:42.717", "Id": "455435", "Score": "1", "body": "@KaPy3141 I did a test implementation and included it in the answer. In my test it was quite a bit faster. You will have to see yourself how this works out in your application." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T16:13:46.533", "Id": "455447", "Score": "0", "body": "Wow, that's just incredible! This is what I cal an improvement! :) And this when converting each RNA and protein within the function, which I could do beforehand. Just awesome!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T16:18:19.147", "Id": "455448", "Score": "1", "body": "What does dtype=int\n ).reshape(-1, 1), if I may ask?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T16:27:11.660", "Id": "455449", "Score": "1", "body": "Python lists are 1D by default, [`reshape`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html) transforms it into a 2D column vector (-1 rows (i.e. choose automatically) x 1 column). You could also specify the exact shape explicitly as `.reshape(len(protein_sequence), 1)`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:44:43.613", "Id": "233073", "ParentId": "233061", "Score": "8" } }, { "body": "<p>You can speed this further in 2 ways.</p>\n\n<h1>local variables</h1>\n\n<p>a local variable lookup is faster than a global. Since you lookup scales an awful lot, this can improve performance</p>\n\n<h1>np.fromiter</h1>\n\n<p>where you can even specify the initial length to improve performance further</p>\n\n<pre><code>def affinity_matrix_generator(protein_sequence, rna_sequence, scales=scales):\n for base in rna_sequence:\n base_scale = scales[base] # saving another dict lookup\n for protein in protein_sequence:\n yield base_scale[protein]\n\ndef affinity_matrix(protein_sequence, rna_sequence, scales=scales):\n iterator = affinity_matrix_generator(protein_sequence, rna_sequence, scales=scales)\n size = len(protein_sequence) * len(rna_sequence)\n return np.fromiter(iterator, dtype=float, count=size).reshape(len(protein_sequence), len(rna_sequence))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T16:05:43.983", "Id": "455445", "Score": "0", "body": "Thanks a lot! (+1) I will use this general knowledge from on! Unfortunately your suggestion was slower than the original code. But I was able to use your input in general to improve others suggestions. For example AlexVs original suggestion is improved by 10% if I save the full dict locally within the function!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T15:35:15.963", "Id": "233075", "ParentId": "233061", "Score": "5" } } ]
{ "AcceptedAnswerId": "233073", "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T12:32:05.627", "Id": "233061", "Score": "9", "Tags": [ "python", "performance", "array", "numpy", "hash-map" ], "Title": "Creating an affinity-matrix between protein and RNA sequences" }
233061
<p>I have a class that creates an object, <code>PlannedYear</code>, and then passes that object into several other classes to manipulate it. The ultimate goal of the class is to manipulate and add items to this <code>PlannedYear</code> object.</p> <p>I have, however, ended up going down a rabbit hole whereby I am updating the same <code>PlannedYear</code> object in memory in multiple classes, rather than having methods with return types and so on.</p> <p>Can anyone look at my code and advise me if I can (or if I even need to) get out of the rabbit hole? I have simplified the code to demonstrate the issue and added comments.</p> <p><strong>EDIT:</strong> The overall purpose of the code is to read an existing production plan from a database, then take new items (stored in <code>Estimate</code> objects) and schedule them on top.</p> <p><strong>Planner.cs:</strong></p> <pre><code>public class Planner { // This object ends up getting modified all over the place // Ultimately it is this YearPlan that is the output of this class public PlannedYear YearPlan { get; private set; } private PlanReader planReader = new PlanReader(); public Planner() { YearPlan = planReader.GetExistingScheduleFromDatabase(); } public void Plan(List&lt;Estimate&gt; estimates) { foreach (var estimate in estimates.OrderBy(x =&gt; x.Priority)) { // Here's the start of the issue. YearPlan passed into a scheduler and gets modified var scheduler = new EstimateScheduler(estimate, YearPlan); scheduler.Schedule(); } } } </code></pre> <p><strong>EstimateScheduler.cs:</strong></p> <pre><code>public class EstimateScheduler { private PlanSearcher planSearcher; private Estimate estimateToSchedule; public EstimateScheduler(Estimate estimate, PlannedYear yearPlan) { estimateToSchedule = estimate; // yearPlan passed into planSearcher planSearcher = new PlanSearcher(yearPlan, estimateToSchedule.StartDate, estimateToSchedule.EndDate); } public void Schedule() { foreach (var itemHeader in estimateToSchedule.ItemHeaders) { ScheduleItemHeader(itemHeader); } } private void ScheduleItemHeader(EstimateItemHeader itemHeader) { foreach (var item in itemHeader.EstimateItems) { if (!planSearcher.DoesABedBigEnoughForThisItemExist(item.Length, item.Width)) { HandleItemThatCannotBePlanned(item); // Not important } else { var canItemBeAddedToBed = true; while (item.HasItemsRemainingToBeScheduled &amp;&amp; canItemBeAddedToBed) { // get a bed from planSearcher (which searches yearPlan) and try to add an item to it var bed = planSearcher.FindBedSpaceForItem(item); if (bed != null) { bed.AddItem(item); // Updates the actual bed object which persists in planSeacher item.ItemsScheduled++; } else { canItemBeAddedToBed = false; HandleItemThatCannotBePlanned(item); } } } } } } </code></pre> <p><strong>PlanSearcher.cs:</strong></p> <pre><code>public class PlanSearcher { private List&lt;PlannedDay&gt; plannedDays; public PlanSearcher(PlannedYear yearPlan, DateTime? start, DateTime? end) { // we take yearPlan and get only the range of days we need to modify plannedDays = yearPlan.PlannedDays.Where(x =&gt; x.Date &gt;= start &amp;&amp; x.Date &lt;= end).ToList(); } public PlannedBed FindBedSpaceForItem(IItem item) { // search this.plannedDays for a bed and return it } } </code></pre> <p><strong>PlannedDay.cs:</strong></p> <pre><code>public class PlannedDay { public DateTime Date { get; set; } public List&lt;PlanendBed&gt; PlannedBeds { get; set; } public PlannedDay(DateTime date) { this.Date = date; this.PlannedBeds = new List&lt;PlannedBed&gt;(); } } </code></pre> <p><strong>PlannedYear.cs:</strong></p> <pre><code>public class PlannedYear { public List&lt;PlannedDay&gt; PlannedDays { get; set; } public PlannedYear() { PlannedDays = new List&lt;PlannedDay&gt;(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T17:18:59.943", "Id": "455458", "Score": "0", "body": "Welcome to Code Review! Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T17:28:32.300", "Id": "455460", "Score": "1", "body": "@TobySpeight Hi Toby. I have edited the question to describe the overall purpose of the code is. I am not sure if I can add this to the title in a way that is clear and not confusing." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:15:54.587", "Id": "233063", "Score": "5", "Tags": [ "c#", "dependency-injection", "reference" ], "Title": "Production planner" }
233063
<p><strong>Method 1</strong>:</p> <pre class="lang-java prettyprint-override"><code>public void removeFirst() { if (first == null) throw new NoSuchElementException(); if (first == last) first = last = null; else { var second = first.next; first.next = null; first = second; } } </code></pre> <p><strong>Method 2</strong>:</p> <pre class="lang-java prettyprint-override"><code>public void removeFirst() { if (first == null) throw new NoSuchElementException(); if (first == last) first = last = null; else first = first.next; } </code></pre> <p>Which method is preferable, speed and memory-wise? Stepping through the debugger, I see no differences in <code>first</code>, <code>next</code>, and <code>last</code> objects or their <code>value</code> attributes - so 'correctness' appears the same, though I ponder about garbage collection.</p> <hr> <p><strong>Base class excerpt</strong>:</p> <pre class="lang-java prettyprint-override"><code>public class LinkedList { private class Node { private int value; private Node next; public Node(int value) { this.value = value; } } private Node first; private Node last; } public void addLast(int value){ var new_node = new Node(value); if (first == null){ first = last = new_node; } else { last.next = new_node; last = new_node; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T18:09:42.270", "Id": "455465", "Score": "0", "body": "Please don't touch the code after receiving answers, it invalidates answers and tends to create a mess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T18:14:18.503", "Id": "455466", "Score": "0", "body": "@Mast The point of my question was being missed, so I clarified it with a close equivalent. It was this or creating a \"duplicate\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:09:02.190", "Id": "455503", "Score": "0", "body": "Yea, had we caught your edit sooner (before the answer was changed to accommodate), we'd still had to roll it back per our guidelines. If your point was being missed, that highlights why putting extra effort in the first iteration is very important on Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:22:31.573", "Id": "455506", "Score": "0", "body": "@Mast Fair, but my original question was already clear enough, just not as explicit as the edit - but the answer, which entirely missed the point of the question (before being revised), was being upvoted, and no alternatives were being posted. Unsure what the best course of action is then, as posting a new question risked being marked as a duplicate" } ]
[ { "body": "<p>Review points:</p>\n\n<ul>\n<li>removeFirst on an empty list should be a no-op, (or throw an exception).</li>\n<li><code>last</code> was dangling.</li>\n<li>Setting things to null of the removed first node, is not done in OOP, is\nleft to the garbage collection. This also removes the need for an extra variable. And the resulting binary code is smaller.</li>\n</ul>\n\n<p>So:</p>\n\n<pre><code>public void removeFirst() {\n if (first != null) {\n if (first == last) { // Either this.\n last = null;\n }\n first = first.next;\n if (first == null) { // Or this.\n last = null;\n }\n }\n}\n</code></pre>\n\n<p>One can only remove the first, when there is one.\nThen the last might be the biblical first.</p>\n\n<p>This is for the single linked list, where a node has just one <em>next</em> pointer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:09:37.463", "Id": "455422", "Score": "0", "body": "@OverLordGoldDragon _setting fields/variables to null_ in order to help garbage collection faster saving memory, has almost no discernible gain (time gain in the future). As there is an extra assignment it might even be slower, **I take it that a Node is not held outside of the list.**" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:24:54.030", "Id": "455426", "Score": "1", "body": "I like this answer, it addresses the core quesiton about having the (unnecessary) `second` variable, and it also resolves the issue with the possible dangling `last` pointer if `first == last`. It may need some better text to describe those aspects, but this is a review with good observations IMHO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T15:51:37.107", "Id": "455437", "Score": "0", "body": "@rolfl , J. Eggen I tried keeping the question minimal, but apparently the intent wasn't too clear - see updated. The most relevant part of this answer is the third bullet point - but is that all there's to say on it? If so, that's fair, but that's the point that should be discussed/emphasized - the rest of the answer's not really relevant (also `last = null` handling is incorrect per standard implementations, as removing from an empty list should throw an exception)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T16:05:18.060", "Id": "455444", "Score": "0", "body": "My apology too. Though if the list contains one element last == first, and a removeFirst should null out `last`. The removed node, and neither its fields need not be nulled in garbage collected languages. It is bad style as it delivers noise to the code reader, and the code writer should better concentrate on functional code. For this reason I automatically just gave the most minimal code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:23:58.443", "Id": "455507", "Score": "0", "body": "So can you (or anyone) confirm that _setting to null_ is **redundant**, and happens automatically by the garbage collector? This is the main idea I'm trying to understand" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T10:48:17.683", "Id": "455540", "Score": "0", "body": "Yes it is redundant, the life time analysis of objects takes care of that & more efficiently. As confirmation readers may **upvote** this comment." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:49:50.957", "Id": "233068", "ParentId": "233065", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:20:19.203", "Id": "233065", "Score": "5", "Tags": [ "java", "linked-list", "comparative-review", "memory-management" ], "Title": "Linked list: removing first element" }
233065
<p>The following program is comprised of three files and is aimed to be used as a Debian-Apache-MySQL-PHP-HTTPS version-agnostic environment bootstrapper.</p> <p>It is aimed to be used on raw Debian systems (anything that doesn't come with the OS wasn't installed) and to establish web domain associated web applications.</p> <h2>The program</h2> <h3>File 1</h3> <p>This file contains fundamental installation and/or configuration commands and comprised of two parts:</p> <ul> <li><p>The first part is a <code>cat</code> heredocument for <code>.profile</code> aimed to declare some global modes, variables and functions ("global" as to effect all shell sessions) that from my experience are harmless although global.</p></li> <li><p>The second part is a "sourcing" of <code>.profile</code> to ensure the variables will take effect in the very first shell session in which they are declared at and also after every booting of Debian.</p></li> </ul> <p>File 1 code is as follows (clarifications available below the code block).</p> <pre><code>#!/bin/bash cat &lt;&lt;-EOF &gt;&gt; "$HOME"/.profile set -x complete -r export war="/var/www/html" export dmp="phpminiadmin" export -f war ssr tmd # Create execution shortcuts to the following functions: war() { cd $war/ } ssr() { chown -R www-data:www-data "$war"/ chmod -R a-x,a=rX,u+w "$war"/ systemctl restart apache* chmod -R 000 "$war"/"$dmp"/ } tmd() { chmod -R a-x,a=rX,u+w "$war"/"$dmp"/ echo "chmod -R 000 "$war"/"$dmp"/" | at now + 1 hours } EOF source "$HOME"/.profile 2&gt;/dev/null </code></pre> <h3>File 1 modes</h3> <ul> <li>The mode <code>set -x</code> means constant working in full debug mode</li> <li>The mode <code>complete -r</code> means constant removal of messy output of programmable completion (by calling to functions, etc) common in full debug mode</li> </ul> <h3>File 1 variables</h3> <ul> <li>The <code>war</code> variable's value reflects a user's preferred <em>Web Application Root</em> directory</li> <li>The <code>dmp</code> variable's value reflects a user's preferred <em>Database Management Program</em> (such as <em>phpMiniAdmin</em>)</li> </ul> <h3>File 1 functions</h3> <ul> <li>The function <code>war</code> means something like "navigate to Web Application Root easy and fast"<br></li> <li>The function <code>ssr</code> means <strong>Secured Server Restart:</strong>; that is, restart web server with repeating basic security directives that might have been mistakenly changed, as well as allowing temporary management of MySQL database by a database management program<br></li> <li>The function <code>tmd</code> means <em>Temporarily Manage Database</em> and is useful after DB-manager security lock by <code>ssr()</code></li> </ul> <h3>File 2</h3> <p>This file contains basic application installation and/or configuration commands.</p> <pre><code>#!/bin/bash apt update -y apt upgrades ufw sshguard unattended-upgrades wget curl git zip unzip tree -y ufw --force enable ufw allow 22,25,80,443 apt install lamp-server^ python-certbot-apache curl -sS https://getcomposer.org/installer -o composer-setup.php php composer-setup.php --install-dir=/usr/local/bin --filename=composer a2enmod http2 deflate expires </code></pre> <h3>File 3</h3> <p>This file uses to create an Apache virtual host and associated files.</p> <p>This file should be executed only after creating a CMS-contexed database on top of MySQL program, based on a single pattern of data, <strong>the web domain</strong> which also uses as the name for:</p> <ul> <li>Web application DB user</li> <li>Web application DB instance</li> <li>Web application directory (explained in following chapter)</li> </ul> <p>The file:</p> <pre><code>#!/bin/bash read -p "Have you created db credentials already?" yn case $yn in [Yy]* ) break;; [Nn]* ) exit;; * ) echo "Please create db credentials and then comeback;";; esac function read_and_verify { read -p "$1:" tmp1 read -p "$2:" tmp2 if [ "$tmp1" != "$tmp2" ]; then echo "Values unmatched. Please try again."; return 2 else read "$1" &lt;&lt;&lt; "$tmp1" fi } read_and_verify domain "Please enter the domain of your web application twice" read_and_verify dbrootp "Please enter the app DB root password twice" read_and_verify dbuserp "Please enter the app DB user password twice" cat &lt;&lt;-EOF &gt; /etc/apache2/sites-available/$domain_2.conf &lt;VirtualHost *:80&gt; ServerAdmin admin@"$domain_2" ServerName ${domain_2} ServerAlias www.${domain_2} DocumentRoot $war/${domain_2} ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; EOF ln -sf /etc/apache2/sites-available/"$domain_2".conf /etc/apache2/sites-enabled/ certbot --apache -d "$domain_2" -d www."$domain_2" </code></pre> <h2>Possible appendix - install Drupal</h2> <p>Because installing a composer-driven drupal project with a local Drush was the original aim of this program, I append the following:</p> <pre><code>composer create-project drupal-composer/drupal-project "$war"/"$domain" cp "$drt/$domain"/wp-config-sample.php "$war/$domain"/wp-config.php drush --root="$war" --uri="$domain" pm install redirect token metatag draggableviews drush --root="$war" --uri="$domain" en language content_translation redirect token metatag draggableviews </code></pre> <h2>Notes</h2> <ul> <li>The program doesn't cover backups because I personally believe that every hosting provider and that includes dedicating hosting, whether semi (commercial) or full (private), should include a reliable, most preferably communally maintained automatic daily backup mechanism, alongside a manual backup standardized routine procedure (say doing manual backup each quarter or half a year).</li> <li>The program doesn't cover web application upgrades because I personally believe that every CMS should include an upgrade mechanism of its own by default, without bestowing upon users the need do maximal upgrade automation from backend.</li> </ul> <h2>My question</h2> <p><strong>How would you revise this Debian-Apache-MySQL-PHP-HTTPS version-agnostic environment bootstrapper?</strong></p>
[]
[ { "body": "<p>Firstly, it's wrong to write a Bash shebang at the start of <code>.profile</code>, for two reasons:</p>\n\n<ol>\n<li>It's not an executable script, but intended to be sourced from other shell environments</li>\n<li><code>.profile</code> is sourced by the user's shell, which need not be Bash.</li>\n</ol>\n\n<p>The bashisms should be rewritten if possible; those that can't (such as <code>complete -r</code>) should be migrated to <code>.bash_profile</code>.</p>\n\n<hr>\n\n<p>These look a little odd:</p>\n\n<blockquote>\n<pre><code> chmod -R a-x,a=rX,u+w \"$war\"/\"$dmp\"/\n echo \"chmod -R 000 \"$war\"/\"$dmp\"/\" | at now + 1 hours\n</code></pre>\n</blockquote>\n\n<p>In the first, there's no need to leave double-quoted string for the <code>/</code> characters. In the second, we definitely don't want argument splitting within the variables. I'd rewrite those two lines as:</p>\n\n<pre><code> chmod -R a-x,a=rX,u+w \"$war/$dmp/\"\n echo \"chmod -R 000 $war/$dmp/\" | at now + 1 hours\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>curl -sS https://getcomposer.org/installer -o composer-setup.php\nphp composer-setup.php --install-dir=/usr/local/bin --filename=composer\n</code></pre>\n</blockquote>\n\n<p>Firstly, we don't check that <code>curl</code> succeeded before depending on its results. Consider <code>set -e</code> for that.</p>\n\n<p>Secondly, and more critically, there's no verification that what we downloaded is safe to execute. I'd expect at least a simple SHA checksum before executing that PHP program.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>read -p \"Have you created db credentials already?\" yn\ncase $yn in\n [Yy]* ) break;;\n [Nn]* ) exit;;\n * ) echo \"Please create db credentials and then comeback;\";;\nesac\n</code></pre>\n</blockquote>\n\n<p>Firstly, a simple spelling mistake - \"come back\" has lost its space.\nSecondly, it seems wrong to exit with no message when <code>n</code> is entered, but to assume <code>n</code> when an invalid reply is given.</p>\n\n<p>I'd expect something like:</p>\n\n<pre><code>read -p \"Have you created db credentials already? [y/N] \" yn\ncase \"$yn\" in\n [Yy]* ) true ;;\n [Nn]* ) echo &gt;&amp;2 \"Please create db credentials and repeat this command;\"; exit ;;\n * ) echo &gt;&amp;2 \"Please respond with Y or N.\"; exit 1 ;;\nesac\n</code></pre>\n\n<hr>\n\n<p>Have you got the prompts right here?</p>\n\n<blockquote>\n<pre><code>function read_and_verify {\n read -p \"$1:\" tmp1\n read -p \"$2:\" tmp2\n if [ \"$tmp1\" != \"$tmp2\" ]; then\n echo \"Values unmatched. Please try again.\"; return 2\n else\n read \"$1\" &lt;&lt;&lt; \"$tmp1\"\n fi\n}\n\nread_and_verify domain \"Please enter the domain of your web application twice\" \nread_and_verify dbrootp \"Please enter the app DB root password twice\" \nread_and_verify dbuserp \"Please enter the app DB user password twice\"\n</code></pre>\n</blockquote>\n\n<p>The first read, where the user is prompted with the variable name is unexpected; that's not in the user's world model, and the second prompt then asks for the same thing (in different words) \"twice\":</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>domain:foo\nPlease enter the domain of your web application twice:foo\n</code></pre>\n\n<p>I think the prompt should be formed from <code>$2</code> each time:</p>\n\n<pre><code>read_and_verify() {\n read -p \"Please enter $2: \" tmp1\n read -p \"Please enter $2 again to confirm: \" tmp2\n if [ \"$tmp1\" != \"$tmp2\" ]; then\n echo &gt;&amp;2 \"Values unmatched. Please try again.\"; return 2\n fi\n\n declare \"$1=$tmp1\"\n}\n\nread_and_verify domain \"the domain of your web application\" \nread_and_verify dbrootp \"the app DB root password\" \nread_and_verify dbuserp \"the app DB user password\"\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code>Please enter the domain of your web application: foo\nPlease enter the domain of your web application again to confirm: foo\n</code></pre>\n\n<p>All that said, requiring user to re-type (or to copy-paste) these values is annoying, and no more effective than re-printing them and asking for confirmation:</p>\n\n<pre><code>read_and_verify() {\n read -p \"Please enter $2: \" \"$1\"\n read -p \"Please confirm $2: ${!1} [y/N] \" yn\n case \"$yn\" in\n [Yy]*) true ;;\n *) echo &gt;&amp;2 \"Cancelled.\" return 2\n esac\n}\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code>Please enter the domain of your web application: foo\nPlease confirm the domain of your web application: foo [y/N] y\n</code></pre>\n\n<p>In fact, I might shuffle things around, to gather all the inputs, and present a single summary for confirmation:</p>\n\n<pre><code>ask_yn() {\n while read -p \"$* [y/n] \" -n1\n do\n case \"$REPLY\" in\n ?) echo ;;&amp;\n [Yy]) return 0 ;;\n [Nn]) return 1 ;;\n esac\n done\n}\n\nuntil\n read -p 'Please enter the domain of your web application: ' domain\n read -p 'Please enter the app DB root password: ' dbrootp\n read -p 'Please enter the app DB user password: ' dbuserp\n printf '%s: \"%s\"\\n' \\\n 'Application domain' \"$domain\" \\\n 'Database root password' \"$dbrootp\" \\\n 'Database user password' \"$dbuserp\"\n ask_yn 'Are these details correct?'\ndo\n true\ndone\n</code></pre>\n\n<p>There's one case where there's value in asking for the same input twice, and that's when the user is <em>setting</em> an unseen value (such as when using the <code>passwd</code> program). The reasoning there is that a mistake can't be detected or easily corrected after the fact (because you're locked out of your account until/unless you can re-create the same typo).</p>\n\n<p>Here, we're just <em>storing</em> values, and if we find the values are wrong, we can easily fix them up. (In fact, we could even test the passwords work before accepting the settings, by making a simple connection to the database).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:30:18.870", "Id": "455427", "Score": "0", "body": "Hi, thanks; I never meant to put `Bash shebang at the start of .profile`; it was just for copy-pasting the content as script. Maybe I should edit to state that so I won't be further interpreted this way. Regarding the prompts; it seems to me from `echo` test for all three prompt comparisons that it works --- I do get `example` for them. Regarding your last sentence in the answer --- I misunderstood what copy-pasting is not more effective than printing? Please example this," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T21:18:19.757", "Id": "455477", "Score": "0", "body": "I think I understand everything besides \"unexpected\"; do you mean you found the phrasing bad and that in any case it's just better to re-print the value before the user and confirm?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:31:27.280", "Id": "455508", "Score": "0", "body": "The \"unexpected\" part is as a user, as shown in the exchange I show immediately after that sentence. The first prompt is `domain` (the shell variable name), rather than something in the user's world model, and the second prompt asks for the same thing to be entered twice (some users will interpret that to mean they should enter `example.com example.com` there. The alternatives I show are intended to be clearer/easier for the user." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:56:02.433", "Id": "455512", "Score": "0", "body": "I've expanded that description, and also suggested a single confirmation using a `do`/`until` loop. I hope that's helpful." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:52:32.383", "Id": "233069", "ParentId": "233067", "Score": "6" } } ]
{ "AcceptedAnswerId": "233069", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T13:31:29.907", "Id": "233067", "Score": "5", "Tags": [ "performance", "security", "bash", "server", "drupal" ], "Title": "Debian-Apache-MySQL-PHP-HTTPS version-agnostic environment bootstrapper" }
233067
<p>This code works, but I don't know if there are better and especially safer ways to do this.</p> <p>For context: this is a Django view (Python) and I wanted to unify the deletion methods because there were many of them.</p> <pre><code>def delete(request, class_name, object_ID): obj = get_object_or_404(eval(class_name), id=object_ID) obj.delete() return redirect(dashboard) </code></pre> <p>Now I know that the <code>eval()</code> method should be used with caution, but would it be enough to wrap a try-catch-method around it or should I do something like a switch-case, or is it even ok to use the code as is?</p> <p>It will be called from this url route (<code>urls.py</code>):</p> <pre><code>path('delete/&lt;str:className&gt;/&lt;int:object_ID&gt;', views.delete) </code></pre> <blockquote> <p>Note: This route will only be accessible to employees and there will be a permission check, so my question is about best practice and potential problems.</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T21:12:27.407", "Id": "455608", "Score": "0", "body": "While I believe the question is answerable as-is, I think it would add value and help answer the \"ok to use\" question if you included a few examples of how you call this function in your views. Also, how is dashboard defined?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T21:30:47.943", "Id": "455609", "Score": "0", "body": "@409_Conflict The dashboard view is just another view with no parameters, I can't imagine how it could cause problems. I am calling this view directly from the `urls.py` and added an example above." } ]
[ { "body": "<p>The use of <code>eval()</code> here is less than ideal as it allows you to call the URL <code>delete/User/3/</code>, for instance, and it will work against all odds. Worse, you can call the URL <code>delete/delete/9</code> where eval will resolve <code>delete</code> to this view function and lead to all kind of weird behavior.</p>\n\n<p>So the first step is to restrict which symbols can be found from there. The easiest way is to retrieve the attribute directly from your models:</p>\n\n<pre><code>from . import models\n\n...\n\ndef delete(request, type_name, object_id):\n try:\n cls = getattr(models, type_name)\n except AttributeError:\n raise Http404\n get_object_or_404(cls, id=object_id).delete()\n redirect(dashboard)\n</code></pre>\n\n<p>But this is still too large as anything that you imported in <code>models</code> can still be retrieved. So you're better off using a base class in your <code>models.py</code> that only your deletable models will inherit from:</p>\n\n<pre><code>class Deletable:\n def can_delete(self, user):\n return user.is_active and user.is_staff\n\nclass OneOfYourCustomModel(Deletable, models.Model):\n # whatever\n</code></pre>\n\n<p>And check in your view that whatever you get is Deletable:</p>\n\n<pre><code>def delete(request, type_name, object_id):\n try:\n cls = getattr(models, type_name)\n except AttributeError:\n raise Http404\n if inspect.isclass(cls) and issubclass(cls, models.Deletable):\n get_object_or_404(cls, id=object_id).delete()\n else:\n raise Http404\n redirect(dashboard)\n</code></pre>\n\n<p>You'll also note that it also lead to easy customization of which user can delete what: you just need to override one method and add proper logic (<em>eg</em> raising 403 forbidden) in your view. This can be more useful than the <a href=\"https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#django.contrib.admin.views.decorators.staff_member_required\" rel=\"nofollow noreferrer\"><code>@staff_member_required</code></a> in case your models can be associated to (owned by) a particular user:</p>\n\n<pre><code>class MyOwnedModel(Deletable, models.Model):\n owner = models.ForeignKey(django.contrib.auth.models.User, …)\n\n def can_delete(self, user):\n return user == self.owner or super().can_delete(user)\n</code></pre>\n\n<p>But of course, if only the staff can delete things, the decorator is plenty sufficient.</p>\n\n<hr>\n\n<p>Lastly, it would be good to separate the \"retrieve the actual model\" logic from the \"delete the particular instance of that model\" one. The latter being the responsibility of the view, but the former would better fit as a custom <a href=\"https://docs.djangoproject.com/en/2.2/topics/http/urls/#registering-custom-path-converters\" rel=\"nofollow noreferrer\">URL converter</a>.</p>\n\n<p>The main advantage being that you don't need to handle the 404s for unknown models in your view, django will take care of that itself if your converter ever raises a <code>ValueError</code>. Going this route, you can have a <code>converters.py</code>:</p>\n\n<pre><code>from inspect import isclass\n\nfrom django.urls.converters import StringConverter\n\nfrom . import models\n\n\nclass DeletableConverter(StringConverter):\n def to_python(self, value):\n try:\n cls = getattr(models, value)\n except AttributeError:\n raise ValueError\n if not isclass(cls) or not issubclass(cls, models.Deletable):\n raise ValueError\n return cls\n\n def to_url(self, value):\n return value.__name__\n</code></pre>\n\n<p>Usage in your <code>urls.py</code>:</p>\n\n<pre><code>from django.urls import path, register_converter\n\nfrom . converters import DeletableConverter\n\n\nregister_converter(DeletableConverter, 'deletable')\n\n\nurlpatterns = [\n …,\n path('delete/&lt;deletable:model&gt;/&lt;int:object_id&gt;', views.delete),\n …,\n]\n</code></pre>\n\n<p>And in your view:</p>\n\n<pre><code>def delete(request, model, object_id):\n instance = get_object_or_404(model, id=object_id)\n if instance.can_delete(request.user):\n # or a simple @staff_member_required decorator\n instance.delete()\n redirect(dashboard)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T10:36:02.453", "Id": "455769", "Score": "0", "body": "Thanks a lot, that all sounds very good, I will try to implement this! Like I said in my post, I took care of the permission problem already, by using `@login_required` and `@staff_member_required` decorators for methods like this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T11:59:55.920", "Id": "455776", "Score": "0", "body": "@creyD I expanded a bit on how it should best be implemented. And added a discussion about the usecase of my approach compared to `@staff_member_required`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T14:11:03.487", "Id": "455779", "Score": "0", "body": "Thank you yet again for your detailed answer and your edits! :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T08:48:18.367", "Id": "233148", "ParentId": "233071", "Score": "2" } } ]
{ "AcceptedAnswerId": "233148", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T14:21:47.733", "Id": "233071", "Score": "2", "Tags": [ "python", "django" ], "Title": "Django Unified Method for Deleting Instances of Any Model" }
233071
<p>I have the following arrays which save the MAC-adresses of a lot of bluetooth beacons and their positions in a building:</p> <pre class="lang-java prettyprint-override"><code>private static final String[][] MAC_ADDRESSES_A_BLUETOOTH = {{"B09122F5D126", "210.105"}, {"B09122F5F26B", "136.121"}, {"B09122F5F619", "181.172"}}; ... private static final String[][] MAC_ADDRESSES_Q_BLUETOOTH = {{"B09122F5D124", "210.105"}, {"B09122F5F26Z", "136.121"}, {"B09122F5F61Q", "181.172"}}; </code></pre> <p>Then I'm looking for the matching triple based on a current triple:</p> <pre class="lang-java prettyprint-override"><code>private String[][] compareArrays(String[] beacon) { if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_A_BLUETOOTH))) { return MAC_ADDRESSES_A_BLUETOOTH; } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_B_BLUETOOTH))) { return MAC_ADDRESSES_B_BLUETOOTH; } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_C_BLUETOOTH))) { return MAC_ADDRESSES_C_BLUETOOTH; } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_D_BLUETOOTH))) { return MAC_ADDRESSES_D_BLUETOOTH; } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_F_BLUETOOTH))) { return MAC_ADDRESSES_F_BLUETOOTH; } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_G_BLUETOOTH))) { return MAC_ADDRESSES_G_BLUETOOTH; } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_H_BLUETOOTH))) { return MAC_ADDRESSES_H_BLUETOOTH; } else if (Arrays.equals(beacon, getFirstArray(MAC_ADDRESSES_I_BLUETOOTH))) { return MAC_ADDRESSES_I_BLUETOOTH; } ... } else { return null; } } </code></pre> <p>This code looks horrible and it bugs me. Is there an easier way to do this without having to write 16 <code>if</code> statements? <code>getFirstArray</code> returns all first values from a two-dimensional array.</p>
[]
[ { "body": "<p>For readability, use an Object instead of a 2d array.</p>\n\n<p>E.G:</p>\n\n<pre><code>public class BluetoothMacAddress {\n private String macAddress;\n private float positionInBuilding;\n}\n</code></pre>\n\n<p>Use <code>java.util.List</code>, then you can have a list of lists:</p>\n\n<pre><code>private sttaic final List&lt;MacAddress&gt; MAC_ADDRESSES_A_BLUETOOTH = Arrays.asList(\n new BluetoothMacAddress(\"B09122F5D126\", \"210.105\"), \n new BluetoothMacAddress(\"B09122F5F26B\", \"136.121\"), \n new BluetoothMacAddress(\"B09122F5F619\", \"181.172\"));\n\nprivate static final List&lt;List&lt;MAC_ADDRESSES&gt;&gt; MAC_ADDRESSES = Arrays.asList(\n MAC_ADDRESSES_A_BLUETOOTH,\n MAC_ADDRESSES_B_BLUETOOTH \n ...\n);\n</code></pre>\n\n<p>Your new method would then look something like this:</p>\n\n<pre><code>private MacAddress compareArrays(String[] beacon) {\n for (List&lt;MacAddress&gt; macAddresses : MAC_ADDRESSES ) {\n if (Arrays.equals(beacon, getFirstArray(macAddresses))) {\n return macAddresses;\n }\n }\n // not found\n return null;\n}\n</code></pre>\n\n<p>You'd have to change the <code>beacon</code> parameter to be a <code>MacAddress</code> too, or convert the <code>MacAddress</code> to a <code>String[]</code> (or visa-versa).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T17:44:14.717", "Id": "455462", "Score": "0", "body": "Used your solution, needed to change a lot in my other code, but looks cleaner in the end." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T17:14:29.990", "Id": "233080", "ParentId": "233077", "Score": "2" } } ]
{ "AcceptedAnswerId": "233080", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T16:26:40.053", "Id": "233077", "Score": "3", "Tags": [ "java", "array" ], "Title": "Easier way to find matching array from a lot of arrays" }
233077
<p>Does anybody know how to find pair of adjacent prime numbers in two-dimensional array, quicker than this? I'm talking especially about this part which looks for adjacent numbers not about function finding prime numbers or anything else in the code.</p> <pre><code>//looking for first prime number of pair for(w=0; w&lt;5; w++) { for(k=0; k&lt;5; k++) { if(is_prime(tab[w][k])==1) { //looking for second number if pair in indices with are only higher then the first prime number for(w2=w; w2&lt;5; w2++) { for(k2=k; k2&lt;5; k2++) { if(is_prime(tab[w2][k2])==1) { //setting conditions for adjacent number (which isnt the same number as the first) if(abs(w-w2)&lt;=1&amp;&amp;abs(k-k2)&lt;=1&amp;&amp;((w==w2)+(k==k2))!=2) //putting adjacent prime pairs one after another into second array {tab2[i]=w; tab2[i+1]=k; tab2[i+2]=w2; tab2[i+3]=k2; i+=4;} }}}}}} </code></pre> <pre><code>#include&lt;stdio.h&gt; #include&lt;string.h&gt; #include&lt;stdlib.h&gt; #include&lt;math.h&gt; int is_prime(int); //function checking if number is prime int is_prime(int x) { int count=0, i; if(x&lt;2) return 0; for(i=2; i&lt;x; i++) {if((x%i)==0) count++;} if(count==0) return 1; else return 0; } int main() {int k, w, tab[5][5], k2, w2; printf("Input: "); //inputting data into two-dimensional array for(w=0; w&lt;5; w++) { for(k=0; k&lt;5; k++) { if(scanf("%d", &amp;tab[w][k])==0) { printf("Incorrect input"); return 1; } }} int tab2[1000], i=0; //looking for first prime number of pair for(w=0; w&lt;5; w++) { for(k=0; k&lt;5; k++) { if(is_prime(tab[w][k])==1) { //looking for second number if pair in indices with are only higher then the first prime number for(w2=w; w2&lt;5; w2++) { for(k2=k; k2&lt;5; k2++) { if(is_prime(tab[w2][k2])==1) { //setting conditions for adjacent number (which isnt the same number as the first) if(abs(w-w2)&lt;=1&amp;&amp;abs(k-k2)&lt;=1&amp;&amp;((w==w2)+(k==k2))!=2) //putting adjacent prime pairs one after another into second array {tab2[i]=w; tab2[i+1]=k; tab2[i+2]=w2; tab2[i+3]=k2; i+=4;} }}}}}} //i is used also as counter of pairs w=i; //printing number of pairs printf("%d\n", i/4); //printing the pairs for(i=0; i&lt;w; i+=4) printf("%d %d %d %d\n", tab2[i], tab2[i+1], tab2[i+2], tab2[i+3]); return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T18:51:26.637", "Id": "455472", "Score": "2", "body": "You should do some reasonable and consistent indentation clarifying the several code blocks' scope. There's a number of styles you can choose from. But how it's like just now, that's not matching any of these. BTW there are even tools like _astyle_ to support you with this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T19:23:43.810", "Id": "455688", "Score": "0", "body": "Did you write this or did you find it elsewhere?" } ]
[ { "body": "<p>Your function <code>is_prime</code> is extremely inefficient perfomance wise called every time you want to check for prime numbers (especially for larger ranges).<br>\nYou're going to loop over all the values and check every time it's called.</p>\n\n<p>You should rather consider to implement a memoizing algorithm like the <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Erasthotenes</a> to check for prime numbers in 1st place to improve the overall performance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T19:55:49.883", "Id": "233084", "ParentId": "233083", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T18:01:23.417", "Id": "233083", "Score": "-5", "Tags": [ "performance", "c", "array", "primes" ], "Title": "Find pair of adjacent prime numbers in a two-dimensional array" }
233083
<p>When learning a new language, one of my first tasks I like to go through is writing a few different sorting algorithms in that language to help familiarize myself with the syntax and see if there are creative ways that algorithm can be conceived in the language. </p> <p>In Go, I wanted to use this as an opportunity to work with Goroutines and see if there are other interesting functions/uses that I had missed while writing this out. Effectively, my goal is to have the divide-and-conquer portion of the algorithm happen concurrently. </p> <p>One possible area of improvement would be to have the combination of the left and right sides also happen concurrently, rather than wait for the left and right sides to complete before moving on to combining. Overall, my concerns boil down to:</p> <p>1) How could I, if possible, use concurrency inside/around the for loops from the mergesort function to speed up the end portion of the algorithm?</p> <p>2) Other than the algorithm itself which, to my understanding, already is in the "sort" package, are there any other Go-specific problems with my code that could be made more..."Go-thic"?</p> <pre><code>package main import ( "crypto/rand" "fmt" "os" "strconv" ) var ( nums []byte //The slice of numbers we want to sort numVals int = -1 ) //User can optionally add a parameter that determines how many random numbers will be sorted //If none are provided, 100 will be used func main() { if len(os.Args) &gt;= 2 { numVals, _ = strconv.Atoi(os.Args[1]) } else { numVals = 100 } nums = initSlice() ms := make(chan []byte) go mergeSort(nums, ms) nums = &lt;-ms for _, value := range nums { fmt.Printf("%d\n", value) } } func initSlice() []byte { vals := make([]byte, numVals) _, err := rand.Read(vals) if err != nil { panic(err) } return vals } func mergeSort(arr []byte, ms chan []byte) { if len(arr) &lt;= 1 { //base case ms &lt;- arr return } leftMS := make(chan []byte) go mergeSort(arr[:len(arr)/2], leftMS) rightMS := make(chan []byte) go mergeSort(arr[len(arr)/2:], rightMS) left, right := &lt;-leftMS, &lt;-rightMS sortArr := make([]byte, len(arr)) lIndex, rIndex := 0, 0 //Combine both sides for lIndex &lt; len(left) &amp;&amp; rIndex &lt; len(right) { leftLeast := left[lIndex] &lt;= right[rIndex] if leftLeast { sortArr[lIndex+rIndex] = left[lIndex] lIndex++ } else { sortArr[lIndex+rIndex] = right[rIndex] rIndex++ } } //Fill in whichever 'pile' is empty if lIndex &lt; len(left) { for ; lIndex &lt; len(left); lIndex++ { sortArr[lIndex+rIndex] = left[lIndex] } } if rIndex &lt; len(right) { for ; rIndex &lt; len(right); rIndex++ { sortArr[lIndex+rIndex] = right[rIndex] } } ms &lt;- sortArr } </code></pre> <p>Of course, please feel free to add any other suggestions. Thanks!</p>
[]
[ { "body": "<ol>\n<li><p>Keep your global environment clean - no need to define <code>nums</code> and <code>numVals</code> globally. Just create them in the <code>main</code> function and pass them to the appropriate functions.</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>nums := initSlice(size)\n</code></pre></li>\n<li><p>You can save on memory by creating the <code>sortArr</code> array at the initialization phase, and pass it along with <code>arr</code>.</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>go mergeSort(arr[:len(arr)/2], res[:len(sortArr)/2], leftMS)\ngo mergeSort(arr[len(arr)/2:], res[len(sortArr)/2:], rightMS)\n</code></pre></li>\n<li><p>You can init <code>numVals</code> to <code>100</code> and then change it if an arg was provided:</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>size := 100\nif len(os.Args) &gt;= 2 {\n size, _ = strconv.Atoi(os.Args[1])\n}\n</code></pre></li>\n<li><p>Add a buffer to <code>leftMS</code> and <code>rightMS</code>. This way their goroutines will be closed when they are done. Currently if the right side is done before the left, then it will have to wait because you are reading <code>leftMS</code> first.</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>leftMS, rightMS := make(chan []byte, 1), make(chan []byte, 1)\n</code></pre></li>\n<li><p>Comments always start with an empty space: <code>//Combine both sides</code> -> <code>// Combine both sides</code></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-09T01:15:55.290", "Id": "456796", "Score": "0", "body": "Really appreciate the feedback. I've updated the algorithm since this post, but hadn't taken into account points 1, 3, and 5. They have been updated [here](https://github.com/c4llmeco4ch/goStudentProjects/blob/master/sortingAlgs/mergeSort/mergeSort.go)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-08T18:33:22.450", "Id": "233642", "ParentId": "233087", "Score": "4" } }, { "body": "<ol>\n<li><p>I don't think there is actually a need for two channel. Whether the sub-slice is from the left part or the right part does not matter when you merge, you can simply use a single channel.</p>\n\n<pre><code>MS := make(chan []byte)\ngo mergeSort(arr[:len(arr)/2], MS)\ngo mergeSort(arr[len(arr)/2:], MS)\nleft, right := &lt;-MS, &lt;-MS\n</code></pre>\n\n<p>This is better because it avoids potential blocking when <code>right</code> is completed before <code>left</code>.</p></li>\n<li><p>Repitively calculating <code>lIndex</code>+<code>rIndex</code> is verbose. Use a variable to record index of <code>sortArr</code>. And use <code>var</code> statement to declare variables that does not need initial value. Go's <code>if</code> statement allows a short statement before the condition; use it to simplify variables:</p>\n\n<pre><code>var index, lIndex, rIndex int\n//Combindexne both sides\nfor lIndex &lt; len(left) &amp;&amp; rIndex &lt; len(right) {\n if l, r := left[lIndex], right[rIndex]; l &lt;= r {\n sortArr[index] = l\n lIndex++\n } else {\n sortArr[index] = r\n rIndex++\n }\n index++\n}\n</code></pre></li>\n<li><p>To fill the remaining <code>sortArr</code>, Go has a <code>copy</code> builtin. Since only one slice is not empty, it is safe to copy without advancing <code>index</code>.</p>\n\n<pre><code>copy(sortArr[index:], left[lIndex:])\ncopy(sortArr[index:], right[rIndex:])\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-22T16:41:13.990", "Id": "234494", "ParentId": "233087", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T21:19:48.440", "Id": "233087", "Score": "2", "Tags": [ "recursion", "go", "concurrency", "mergesort" ], "Title": "Recursive Mergesort using goroutines" }
233087
<p>I would like someone to review my code on find indices of 2 numbers in array that sums up to an number. Following is the code that I have tried and it works. The real issue in the code is I am doing Map.lookup twice. Is there a way to avoid it. </p> <pre><code>Input [1,2,3,4,5] 5 Output [2,1] Input [1,2,3,4,5] 4 Output [2,0] </code></pre> <p>Code</p> <pre><code>import Data.Char import Data.Maybe import Data.List import qualified Data.Map as Map {-- - two sums - https://leetcode.com/problems/two-sum/ - --} twosums :: [Int]-&gt; Int -&gt; [Int] twosums [] _ = [] twosums k g = flip twosum' Map.empty $ zip k [0..] where twosum'::[(Int, Int)] -&gt; Map.Map Int Int -&gt; [Int] twosum' [] _ = [] twosum' (x:xs) mp | Map.lookup (g - fst x) mp == Nothing = twosum' xs qmap' | otherwise = [snd x, fromMaybe (-1) $ Map.lookup ( g - fst x) mp ] where qmap' = Map.insert (fst x) (snd x) mp <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T19:37:10.783", "Id": "455603", "Score": "1", "body": "The reason for off-topic is \"Code not implemented or not working as intended\". The code is working as intended. There are no bugs. I just want someone to help me on how I can avoid 2 lookup calls." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T13:00:01.887", "Id": "455651", "Score": "0", "body": "`twosum' ((n,i):xs) mp = case Map.lookup (g - n) mp of Nothing -> twosum' xs $ Map.insert n i mp; Just j -> [i, j]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T21:54:23.337", "Id": "455706", "Score": "0", "body": "Thanks Gurkenglas, I found the answer on Haskell IRC beginner chat." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T22:46:43.250", "Id": "233091", "Score": "3", "Tags": [ "haskell" ], "Title": "find indices of 2 numbers in array that sums up to an number" }
233091
<p>I want to make sure that I am writing the code correctly and fully understand what is needed. My biggest concern is what tags to use, (<code>?</code> <code>*</code> <code>|</code> etc.)</p> <blockquote> <ol start="5"> <li><p>The element stories<br> 5.1. The element stories contains 0 or more story elements. </p></li> <li><p>The element story<br> 6.1. The element story has an enumerated attribute updated that can only have the values true, false, or unknown. The default is true. Represents whether or not the story was updated since the last time the feed was downloaded.<br> 6.2. The element story’s first element is the url element. Must appear exactly once. A link to the story.<br> 6.3. The element story’s second element is the title element. Must appear exactly once.<br> 6.4. The element story’s third element is the preview element. Must appear exactly once. A short introduction to the story. Usually, about 1 sentence.<br> 6.5. The element story’s element content is optional, but if present, appears no more than once. The story. Some sites allow the story text in feeds, some don’t. That is why it is optional<br> 6.6. The element story’s element video is optional, but if present, appears no more than once. A link to an optional video.<br> 6.6.1. The order of the elements content and video does not matter. If both are present, content can be first or video can be first.<br> 6.7. The element story’s last element publication-date is optional, but if present, appears no more than once and must be the last element. The date the story was published. </p></li> <li><p>The element title<br> 7.1. The element title can contain text</p></li> </ol> </blockquote> <h2>My code:</h2> <pre><code>&lt;!ELEMENT stories (stories*)&gt; &lt;!ELEMENT story (update true|false, url?, title?, preview?, content?, video?, publication-date?&gt; &lt;!ELEMENT title &gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T00:12:15.720", "Id": "455483", "Score": "0", "body": "Do you know why you have to use DTDs instead of the more modern and more expressive XSD? Do you know the difference between an _element_ and an _attribute_?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T02:57:01.583", "Id": "455493", "Score": "1", "body": "Was part of a class assignment, and have to write it in a dtd, i have the XML for them alredy, just not fully understanding the dtd." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:09:09.563", "Id": "455504", "Score": "1", "body": "IMO this question is quite similar to [your previous one](https://codereview.stackexchange.com/q/233092/) in that it seems to lack sufficient code context for a meaningful review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T15:24:34.057", "Id": "455577", "Score": "0", "body": "Yes this is a code i did and turn out to be wrong, now I am trying in small sections to see what i been doing wrong. the dtd it self is 24 question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-26T09:06:39.850", "Id": "458955", "Score": "0", "body": "There is not enough code here for a review, just like your earlier question. Please *fix* a question instead of deleting and re-posting it. We can help you, if you tell us what you're doing and if the code is working as intended. If the code is producing incorrect results, the code is not ready for a review. Please take a look at the [help/on-topic]." } ]
[ { "body": "<p>There's an unmatched <code>(</code> in the declaration of the contents of <code>story</code>. I recommend that you actually test the DTD using a validating parser such as OpenSP before posting code for review.</p>\n\n<p>6.1 is not satisfied: you have declared content for <code>story</code> but no attributes.</p>\n\n<p>6.2-6.4 are not satisfied: the <code>url</code>, <code>title</code> and <code>preview</code> elements must each appear <strong>exactly once</strong>.</p>\n\n<p>6.6.1 is not satisfied: you only allow <code>content</code> before <code>video</code> and not <code>video</code> before <code>content</code>.</p>\n\n<p>7.1 is not satisfied, because <code>title</code> has been declared as an empty element.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T15:23:43.833", "Id": "455576", "Score": "0", "body": "\"The element stories contains 0 or more story elements\" . To write this i have to say (stories*), is the * right to use in this situation. And \"The element title can contain text\" do i type title (text) ?? this are the questions i am wondering" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T16:31:47.973", "Id": "455581", "Score": "1", "body": "The requirement 7.1 says `title` can contain text, rather than `title` can contain a `text` element; my reading is that you're expected to declare as having Parsed Character Data content rather than element content. But that's something you ought to clarify with whoever gave you the requirements. I'm not convinced this is ready for review until you can answer some of your own questions..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T09:20:27.113", "Id": "233111", "ParentId": "233094", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-27T23:55:49.373", "Id": "233094", "Score": "0", "Tags": [ "xml" ], "Title": "XML DTD for downloadable stories" }
233094
<p>I'm looking for optimized code with faster execution time. This writes CSV to parquet with the max size of 64 MB chunks.</p> <p>we are trying to concatenate the csv file contents being written as an parquet file until the parquet file size reaches 64MB </p> <p>The loop would continue to run until reads all the csv files content being concatenated being written as parquet format </p> <pre><code>import pandas as pd import uuid import boto3 s3 = boto3.client('s3') out_path='s3://ahshan/parquet-out/' ssize=64*1024*1024 def get_s3_keys(bucket, prefix): """Get a list of keys in an S3 bucket.""" resp = s3.list_objects_v2(Bucket=bucket, Prefix=prefix) files=[] for obj in resp['Contents']: str_key = obj['Key'] files.append(str_key.split('\n')) # print(files) return files def lambda_handler(event,context): counter=0 count=0 cond=False extension = 'csv' all_filenames = get_s3_keys('ahshan','csvfiles/csvtemp/') # print (all_filenames) df = [] sizedf =0 cond=False flat_list = [item for sublist in all_filenames for item in sublist] flatl= [ item for item in flat_list if '.csv' in item] print(' shiva pre :', flatl) for f in flatl: ipd = pd.read_csv('s3://ahshan/'+f) sizedf += ipd.size print(sizedf, ":", ssize) if sizedf &gt; ssize: pd.concat(df).to_parquet(out_path+str(uuid.uuid1())+'.parq', compression='gzip') sizedf = 0 df = [] cond=True else: df.append(ipd) cond=False if not cond: print('hello') pd.concat(df).to_parquet(out_path+str(uuid.uuid1())+'.parq', compression='gzip') <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T07:12:52.353", "Id": "455502", "Score": "1", "body": "With this condition `if sizedf > ssize:` all csv files whose records **size** is greater than `64`Mb will be skipped from export. Is that intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T09:20:34.487", "Id": "455518", "Score": "0", "body": "@RomanPerekhrest - you are right , we are not expecting csv files greater than 1MB" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T09:32:26.963", "Id": "455522", "Score": "2", "body": "This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T09:41:59.287", "Id": "455527", "Score": "0", "body": "@user1510139, If not \"greater than **1**MB\", why compare to 64Mb? We are waiting for your edit" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T10:23:35.010", "Id": "455532", "Score": "0", "body": "we are trying to concatenate the *.csv files (size 1MB) contents being written as an parquet file until the parquet file size reaches 64MB" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T10:24:48.453", "Id": "455534", "Score": "1", "body": "Goal is to concatenate multiple csv files of small size and write it as parquet file not exceeding 64MB" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T10:33:57.837", "Id": "455538", "Score": "1", "body": "@user1510139, the current approach does different than a conception you are describing. It does not look workable in terms the conditions you mentioned and does not look ready to review" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T05:47:38.367", "Id": "233100", "Score": "1", "Tags": [ "python", "python-3.x", "csv", "parquet" ], "Title": "Optimized AWS Lamda purpose" }
233100
Timsort is a sorting algorithm invented by Tim Peters, designed to take advantage of partial ordering in data. It has an average-case complexity of Θ(nlogn) and worst-case complexity of O(nlogn).
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T06:31:37.967", "Id": "233102", "Score": "0", "Tags": null, "Title": null }
233102
<p>This is my attempt to build a simple simulation of a direct mapped cache, I'm new to C and trying to learn some low level concepts. I had some difficulties with the design, because I'm used to program in a object-oriented style. </p> <pre><code>#include &lt;stdio.h&gt; int create_mask(int num_of_bits, int pos) { return (1 &lt;&lt; num_of_bits)-1 &lt;&lt; pos; } int get_window_bits(int num, int window_size, int pos) { return (create_mask(window_size, pos) &amp; num) &gt;&gt; pos; } int is_valid(char cache[4][4], int set, int tag) { return cache[set][0] &amp;&amp; (cache[set][1] == tag); } void load_to_cache(int address, char memory[8][2], char cache[4][4], int set, int tag, int offset) { int memory_index = get_window_bits(address, 3, 1); cache[set][0] = 1; cache[set][1] = tag; cache[set][2] = memory[memory_index][0]; cache[set][3] = memory[memory_index][1]; } int fetch_from_cache(int address, char cache[4][4], char memory[8][2]) { int set = get_window_bits(address, 2, 1); int offset = get_window_bits(address, 1, 0); int tag = get_window_bits(address, 1, 3); if (!is_valid(cache, set, tag)) { printf("cache miss\n"); load_to_cache(address, memory, cache, set, tag, offset); } else { printf("cache hit\n"); } return cache[set][2+offset]; } int main() { /* init memory - 8 blocks of 2 bytes */ char memory[8][2] = {{'A','B'}, {'C','D'}, {'E','F'}, {'G','H'}, {'I','J'}, {'K','L'}, {'M','N'}, {'O','P'}}; /* init cache - 4 lines of 2 bytes storage*/ char cache[4][4] = {{0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}}; fetch_from_cache(0, cache, memory); fetch_from_cache(1, cache, memory); return 0; } </code></pre> <p>Structure: </p> <p>The program consists of a 2d array that represents the memory, it's size is 16 bytes:</p> <pre><code>char memory[8][2] = {{'A','B'}, {'C','D'}, {'E','F'}, {'G','H'}, {'I','J'}, {'K','L'}, {'M','N'}, {'O','P'}}; </code></pre> <p>another array which represents the cache of 4 lines, each line can store 2 bytes the first byte of the line is for the valid bit, the second is for the tag, and the rest are for the data.</p> <pre><code>char cache[4][4] = {{0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}}; </code></pre> <p>The function <code>get_window_bits</code> is used to extract the tag, set and offset of a memory address.</p> <pre><code>int get_window_bits(int num, int window_size, int pos) { return (create_mask(window_size, pos) &amp; num) &gt;&gt; pos; } </code></pre> <p>I hope everything else is clear.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T22:14:45.880", "Id": "455707", "Score": "1", "body": "There is nothing about memory that needs signed types. Are you required to use `int` vs. `unsigned` for example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T08:02:12.380", "Id": "455841", "Score": "0", "body": "@chux - Reinstate Monica good point, it should be unsigned." } ]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Use parentheses to clarify expressions</h2>\n\n<p>The code contains this line:</p>\n\n<pre><code>return (1 &lt;&lt; num_of_bits)-1 &lt;&lt; pos;\n</code></pre>\n\n<p>A programmer reading it might wonder which of the following is the correct interpretation:</p>\n\n<pre><code>return ((1 &lt;&lt; num_of_bits)-1) &lt;&lt; pos;\nreturn (1 &lt;&lt; num_of_bits)-(1 &lt;&lt; pos);\n</code></pre>\n\n<p>To interpret correctly (the first one), one would have to remember that according to <a href=\"https://en.cppreference.com/w/c/language/operator_precedence\" rel=\"nofollow noreferrer\">C operator precedence</a>, the <code>-</code> operator has higher precedence than the <code>&lt;&lt;</code> operator. We can easily avoid this potential confusion by simply writing the code with parentheses, even though, technically, they're redunandant.</p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>The <code>load_to_cache</code> function includes unused parameter <code>offset</code>. If it's not used, it probably should be removed.</p>\n\n<h2>Be wary of plain <code>char</code></h2>\n\n<p>Whether <code>char</code> is signed or unsigned is implementation defined. I'd suggest instead using <code>uint8_t</code> from <code>&lt;stdint.h&gt;</code> to make sure that there aren't any surprises when doing right shifts. A short example shows the difference:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint main() {\n signed char a = -1;\n unsigned char b = -1;\n printf(\"%x\\n\", a&gt;&gt;2); // prints ffffffff \n printf(\"%x\\n\", b&gt;&gt;2); // prints 3f\n}\n</code></pre>\n\n<p>For similar reasons, most of the places the code is using <code>int</code> should probably be either <code>unsigned</code> or <code>size_t</code>.</p>\n\n<h2>Use a <code>struct</code> where appropriate</h2>\n\n<p>The cache is just memory, of course, but with a simulation, the bytes have structure and meaning. The code has these three lines:</p>\n\n<pre><code>cache[set][0] = 1;\ncache[set][1] = tag;\ncache[set][2] = memory[memory_index][0];\ncache[set][3] = memory[memory_index][1];\n</code></pre>\n\n<p>This suggests the following <code>struct</code> definition:</p>\n\n<pre><code>#define CACHESIZE 2\ntypedef struct cacheline_s {\n uint8_t valid;\n uint8_t tag;\n uint8_t mem[CACHESIZE];\n} cacheline;\n</code></pre>\n\n<p>Now the lines above become this:</p>\n\n<pre><code>cache[set].valid = 1;\ncache[set].tag = tag;\ncache[set].mem[0] = memory[memory_index][0];\ncache[set].mem[1] = memory[memory_index][1];\n</code></pre>\n\n<h2>Reconsider the interfaces</h2>\n\n<p>Instead of this:</p>\n\n<pre><code>if (!is_valid(cache, set, tag)) {\n</code></pre>\n\n<p>I think it might make more sense to pass only a single cache line. Using the <code>struct</code> defined above, the function now looks like this:</p>\n\n<pre><code>int is_valid(const cacheline *cache, int tag) {\n return cache-&gt;valid &amp;&amp; (cache-&gt;tag == tag);\n}\n</code></pre>\n\n<p>Note too that we're passing a <code>const</code> pointer, advertising the fact that the underlying cacheline will not be changed by this function. A similar interface change could be made to <code>load_to_cache</code>.</p>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>This code has a number of inscrutable \"magic numbers,\" that is, unnamed constants such as 2, 4, 8, etc. Generally it's better to avoid that and give such constants meaningful names. That way, if anything ever needs to be changed, you won't have to go hunting through the code for all instances of \"2\" and then trying to determine if this <em>particular</em> 2 is relevant to the desired change or if it is some other constant that happens to have the same value. This is especially beneficial in cases like this in which some numbers depend on others. For example, we can use these to make sure that the two constants are easily changed and kept consistent. Only the first variable needs to be touched.</p>\n\n<pre><code>#define CACHESIZE_BITS 1\n#define CACHESIZE (1u &lt;&lt; CACHESIZE_BITS)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T14:25:41.800", "Id": "233788", "ParentId": "233105", "Score": "1" } } ]
{ "AcceptedAnswerId": "233788", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T07:41:33.207", "Id": "233105", "Score": "8", "Tags": [ "c", "cache" ], "Title": "Direct Mapped Cache simulation" }
233105
<p>Apologies for the cryptic title, I don't quite know how to title this question. I'm asking here rather than StackOverflow since I've got a working query, I'm just wondering if it can be improved.</p> <p>Anyway, I've got three tables, <code>administration</code>, <code>mapping</code> and <code>used_mappings</code>. <code>Administration</code> holds details of individual financial administrations, <code>mapping</code> is a "static" table holding details for all available financial mappings, <code>used_mappings</code> holds records of what mappings are used by what administration (not every administration uses every mapping). The <code>used_mappings</code> table also has a column, <code>custom_name</code>, so the columns look as follows;</p> <p>Administration</p> <pre><code>| id | name | |----|---------| | 1 | Admin 1 | | 2 | Admin 2 | </code></pre> <p>Mapping</p> <pre><code>| id | name | |----|-----------| | 1 | Mapping 1 | | 2 | Mapping 2 | | 3 | Mapping 3 | | 4 | Mapping 4 | | 5 | Mapping 5 | </code></pre> <p>Used mapping</p> <pre><code>| id | administration_id | mapping_id | custom_name | |----|-------------------|------------|-------------------| | 1 | 1 | 1 | Revenue | | 2 | 1 | 3 | Cost of sales | | 3 | 2 | 1 | Bar revenue | | 4 | 2 | 3 | Cost of bar sales | | 5 | 2 | 4 | Wages | </code></pre> <p>I now need to fetch all records from <code>mapping</code>, regardless of them being used, and where a <code>custom_name</code> is defined in <code>used_mappings</code> for a specific administration, add it on as an extra column (and have <code>custom_name</code> in the results be <code>null</code> if no <code>custom_name</code> exists.)</p> <p>I first tried a simple <code>LEFT JOIN</code>;</p> <pre><code>SELECT M.id, M.name, U.custom_name as customName FROM mapping M LEFT JOIN used_mapping U ON U. = M.id WHERE U.administration_id = 2; </code></pre> <p>And although it does fetch the correct <code>custom_name</code>s, because of the <code>WHERE U.administration_id = 1;</code> it only fetches rows from <code>used_mapping</code> where that condition is met. In other words, in this example it fetches</p> <pre><code>| id | name | customName | |----|--------------|-------------------| | 1 | Mapping 1 | Bar revenue | | 3 | Mapping 3 | Cost of bar sales | | 4 | Mapping 4 | Wages | </code></pre> <p>rather than</p> <pre><code>| id | name | customName | |----|-----------|-------------------| | 1 | Mapping 1 | Bar revenue | | 2 | Mapping 2 | null | | 3 | Mapping 3 | Cost of bar sales | | 4 | Mapping 4 | Wages | | 5 | Mapping 5 | null | </code></pre> <p>I've got it working with a slightly more complex <code>LEFT JOIN</code>;</p> <pre><code>SELECT id, name, custom_name FROM mapping AS M LEFT JOIN ( SELECT custom_name, mapping_id FROM used_mappings WHERE administration_id = 2 ) AS U ON U.mapping_id = M.id; </code></pre> <p>but it takes twice as long compared to fetching all rows from <code>mapping</code> (obviously because for every record in <code>mapping</code>, it runs a query on <code>used_mappings</code> as well). Hence my question, is there a way of making the query more efficient?</p>
[]
[ { "body": "<pre><code>SELECT M.id,\n M.name,\n U.custom_name as customName\nFROM mapping M\nLEFT JOIN used_mapping U ON U. = M.id\nWHERE U.administration_id = 2;\n</code></pre>\n\n<p>The problem is in the <code>where</code> statement. Here it checks whether the <code>administration_id = 2</code>. For mappings where there is no match in <code>used_mapping</code> this id will be <code>null</code>. So it gets filtered out. Essentially you're performing an <code>inner join</code> here.</p>\n\n<p>Instead you can also allow rows that have <code>administration_id is null</code>:</p>\n\n<pre><code>SELECT M.id,\n M.name,\n U.custom_name as customName\nFROM mapping M\nLEFT JOIN used_mapping U ON U. = M.id\nWHERE U.administration_id = 2 or U.administration_id IS NULL;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:47:46.257", "Id": "455510", "Score": "0", "body": "The problem is that `U.administration_id` can't be null. `Used_mapping` holds the `mapping`s used by each administration, so if a mapping isn't used by a certain administration, it simply doesn't appear in `used_mapping`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:51:53.173", "Id": "455511", "Score": "0", "body": "@Alex it can't be null in the table, it can be after the left join: rows in `mapping` that don't exist in `used_mapping` (2 and 5), won't have a matching record in the result set after the join, so there the columns coming from the `used_mapping` table will be null. Try executing `select * from mapping M left join used_mapping U on U.mapping_id = M.id`: you'll see what I mean." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T09:48:34.247", "Id": "455528", "Score": "0", "body": "Hmm, oddly your query works in a sample database I quickly set up, with limited records, but doesn't work in the actual database despite the structure being the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T10:23:59.193", "Id": "455533", "Score": "0", "body": "@Alex at risk of turning this into a SO-debug session, can you describe how it doesn't work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T10:51:30.720", "Id": "455541", "Score": "0", "body": "I just realised the error, some mappings are simply not used by any administration ever, so they won't appear when running the query. Your query works in case all records from one column are used in the other, but that's not the case for me sadly. Basically, there's nothing wrong with your query, it's just not usable in my situation" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:42:44.783", "Id": "233107", "ParentId": "233106", "Score": "1" } } ]
{ "AcceptedAnswerId": "233107", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:22:49.590", "Id": "233106", "Score": "2", "Tags": [ "sql" ], "Title": "Querying all records from one table, add column from another with foreign key constraint" }
233106
<p>A dataset consisting of N items. Each item is a pair of a word and a boolean denoting whether the given word is a spam word or not.</p> <p>There shouldn't be a word included in the training set that's marked both as spam and not-spam. For example item <code>{"fck", 1}</code>, and item <code>{"fck, 0"}</code> can't be present in the training set, because first item says the word <code>"fck"</code> is a spam, whereas the second item says it is not, which is a contradiction.</p> <p>Your task is to select the maximum number of items in the training set.</p> <p>Note that same pair of <code>{word, bool}</code> can appear multiple times in input. The training set can also contain the same pair multiple times.</p> <p>Question link is <a href="https://www.codechef.com/problems/TRAINSET" rel="nofollow noreferrer">here</a>.</p> <p><em>What I have done so far:</em></p> <ul> <li>Grouped given pair by word and taken count of spam and not-spam of each group.</li> <li>Finally, taken <code>max</code> count of each group and taken <code>sum</code> of this values.</li> </ul> <p><strong>Code:</strong></p> <pre><code>from itertools import groupby from collections import Counter t = int(input()) for _ in range(t): n = int(input()) data_set = sorted([tuple(map(str, input().split())) for __ in range(n)]) print(sum(max(Counter(element[1]).values()) for element in groupby(data_set, key=lambda x:x[0]))) </code></pre> <p>My code is working fine. Is my solution is efficient? If not please explain an efficient algorithm.</p> <p>What is the time complexity of my algorithm? </p> <p>Is it <code>O(N)</code>?</p> <p><strong>Example Input:</strong></p> <pre><code>3 3 abc 0 abc 1 efg 1 7 fck 1 fck 0 fck 1 body 0 body 0 body 0 ram 0 5 vv 1 vv 0 vv 0 vv 1 vv 1 </code></pre> <p><strong>Example Output:</strong></p> <pre><code>2 6 3 </code></pre> <p><strong>Constraints:</strong></p> <ul> <li>1≤T≤10</li> <li>1≤N≤25,000</li> <li>1≤|wi|≤5 for each valid i</li> <li>0≤si≤1 for each valid i</li> <li>w1,w2,…,wN contain only lowercase English letters</li> </ul> <p><strong>Edit-1:</strong></p> <p>To take input from file for testing,</p> <pre><code>with open('file.txt', 'r') as f: for _ in range(int(f.readline())): n = int(f.readline()) data_set = [tuple(map(str, f.readline().replace('\n','').split())) for __ in range(n)] print(data_set) # your logic here # Output: # [('abc', '0'), ('abc', '1'), ('efg', '1')] # [('fck', '1'), ('fck', '0'), ('fck', '1'), ('body', '0'), ('body', '0'), ('body', '0'), ('ram', '0')] # [('vv', '1'), ('vv', '0'), ('vv', '0'), ('vv', '1'), ('vv', '1')] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:59:33.297", "Id": "455513", "Score": "0", "body": "did you get the dataset where the answer is wrong and the exected outcome?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T09:00:41.753", "Id": "455514", "Score": "0", "body": "@MaartenFabré No, they didn't provide that dataset. Is there any other way to debug?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T12:38:45.477", "Id": "455563", "Score": "1", "body": "@shaikmoeed, Ok, thanks for the edit, I'll look at it" } ]
[ { "body": "<p>On first sight, I see 2 issues:</p>\n\n<h1><code>groupby</code>.</h1>\n\n<p>From the documentation:</p>\n\n<blockquote>\n <p>The operation of groupby() is similar to the <code>uniq</code> filter in Unix. It generates a break or new group every time the value of the key function changes <strong>(which is why it is usually necessary to have sorted the data using the same key function)</strong>.</p>\n</blockquote>\n\n<p>(emphasis mine)</p>\n\n<p>Compare your result for</p>\n\n<pre><code>fck 1\nbody 0\nbody 0\nfck 0\nbody 0\nram 0\nfck 1\n</code></pre>\n\n<p>to the result for </p>\n\n<pre><code>fck 1\nfck 0\nbody 0\nbody 0\nbody 0\nram 0\nfck 1\n</code></pre>\n\n<h1>debugging</h1>\n\n<p>The data structure that is important for the correctness of your answer is:</p>\n\n<pre><code>[Counter(element[1]) for element in groupby(data_set, key=lambda x:x[0])]\n</code></pre>\n\n<p>Here you assemble the values, which you later count.</p>\n\n<p>In the first case:</p>\n\n<pre><code>[Counter({('fck', '1'): 1, ('fck', '0'): 1}),\n Counter({('body', '0'): 3}),\n Counter({('ram', '0'): 1}),\n Counter({('fck', '1'): 1})]\n</code></pre>\n\n<p>In the second case:</p>\n\n<pre><code>[Counter({('fck', '1'): 1}),\n Counter({('body', '0'): 2}),\n Counter({('fck', '0'): 1}),\n Counter({('body', '0'): 1}),\n Counter({('ram', '0'): 1}),\n Counter({('fck', '1'): 1})]\n</code></pre>\n\n<p>The entries for <code>fck</code> are not grouped anymore.</p>\n\n<p>The easiest way to solve this, is by changing <code>data_set</code> to <code>data_set = sorted(tuple(map(str, input().split())) for __ in range(n))</code>,</p>\n\n<p>Or you can use an intermediate 2-level dict, but that is more complicated. I don't know which one will be the fastest.</p>\n\n<p>-- </p>\n\n<h1>alternative without <code>sorted</code></h1>\n\n<p>You can use <code>defaultdict</code> and <code>Counter</code> to set up an alternative datastructure</p>\n\n<pre><code>from collections import defaultdict, Counter\n\ninput_str = \"\"\"\nfck 1\nbody 0\nbody 0\nfck 0\nbody 0\nram 0\nfck 1\n\"\"\"\nresults = defaultdict(Counter)\n\ndata_set = (row.split() for row in input_str.split(\"\\n\") if row)\nfor word, result_bool in data_set:\n results[word][result_bool] += 1\n</code></pre>\n\n<blockquote>\n<pre><code>defaultdict(collections.Counter,\n {'fck': Counter({'1': 2, '0': 1}),\n 'body': Counter({'0': 3}),\n 'ram': Counter({'0': 1})})\n</code></pre>\n</blockquote>\n\n<pre><code>sum(max(result_bools.values()) for word, result_bools in results.items())\n</code></pre>\n\n<p>This does not need the sorting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T12:06:29.543", "Id": "455555", "Score": "0", "body": "@shaikmoeed Considering there are 2 for loops in your code, probably not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T12:14:25.663", "Id": "455560", "Score": "0", "body": "@Mast Thanks for letting me know. Can we solve this problem in `O(N)`? or What is the optimal time complexity we can achieve for this problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T17:23:05.593", "Id": "455591", "Score": "0", "body": "The outer loop loops over the test cases, so I wouldn't include that in the time complexity analysis. The sorted is `O(n log(n))` (depending on the sortedness of the input), the alternative solution loops once over all the lines, once over all the words, so looks `O(n)` to me" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T09:14:56.907", "Id": "233109", "ParentId": "233108", "Score": "2" } }, { "body": "<p>In search of most performant and optimized solution for your task let's consider <strong>3</strong> cases.</p>\n\n<p>We'll test them on input file containing <em>\"example intput\"</em> from the question.</p>\n\n<hr>\n\n<p>Case #<strong>1</strong> - is your initial approach with suggested <code>sorted</code> call wrapped in <code>max_trainset_sorted_counter</code> function:</p>\n\n<pre><code>def max_trainset_sorted_counter():\n with open('lines.txt', 'r') as f:\n for line in f:\n n = int(line.strip())\n data_set = sorted(tuple(map(str, f.readline().split())) for __ in range(n))\n print(sum(max(Counter(element[1]).values()) for element in groupby(data_set, key=lambda x: x[0])))\n</code></pre>\n\n<p>When profiled (<code>cProfile</code>) it produces: <strong><em>179</strong> function calls (165 primitive calls)</em>.</p>\n\n<hr>\n\n<p>Case #<strong>2</strong> - is an approach from <a href=\"https://codereview.stackexchange.com/a/233109/95789\">previous answer</a> based on <code>defaultdict</code> and <code>Counter</code> wrapped in <code>max_trainset_ddict_counter</code> function:</p>\n\n<pre><code>def max_trainset_ddict_counter():\n with open('lines.txt', 'r') as f:\n for line in f:\n n = int(line.strip())\n results = defaultdict(Counter)\n data_set = (f.readline().replace('\\n', '').split() for _ in range(n))\n for word, result_bool in data_set:\n results[word][result_bool] += 1\n print(sum(max(result_bools.values()) for word, result_bools in results.items()))\n</code></pre>\n\n<p>When profiled it produces: <strong><em>140</strong> function calls</em>.</p>\n\n<hr>\n\n<p>Case #<strong>3</strong> - is actually my solution based on <code>itertools.groupby</code>, <code>itertools.islice</code> features and simple arithmetic trick of 2 steps to sum up <em>maximals</em> (items with greater number of occurrences of <code>1</code> or <code>0</code> flags) of each group within a <em>trainset</em>:</p>\n\n<ul>\n<li>sum up all values of the group - <code>sum_ones = sum(int(i[1]) for i in group)</code>, which actually gives a number of <strong><code>1</code></strong> values/flags</li>\n<li>then <em>maximal</em> is found with simple <code>max(sum_ones, g_size - sum_ones)</code>, where <code>g_size</code> is assigned with <code>len(group)</code> (number of entries within a group). This will cover any combinations of <code>0</code> and <code>1</code> in <em>solitary</em> or mixed sequences.</li>\n</ul>\n\n<p>It's wrapped in <code>max_trainset_ext_sums</code> function:</p>\n\n<pre><code>def max_trainset_ext_sums():\n with open('lines.txt', 'r') as f:\n for line in f:\n n = int(line.strip())\n sum_groups = 0\n for k, g in groupby(sorted(tuple(row.split()) for row in islice(f, n)), key=lambda x: x[0]):\n group = tuple(g)\n g_size = len(group)\n if g_size == 1:\n sum_groups += g_size\n else:\n sum_ones = sum(int(i[1]) for i in group)\n sum_groups += max(sum_ones, g_size - sum_ones)\n print(sum_groups)\n</code></pre>\n\n<p>When profiled it produces: <strong><em>99</strong> function calls</em>.</p>\n\n<hr>\n\n<p>All 3 cases produce the same expected output:</p>\n\n<pre><code>2\n6\n3\n</code></pre>\n\n<p><strong>But</strong> let's get to <em>time performance</em> test (note, on very small input sample the time difference may not be significant):</p>\n\n<pre><code>&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; timeit('max_trainset_sorted_counter()', setup='from __main__ import max_trainset_sorted_counter', number=1000)\n0.1788159019779414\n&gt;&gt;&gt; timeit('max_trainset_ddict_counter()', setup='from __main__ import max_trainset_ddict_counter', number=1000)\n0.17249802296282724\n&gt;&gt;&gt; timeit('max_trainset_ext_sums()', setup='from __main__ import max_trainset_ext_sums', number=1000)\n0.14651802799198776\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T19:30:09.453", "Id": "233173", "ParentId": "233108", "Score": "2" } } ]
{ "AcceptedAnswerId": "233173", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T08:57:03.360", "Id": "233108", "Score": "-1", "Tags": [ "python", "performance", "algorithm", "memory-optimization" ], "Title": "TrainSet Practice Problem from CodeChef" }
233108
<p>I wrote code to upload multiple(2) files.</p> <p>1.Check if this is image: mime/extension/getimagesize. 2.Remove execute file permissions from the file(chmod).</p> <p>Is this script secure? What can go wrong?</p> <p><strong><em>Class photograph</em></strong></p> <pre><code>class Photograph extends DatabaseObject { protected static $table_name = "photographs"; protected static $db_columns = ['id', 'filename', 'filename2', 'type', 'type2', 'size', 'size2', 'caption']; public $id; public $filename; public $filename2; public $type; public $type2; public $size; public $size2; public $caption; private $temp_path; //protected $upload_dir="../images"; protected $upload_dir = PUBLIC_PATH . '/images'; protected $max_file_size = 1048576; // 1 MB expressed in bytes public $errors = array(); // Define allowed filetypes to check against during validations protected $allowed_mime_types = ['image/png', 'image/gif', 'image/jpg', 'image/jpeg']; protected $allowed_extensions = ['png', 'gif', 'jpg', 'jpeg']; protected $upload_errors = array( 0 =&gt; 'There is no error, the file uploaded with success.', 1 =&gt; 'Larger than upload_max_filesize.', 2 =&gt; 'Larger than form MAX_FILE_SIZE.', 3 =&gt; 'Partially uploaded.', 4 =&gt; 'No file.', 6 =&gt; 'No temporary folder.', 7 =&gt; 'Failed to write file to disk.', 8 =&gt; 'A PHP extension stopped the file upload.', ); protected function sanitize_file_name($string) { // Remove characters that could alter file path. // I disallowed spaces because they cause other headaches. // "." is allowed (e.g. "photo.jpg") but ".." is not. $string = preg_replace("/([^A-Za-z0-9_\-\.]|[\.]{2})/", "", $string); // basename() ensures a file name and not a path $string = basename($string); return $string; } protected $check_is_image = true; private function size_as_kb() { if ($this-&gt;size &lt; 1024) { return "{$this-&gt;size} bytes"; } elseif ($this-&gt;size &lt; 1048576) { $size_kb = round($this-&gt;size/1024); return "{$size_kb} KB"; } else { $size_mb = round($this-&gt;size/1048576, 1); return "{$size_mb} MB"; } } private function size_as_kb_2() { if ($this-&gt;size2 &lt; 1024) { return "{$this-&gt;size2} bytes"; } elseif ($this-&gt;size2 &lt; 1048576) { $size_kb = round($this-&gt;size2/1024); return "{$size_kb} KB"; } else { $size_mb = round($this-&gt;size2/1048576, 1); return "{$size_mb} MB"; } } // Returns the file permissions in octal format. private function file_permissions($file) { // fileperms returns a numeric value $numeric_perms = fileperms($file); // but we are used to seeing the octal value $octal_perms = sprintf('%o', $numeric_perms); return substr($octal_perms, -4); } /* ================================================================================== public function attach_file($file) ================================================================================== */ public function attach_file($file) { $this-&gt;temp_path = $file['tmp_name']['0']; $this-&gt;filename = $this-&gt;sanitize_file_name($file['name']['0']); $this-&gt;type = $file['type']['0']; $this-&gt;size = $file['size']['0']; $this-&gt;temp_path2 = $file['tmp_name']['1']; $this-&gt;filename2 = $this-&gt;sanitize_file_name($file['name']['1']); $this-&gt;type2 = $file['type']['1']; $this-&gt;size2 = $file['size']['1']; } /* ================================================================================== public function upload file 1 ================================================================================== */ public function upload_file() { $filename_extension = pathinfo($this-&gt;filename, PATHINFO_EXTENSION); if($this-&gt;size &gt; $this-&gt;max_file_size) { // PHP already first checks php.ini upload_max_filesize, and // then form MAX_FILE_SIZE if sent. // But MAX_FILE_SIZE can be spoofed; check it again yourself. echo "Error: Your product image 1 is too big. The file has: {$this-&gt;size_as_kb()}.&lt;br /&gt;"; return false; } if(!is_uploaded_file($this-&gt;temp_path)) { echo "Fatal error: Possible alien attack!&lt;br /&gt;"; return false; } // check if this is image: mime/extension/getimagesize - return false. if(!in_array($this-&gt;type, $this-&gt;allowed_mime_types)) { echo "Error: Not an allowed mime type.&lt;br /&gt;"; } if(!in_array($filename_extension, $this-&gt;allowed_extensions)){ echo "Error: Your product image 1 file extension is not supported.&lt;br /&gt;"; } if($this-&gt;check_is_image &amp;&amp; (getimagesize($this-&gt;temp_path) === false)) { // getimagesize() returns image size details, but more importantly, // returns false if the file is not actually an image file. // You obviously would only run this check if expecting an image. echo "Error: Not a valid image file.&lt;br /&gt;"; return false; } // ends - check image // Can't save without filename and temp location if(empty($this-&gt;filename) || empty($this-&gt;temp_path) ) { $this-&gt;errors[] = "The file location was not available."; return false; } $target_path = $this-&gt;upload_dir . '/' . $this-&gt;filename; // Make sure a file doesn't already exist in the target location if(file_exists($target_path)) { $this-&gt;errors[] = "The file {$this-&gt;filename} already exists."; return false; } // Attempt to move the file if(move_uploaded_file($this-&gt;temp_path, $target_path)) { echo "First file name is '{$this-&gt;filename}'.&lt;br /&gt;"; echo "First file moved to: {$target_path}&lt;br /&gt;" ; echo "Uploaded file size was {$this-&gt;size_as_kb()}.&lt;br /&gt;"; echo "&lt;br /&gt;"; // Success // remove execute file permissions from the file if(chmod($target_path, 0644)) { echo "Execute permissions removed from file: {$this-&gt;filename}.&lt;br /&gt;"; $file_permissions = $this-&gt;file_permissions( $target_path ); echo "File permissions are now '{$file_permissions}'.&lt;br /&gt;"; } else { echo "Error: Execute permissions could not be removed.&lt;br /&gt;"; } echo "&lt;br /&gt;"; } else { // File was not moved. $this-&gt;errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder."; return false; } } /* ================================================================================== public function upload file 2 ================================================================================== */ public function upload_file2() { // Can save first without second filename and temp location if(!empty($this-&gt;filename2) || !empty($this-&gt;temp_path2)) { $filename_extension2 = pathinfo($this-&gt;filename2, PATHINFO_EXTENSION); if($this-&gt;size2 &gt; $this-&gt;max_file_size) { // PHP already first checks php.ini upload_max_filesize, and // then form MAX_FILE_SIZE if sent. // But MAX_FILE_SIZE can be spoofed; check it again yourself. echo "Error: Your product image 2 is too big. The file has: {$this-&gt;size_as_kb_2()}.&lt;br /&gt;"; return false; } if(!is_uploaded_file($this-&gt;temp_path2)) { echo "Fatal error: Possible alien attack!&lt;br /&gt;"; return false; } // check if this is image: mime/extension/getimagesize - return false. if(!in_array($this-&gt;type2, $this-&gt;allowed_mime_types)) { echo "Error: Not an allowed mime type.&lt;br /&gt;"; } if(!in_array($filename_extension2, $this-&gt;allowed_extensions)){ echo "Error: Your product image 2 file extension is not supported.&lt;br /&gt;"; } if($this-&gt;check_is_image &amp;&amp; (getimagesize($this-&gt;temp_path2) === false)) { // getimagesize() returns image size details, but more importantly, // returns false if the file is not actually an image file. // You obviously would only run this check if expecting an image. echo "Error: Not a valid image file.&lt;br /&gt;"; return false; } // ends - check image $target_path2 = $this-&gt;upload_dir . '/' . $this-&gt;filename2; // Make sure a file doesn't already exist in the target location if(file_exists($target_path2)) { $this-&gt;errors[] = "The file {$this-&gt;filename2} already exists."; return false; } // Attempt to move the file if(move_uploaded_file($this-&gt;temp_path2, $target_path2)) { echo "Second file name is '{$this-&gt;filename2}'.&lt;br /&gt;"; echo "Second file moved to: '{$target_path2}'&lt;br /&gt;" ; echo "Uploaded file size was {$this-&gt;size_as_kb_2()}.&lt;br /&gt;"; echo "&lt;br /&gt;"; // Success // remove execute file permissions from the file if(chmod($target_path, 0644)) { echo "Execute permissions removed from file: {$this-&gt;filename2}.&lt;br /&gt;"; $file_permissions2 = $this-&gt;file_permissions( $target_path2 ); echo "File permissions are now '{$file_permissions2}'.&lt;br /&gt;"; } else { echo "Error: Execute permissions could not be removed.&lt;br /&gt;"; } echo "&lt;br /&gt;"; } else { // File was not moved. $this-&gt;errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder."; return false; } } } /* ================================================================================== public function save() ================================================================================== */ public function save() { // A new record won't have an id yet. if(isset($this-&gt;id)) { $this-&gt;upload_file(); $this-&gt;upload_file2(); if($this-&gt;update_photo()) { // We are done with temp_path, the file isn't there anymore unset($this-&gt;temp_path, $this-&gt;temp_path2); return true; } } else { // Can't save if there are pre-existing errors if(!empty($this-&gt;errors)) { return false; } $this-&gt;upload_file(); $this-&gt;upload_file2(); // Save a corresponding entry to the database //if($this-&gt;create3()) { - dziala if($this-&gt;create()) { // We are done with temp_path, the file isn't there anymore unset($this-&gt;temp_path, $this-&gt;temp_path2); return true; } } } </code></pre> <p><strong><em>photo_upload.php</em></strong></p> <pre><code>if(isset($_POST['submit'])) { $photo = new Photograph(); $photo-&gt;caption = $_POST['caption']; $photo-&gt;attach_file($_FILES['file_upload']); $photo-&gt;attach_file($_FILES['file_upload']); if($photo-&gt;save() ) { // Success } else { // Failure } } &lt;form action="photo_upload.php" enctype="multipart/form-data" method="POST"&gt; &lt;p&gt;&lt;input name="file_upload[]" type="file" id="file_upload[]" value=""&gt;&lt;/p&gt; &lt;p&gt;&lt;input name="file_upload[]" type="file" id="file_upload[]" value=""&gt;&lt;/p&gt; &lt;p&gt;Caption: &lt;input type="text" name="caption" value="" /&gt;&lt;/p&gt; &lt;input type="submit" name="submit" value="Upload" /&gt; &lt;/form&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T12:07:48.060", "Id": "455556", "Score": "1", "body": "You want to know whether your script is secure. Secure against what? What is your [threat model](https://en.wikipedia.org/wiki/Threat_model)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T12:36:22.973", "Id": "455561", "Score": "0", "body": "I want to know if this is a good practice. Chmod, filename_extension and so on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T12:41:58.510", "Id": "455565", "Score": "0", "body": "That has nothing to do with whether it's secure or not. What are your expectations for this code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T12:52:47.073", "Id": "455569", "Score": "0", "body": "e.g that the hacked photo, script, file with 777 mode will not get to the server." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T15:17:48.247", "Id": "455574", "Score": "1", "body": "You want to protect against hacked photos?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T15:19:05.313", "Id": "455575", "Score": "0", "body": "A lot of your code seems to be missing since I see a lot of empty if-else statements. Can you clarify your concerns and what's up with the empty blocks? Please take a look at the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T22:29:19.703", "Id": "455612", "Score": "0", "body": "@Manty I don't have enough of a critique to merit a review, but `/([^A-Za-z0-9_\\-\\.]|[\\.]{2})/` is more simply written as `/[^\\w.-]|\\.{2}/` and `unset()` can receive one or more parameters in a single call." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T07:22:47.187", "Id": "455628", "Score": "0", "body": "`unset($this->test1, $this->test2, $this->test3); ` - Yes - you're right" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T07:23:59.220", "Id": "455629", "Score": "0", "body": "` /[^\\w.-]|\\.{2}/ `- I have to test and check documentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T07:32:17.497", "Id": "455630", "Score": "0", "body": "Empty blocks? Everything works - I mean `if error return false`, I checked this 10 times - sanitize file, chmod, max file, is image and so on..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T07:39:41.900", "Id": "455631", "Score": "0", "body": "\" Hacked photos\" - `getimagesize()` returns image size details, but more importantly, returns false if the file is not actually. You obviously would only run this check if expecting an image." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T07:41:11.067", "Id": "455632", "Score": "0", "body": "A file could be of several types at once. If a file is of the image type it doesn't mean it couldn't be of php type at the same time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T07:58:20.417", "Id": "455633", "Score": "0", "body": "\"several types at once\"? Example please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T19:55:56.030", "Id": "457581", "Score": "0", "body": "Why do you repeat a lot of code, with the same functionality, to upload the second photo? This is not [DRY](https://www.thinktocode.com/2017/11/20/dont-repeat-dry). What will you do if you have to add a third photo? It is also obvious that the `save()` method is far too long." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-17T22:34:48.027", "Id": "458101", "Score": "0", "body": "Good advice, thank you, I don't know how to code this, but I will think about it tomorrow." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T11:59:18.970", "Id": "233115", "Score": "1", "Tags": [ "php", "mysql" ], "Title": "Uploading files securely with php - OOP" }
233115
<p>I am new to python and coding in general and I recently found HackerRank. I have been mostly doing easy problems until now. Today, I saw the problem "Queen's Attack II" (<a href="https://www.hackerrank.com/challenges/queens-attack-2/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/queens-attack-2/problem</a>), wrote my code, and it didn't execute in time for some of the testcases. I optimized it best to what I could and then I went in the discussions, where I found a code from u/Arviy which follows basically the same algorithm as mine but the implementation was a bit different. But it ran just fine comparing all the test cases.</p> <p>I also compared them to best of my knowledge, and tried to time different portions of code using <code>time.time()</code> from <code>import time</code>. In the end, I got my code to pass the test cases but it still runs about 2x slower than the other code.</p> <p><strong>Problem Summary -</strong><br> A queen is standing on an <em>n times n</em> chessboard. The chess board's rows are numbered from <em>1 to n</em>, going from bottom to top. Its columns are numbered from <em>1 to n</em>, going from left to right. Each square is referenced by a tuple, <em>(r,c)</em>, describing the row <em>r</em>, and column <em>c</em>, , where the square is located.<br> The queen is standing at position <em>(r_q, c_q)</em>. In a single move, she can attack any square in any of the eight directions (left, right, up, down, and the four diagonals). There are obstacles on the chessboard, each preventing the queen from attacking any square beyond it on that path. Given the queen's position and the locations of all the obstacles, find and print the number of squares the queen can attack from her position.</p> <p>Variables setup - </p> <pre><code>n, k = 100000, 100000 r_q, c_q = 1, 1 obstacles = [[1000, 1000], [714, 169], [619, 264], [609, 274], [809, 74], [819, 64], [714, 264], [714, 74], [952, 569], [623, 471], [256, 985], [934, 419], [745, 280], [926, 189], [159, 859], [106, 912], [509, 894], [170, 402], [476, 238], [173, 546], [674, 438], [539, 597], [215, 724], [675, 975], [128, 814], [789, 162], [492, 142], [694, 384], [206, 253], [347, 625], [491, 147], [243, 639], [408, 401], [850, 293], [310, 901], [925, 147], [138, 471], [610, 203], [571, 658], [724, 762], [456, 908], [710, 842], [203, 321], [972, 254], [527, 214], [945, 750], [103, 561], [374, 947], [439, 716], [958, 504], [830, 182], [902, 635], [901, 158], [804, 532], [903, 957], [126, 916], [418, 485], [493, 385], [410, 247], [217, 712], [936, 340], [805, 645], [940, 430], [194, 148], [719, 247], [872, 928], [251, 231], [136, 240], [609, 860], [401, 230], [168, 759], [531, 907], [546, 927], [729, 590], [648, 912], [407, 793], [917, 256], [671, 489], [926, 874], [438, 467], [602, 462], [239, 328], [104, 510], [260, 739], [864, 741], [837, 493], [418, 345], [798, 754], [841, 710], [169, 365], [954, 389], [160, 496], [183, 108], [741, 796], [753, 682], [159, 324], [417, 306], [261, 509], [587, 194], [805, 907], [218, 204], [591, 389], [916, 894], [963, 103], [461, 689], [937, 520], [350, 730], [436, 208], [381, 617], [546, 361], [719, 512], [305, 794], [509, 820], [915, 570], [408, 420], [609, 973], [872, 710], [465, 409], [459, 427], [918, 847], [142, 943], [457, 364], [360, 273], [276, 289], [427, 537], [317, 475], [864, 832], [845, 639], [463, 520], [741, 617], [762, 734], [160, 804], [192, 739], [289, 715], [340, 826], [827, 872], [186, 836], [967, 639], [145, 137], [581, 147], [479, 897], [203, 960], [967, 691], [891, 680], [593, 651], [172, 257], [258, 325], [351, 859], [153, 801], [705, 589], [832, 832], [718, 864], [971, 652], [567, 561], [715, 729], [689, 821], [178, 891], [962, 408], [829, 639], [561, 413], [401, 261], [491, 952], [831, 741], [271, 471], [826, 312], [482, 317], [413, 769], [231, 561], [579, 735], [769, 916], [184, 586], [820, 208], [476, 298], [587, 157], [194, 642], [341, 647], [478, 731], [951, 620], [401, 912], [837, 358], [249, 349], [158, 201], [195, 968], [294, 132], [291, 193], [158, 480], [849, 761], [832, 157], [364, 809], [293, 526], [164, 865], [193, 429], [158, 520], [342, 574], [409, 815], [627, 765], [413, 316], [426, 508], [902, 620], [278, 385], [587, 342], [982, 812], [753, 721], [176, 192], [289, 729], [845, 729], [698, 205], [597, 378], [570, 251], [853, 742], [903, 126], [546, 172], [792, 491], [160, 926], [321, 597], [835, 356], [894, 207], [153, 807], [106, 372], [716, 105], [638, 281], [814, 597], [970, 926], [175, 943], [135, 642], [372, 142], [701, 980], [720, 184], [695, 491], [682, 354], [371, 246], [421, 574], [803, 108], [429, 687], [465, 953], [157, 385], [624, 893], [201, 896], [975, 295], [635, 348], [351, 659], [127, 109], [705, 852], [471, 327], [915, 750], [720, 637], [126, 358], [506, 690], [317, 923], [285, 725], [957, 406], [372, 810], [971, 170], [920, 452], [756, 743], [791, 158], [698, 835], [576, 470], [209, 329], [902, 948], [854, 249], [347, 780], [386, 215], [713, 130], [516, 760], [964, 374], [781, 340], [763, 402], [408, 824], [476, 642], [752, 320], [605, 185], [231, 745], [941, 962], [354, 760], [927, 426], [340, 164], [809, 720], [465, 152], [487, 280], [386, 690], [401, 605], [351, 517], [421, 120], [571, 870], [409, 581], [647, 268], [254, 168], [290, 687], [982, 452], [184, 813], [942, 726], [829, 856], [305, 874], [759, 456], [623, 930], [813, 984], [297, 432], [609, 397], [257, 921], [320, 375], [109, 570], [126, 210], [763, 189], [798, 708], [803, 368], [971, 631], [967, 791], [962, 850], [906, 201], [849, 403], [905, 389], [284, 231], [726, 275], [742, 562], [754, 948], [724, 481], [903, 168], [523, 231], [735, 452], [930, 149], [503, 950], [572, 473], [561, 967], [296, 281], [352, 283], [638, 856], [760, 602], [801, 170], [598, 417], [841, 965], [479, 485], [859, 916], [293, 248], [457, 791], [238, 462], [725, 943], [821, 372], [543, 901], [473, 507], [982, 723], [726, 394], [418, 350], [834, 150], [218, 437], [584, 290], [934, 271], [294, 895], [543, 671], [623, 784], [485, 478], [276, 643], [513, 136], [957, 407], [621, 340], [972, 817], [971, 291], [950, 315], [674, 315], [451, 982], [327, 829], [294, 154], [732, 601], [739, 352], [529, 495], [240, 720], [918, 387], [597, 715], [186, 716], [824, 875], [190, 852], [524, 328], [531, 753], [392, 985], [164, 849], [715, 864], [438, 935], [591, 946], [528, 690], [296, 560], [210, 102], [458, 148], [513, 615], [561, 324], [594, 451], [546, 159], [506, 473], [367, 107], [172, 230], [651, 629], [345, 628], [627, 425], [973, 940], [923, 914], [603, 437], [986, 684], [679, 230], [560, 204], [102, 578], [154, 863], [241, 153], [107, 152], [109, 530], [154, 849], [610, 175], [753, 213], [852, 279], [328, 287], [952, 832], [487, 904], [869, 519], [915, 809], [704, 657], [843, 871], [371, 351], [645, 963], [925, 638], [692, 623], [492, 786], [692, 708], [945, 658], [176, 736], [369, 547], [578, 812], [873, 763], [620, 418], [589, 209], [906, 418], [426, 976], [120, 451], [475, 735], [831, 746], [908, 270], [246, 721], [541, 120], [352, 286], [128, 826], [210, 431], [865, 687], [817, 576], [139, 907], [674, 491], [671, 396], [536, 604], [809, 396], [284, 817], [941, 841], [712, 370], [649, 931], [395, 689], [429, 249], [869, 218], [370, 730], [570, 140], [475, 136], [408, 509], [958, 294], [874, 847], [362, 807], [401, 301], [892, 204], [874, 365], [549, 780], [487, 146], [432, 293], [270, 901], [968, 891], [386, 642], [812, 801], [834, 860], [987, 237], [568, 894], [562, 271], [189, 704], [230, 928], [501, 905], [870, 189], [980, 421], [258, 126], [960, 402], [531, 852], [450, 374], [327, 840], [172, 405], [960, 680], [279, 532], [284, 829], [230, 701], [289, 218], [423, 580], [865, 895], [635, 129], [831, 809], [934, 568], [234, 901], [639, 976], [265, 256], [347, 194], [204, 863], [275, 748], [274, 973], [653, 793], [854, 873], [741, 917], [981, 653], [194, 642], [897, 538], [542, 914], [579, 701], [983, 459], [342, 857], [398, 650], [139, 973], [214, 216], [240, 684], [135, 529], [128, 780], [638, 493], [513, 240], [428, 168], [615, 423], [317, 560], [821, 791], [973, 724], [431, 729], [521, 267], [740, 231], [519, 706], [273, 897], [269, 902], [284, 362], [859, 912], [178, 352], [432, 513], [250, 248], [368, 614], [527, 319], [341, 125], [481, 543], [932, 412], [398, 428], [237, 648], [698, 870], [760, 352], [279, 749], [194, 607], [972, 973], [865, 136], [198, 750], [312, 871], [793, 159], [985, 923], [913, 635], [726, 813], [940, 948], [294, 364], [913, 482], [239, 127], [457, 390], [407, 679], [820, 327], [372, 867], [238, 794], [637, 546], [374, 857], [416, 130], [650, 650], [306, 926], [810, 823], [431, 378], [562, 593], [931, 715], [925, 256], [831, 718], [132, 837], [153, 571], [613, 436], [712, 817], [819, 527], [497, 947], [917, 629], [648, 548], [835, 164], [854, 324], [829, 859], [970, 694], [478, 860], [528, 204], [397, 925], [126, 457], [735, 593], [910, 532], [967, 930], [462, 718], [932, 867], [712, 827], [794, 534], [546, 162], [213, 941], [750, 980], [487, 761], [219, 263], [139, 870], [573, 932], [194, 609], [278, 839], [201, 305], [159, 576], [250, 857], [350, 607], [350, 674], [386, 702], [835, 561], [361, 817], [974, 187], [194, 984], [257, 201], [846, 973], [597, 361], [745, 658], [192, 397], [463, 738], [935, 913], [167, 572], [324, 210], [178, 641], [436, 890], [705, 795], [548, 721], [745, 104], [450, 612], [106, 613], [796, 908], [586, 374], [410, 827], [348, 561], [867, 573], [371, 493], [951, 438], [130, 302], [367, 156], [635, 926], [912, 346], [596, 732], [163, 850], [495, 725], [935, 849], [617, 789], [254, 952], [592, 748], [598, 514], [869, 215], [503, 906], [856, 865], [671, 893], [203, 298], [618, 168], [610, 207], [150, 634], [159, 906], [318, 867], [413, 412], [985, 134], [180, 280], [403, 781], [462, 370], [895, 567], [431, 876], [702, 583], [536, 514], [518, 364], [467, 697], [872, 853], [435, 245], [420, 134], [746, 109], [329, 278], [432, 389], [156, 875], [981, 312], [876, 361], [417, 269], [670, 762], [180, 405], [270, 319], [846, 345], [839, 863], [524, 418], [923, 704], [523, 489], [561, 913], [723, 369], [156, 620], [519, 164], [689, 354], [754, 324], [795, 459], [531, 931], [761, 187], [280, 289], [130, 907], [340, 173], [174, 846], [307, 456], [409, 729], [129, 418], [925, 465], [684, 563], [932, 582], [350, 471], [496, 547], [825, 875], [306, 245], [130, 678], [932, 264], [180, 109], [140, 520], [937, 247], [648, 954], [423, 957], [578, 254], [917, 514], [382, 539], [406, 405], [354, 486], [182, 392], [547, 124], [245, 760], [574, 187], [413, 618], [906, 976], [709, 931], [637, 891], [759, 253], [307, 684], [215, 168], [427, 683], [751, 132], [924, 182], [149, 528], [794, 564], [305, 386], [350, 497], [215, 963], [841, 102], [829, 130], [641, 149], [185, 527], [402, 804], [840, 740], [635, 641], [896, 573], [916, 987], [149, 209], [408, 904], [379, 528], [243, 863], [319, 721], [923, 942], [285, 523], [746, 429], [609, 645], [538, 528], [265, 321], [502, 615], [314, 432], [316, 349], [312, 493], [694, 260], [908, 541], [950, 630], [482, 234], [760, 548], [963, 345], [675, 569], [628, 591], [509, 485], [832, 610], [761, 480], [486, 841], [153, 841], [902, 750], [204, 905], [894, 539], [608, 137], [156, 721], [146, 435], [345, 647], [736, 239], [987, 346], [247, 319], [752, 568], [597, 796], [378, 180], [872, 601], [816, 853], [489, 583], [591, 506], [764, 603], [963, 261], [964, 702], [569, 910], [817, 649], [841, 487], [146, 609], [453, 468], [914, 684], [721, 216], [261, 703], [736, 687], [369, 927], [720, 640], [829, 741], [671, 987], [934, 248], [105, 368], [987, 714], [973, 672], [890, 840], [906, 786], [134, 351], [250, 394], [457, 540], [289, 237], [537, 104], [837, 437], [148, 504], [409, 654], [485, 895], [804, 706], [816, 943], [234, 156], [ 149, 206], [340, 542], [840, 691], [652, 514], [526, 942], [732, 347], [280, 541], [806, 521], [523, 629], [835, 359], [176, 702], [370, 732], [975, 586], [674, 857], [852, 364], [869, 376], [719, 591], [182, 469], [175, 132], [691, 417], [124, 294], [103, 809], [912, 214], [597, 203], [549, 385], [896, 970], [463, 691], [508, 701], [360, 183], [650, 471], [169, 249], [824, 198], [734, 312], [679, 308], [927, 513], [261, 384], [873, 451], [876, 972], [265, 604], [746, 594], [652, 863], [127, 608], [692, 493], [675, 958], [564, 584], [742, 206], [816, 563], [906, 209], [931, 694], [608, 203], [580, 405], [631, 315], [129, 950], [596, 496], [826, 583], [365, 928], [842, 902], [508, 497], [903, 127], [381, 916], [458, 721], [685, 469], [720, 875], [351, 319], [178, 296], [830, 740], [547, 365], [823, 679], [507, 950], [297, 395], [217, 460], [186, 354], [405, 402], [245, 641], [975, 153], [758, 604], [390, 172], [936, 672], [823, 271], [590, 462], [470, 302], [680, 837], [371, 463], [605, 560], [248, 172], [856, 813], [152, 795], [254, 739], [705, 285], [576, 968], [270, 214], [539, 793], [376, 560], [175, 843], [341, 148], [423, 458], [631, 659], [428, 640], [935, 649], [946, 105], [950, 103], [807, 964], [976, 456], [230, 607], [460, 829], [915, 489], [164, 761], [815, 395], [784, 385], [417, 412], [708, 124], [247, 716], [869, 695], [179, 795], [504, 982], [175, 497], [215, 467], [284, 638], [638, 295], [248, 510], [481, 895], [715, 528], [527, 549], [478, 875], [716, 764], [327, 168], [456, 526], [170, 356], [249, 219], [602, 850], [142, 194], [821, 609], [104, 564], [948, 842], [851, 537], [375, 823], [408, 792], [195, 465], [490, 241], [981, 235], [175, 265], [679, 347], [293, 473], [406, 259], [156, 397], [784, 360], [306, 139], [258, 689], [369, 964], [386, 172], [971, 475], [893, 286], [438, 842], [690, 249], [183, 643], [374, 150], [256, 147], [432, 346], [508, 465], [324, 546], [584, 985], [164, 160], [395, 865], [381, 971], [928, 742], [862, 715], [850, 296], [491, 214], [753, 650], [814, 256]] </code></pre> <p>My first approach - </p> <pre><code>def queensAttack(n, k, r_q, c_q, obstacles): direction_vectors = ((1,0), (1,1), (0,1), (-1,1), (-1,0), (-1,-1), (0,-1), (1,-1)) count = 0 for i in range(8): r_q_temp, c_q_temp = r_q, c_q while True: r_q_temp += direction_vectors[i][0] c_q_temp += direction_vectors[i][1] if [r_q_temp,c_q_temp] in obstacles or not(0&lt;r_q_temp&lt;n+1) or not(0&lt;c_q_temp&lt;n+1): break count += 1 return count print(queensAttack(n, k, r_q, c_q, obstacles)) </code></pre> <p>Now in u/Arviy 's code - </p> <blockquote> <pre><code>def move_queen(n, updated_row, updated_col, r , c, obs): p = 0 while True: r = updated_row(r) c = updated_col(c) key = (r - 1) * n + c if (c &lt; 1 or c &gt; n or r &lt; 1 or r &gt; n) or (key in obstacles): return p p += 1 return p def queensAttack(n, k, r_q, c_q, obstacles): obs = {} for b in obstacles: obs[(b[0] - 1) * n + b[1]] = None p = 0 dr = [-1, -1, -1, 0, 0 , 1 , 1,1] dc = [0, -1, 1, 1, -1 , 0 , 1,-1] for i in range(8): p += move_queen(n, (lambda r: r + dr[i]), (lambda c: c + dc[i] ), r_q, c_q, obs) return p print(queensAttack(n, k, r_q, c_q, obstacles)) </code></pre> </blockquote> <p>This code ran significantly faster than mine and I investigated and found that it was how he checked for obstacles, so I did the same it my code and it was immediate 10x speedup. But still my code runs about 2x slower than u/Alviy 's code. <strong>And I am unable to figure out 1. why there was a huge speedup the first time and 2. why my code is still slower?</strong></p> <p>My updated code - </p> <pre><code>def queensAttack(n, k, r_q, c_q, obstacles): direction_vectors = ((1,0), (1,1), (0,1), (-1,1), (-1,0), (-1,-1), (0,-1), (1,-1)) count = 0 obstacle_dir = {} for obstacle in obstacles: obstacle_dir[(obstacle[0] - 1) * n + obstacle[1]] = None for i in range(8): r_q_temp, c_q_temp = r_q, c_q while True: r_q_temp += direction_vectors[i][0] c_q_temp += direction_vectors[i][1] key = (r_q_temp - 1) * n + c_q_temp if key in obstacle_dir or not(0&lt;r_q_temp&lt;n+1) or not(0&lt;c_q_temp&lt;n+1): break count += 1 return count </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T23:08:17.960", "Id": "455614", "Score": "0", "body": "The answer to your question is `1^n`. It can never attack more than 1 square at a time!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T03:00:21.397", "Id": "455620", "Score": "0", "body": "Yes, it can attack only one square at a time but the question is more like how many squares are in the queen's reach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T03:02:39.623", "Id": "455621", "Score": "0", "body": "And my code gets the answer but it runs 2x slow (20x slow before borrowing a line from other code) than a similar looking implementation, and I am unable to figure out why that is ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:26:28.240", "Id": "455726", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post a follow-up question instead, or an answer if there are insightful remarks in the text." } ]
[ { "body": "<p>There are two main problems with your code.</p>\n\n<ol>\n<li>Repeated Lookups</li>\n<li>Unnecessary Calculations</li>\n</ol>\n\n<h2>Repeated Lookups</h2>\n\n<p>With a 100,000 x 100,000 chess board, when you begin moving in a particular direction, you lookup <code>direction_vectors[i][0]</code> and <code>direction_vectors[i][1]</code> and add those values to <code>r_q_temp</code> and <code>c_q_temp</code>. And on the next move you look up those values again. And on the move after that, you look up those values again.</p>\n\n<p>To be clear, each time you look up those values, the Python interpreter must:</p>\n\n<ul>\n<li>Look up <code>direction_vectors</code> in the local symbol table for <code>queensAttack</code>,</li>\n<li>Look up <code>i</code> in the local symbol table for <code>queensAttack</code>,</li>\n<li>Index to the <code>[i]</code> entry,</li>\n<li>Index to the <code>[0]</code> entry of that,</li>\n<li>Look up <code>direction_vectors</code> in the local symbol table for <code>queensAttack</code>, again,</li>\n<li>Look up <code>i</code> in the local symbol table for <code>queensAttack</code>, again,</li>\n<li>Index to the <code>[i]</code> entry, again,</li>\n<li>Index to the <code>[1]</code> entry of that.</li>\n</ul>\n\n<p>So all that happens on up to 100,000 iterations in each given direction! That is a lot of indexing &amp; lookups. They are each very fast, but a hundred thousand iterations of very fast starts becoming slow.</p>\n\n<p>First, let's speed that up.</p>\n\n<p>Instead of indexing over the (hard coded) 8 direction indices, let's loop directly over the <code>direction_vectors</code>:</p>\n\n<pre><code>for direction in direction_vectors:\n r_q_temp, c_q_temp = r_q, c_q\n while True:\n r_q_temp += direction[0]\n c_q_temp += direction[1]\n ...\n</code></pre>\n\n<p>Two wins! First, we've eliminated that ugly hard-coded <code>8</code>. If you repeat the same challenge with bishops or rooks, you don't have to remember that the number of direction vectors has changed. Second, we're no longer doing the <code>[i]</code> indexing operation twice per loop. Should be faster, since on each iteration we now only:</p>\n\n<ul>\n<li>Look up <code>direction</code> in the local symbol table for <code>queensAttack</code>,</li>\n<li>Index to the <code>[0]</code> entry of that,</li>\n<li>Look up <code>direction</code> in the local symbol table for <code>queensAttack</code>, again,</li>\n<li>Index to the <code>[1]</code> entry of that.</li>\n</ul>\n\n<p>But why stop there? Let's get rid of the <code>[0]</code> and <code>[1]</code> indexing operations as well:</p>\n\n<pre><code>for dr, dc in direction_vectors:\n r_q_temp, c_q_temp = r_q, c_q\n while True:\n r_q_temp += dr\n c_q_temp += dc\n ...\n</code></pre>\n\n<p>Now, when we loop over the <code>direction_vectors</code> elements, we unpack the tuples directly into two local variables. Again, should be faster, since on each iteration we now only:</p>\n\n<ul>\n<li>Look up <code>dr</code> in the local symbol table for <code>queensAttack</code>,</li>\n<li>Look up <code>dc</code> in the local symbol table for <code>queensAttack</code></li>\n</ul>\n\n<p>So, how did u/Alviy's code avoid this?</p>\n\n<pre><code> ..., (lambda r: r + dr[i]), (lambda c: c + dc[i]), ...\n</code></pre>\n\n<p>They are indexing <code>dr[i]</code> and <code>dc[i]</code> once per direction index, and constructing lambda functions from the values. Tricky, but it works. We're now doing effectively the same thing, just without the lambdas.</p>\n\n<h2>Unnecessary Calculations</h2>\n\n<p>Consider the statement:</p>\n\n<pre><code>if key in obstacle_dir or not(0&lt;r_q_temp&lt;n+1) or not(0&lt;c_q_temp&lt;n+1):\n</code></pre>\n\n<p>Let's assume for the moment that <code>key in obstacle_dir</code> is frequently <code>False</code>, so we need to evaluate <code>not(0&lt;r_q_temp&lt;n+1) or not(0&lt;c_q_temp&lt;n+1)</code>. Since we spend a lot of the time examining moves which are on the board, we frequently have to fully evaluate <code>0&lt;r_q_temp&lt;n+1</code> and <code>0&lt;c_q_temp&lt;n+1</code>.</p>\n\n<p>So we need to evaluate <code>n+1</code> ... twice ... per direction iteration. Hundreds of thousands of adding <code>1</code> to <code>n</code>, to get exactly the same value. Ouch.</p>\n\n<p>Compiled languages can do data flow analysis, and move constant expressions outside of loops. As Python is interpreted, (insert technobabble here), it cannot. So you end up doing an expensive <code>n+1</code> addition each iteration. Why expensive? Because, integers are objects, and adding one to a large integer requires allocating a new integer object for the result. Since it is not saved in a variable, this newly created integer becomes unreferenced and then discarded from the heap, only to be computed again (including allocation &amp; freeing) a microsecond later. Hundreds of thousands of times!</p>\n\n<p>Should we store <code>n + 1</code> in a local variable? Sure, that would work. But so would changing the sub-expression to:</p>\n\n<pre><code> not (0 &lt; r_q_temp &lt;= n) or not (0 &lt; c_q_temp &lt;= n)\n</code></pre>\n\n<p>Using \"less than or equal to\" instead of \"less than\" means the expensive <code>n + 1</code> addition goes away.</p>\n\n<hr>\n\n<p>Micro optimization: By <a href=\"https://en.wikipedia.org/wiki/De_Morgan%27s_laws\" rel=\"nofollow noreferrer\">De Morgan's Laws</a> we know that <code>not x or not y</code> is equivalent to <code>not (x and y)</code>, so we can write:</p>\n\n<pre><code> not ((0 &lt; r_q_temp &lt;= n) and (0 &lt; c_q_temp &lt;= n))\n</code></pre>\n\n<p>which saves one <code>not</code> operation. Further, we can reverse the second sub-expression:</p>\n\n<pre><code> not ((0 &lt; r_q_temp &lt;= n) and (n &gt;= c_q_temp &gt; 0))\n</code></pre>\n\n<p>which then allows us to chain the two subexpression, eliminating the second lookup of the <code>n</code> variable in the local symbol table:</p>\n\n<pre><code> not (0 &lt; r_q_temp &lt;= n &gt;= c_q_temp &gt; 0)\n</code></pre>\n\n<hr>\n\n<p>There is another unnecessary calculation that is repeated over and over again, hundreds of thousands of times:</p>\n\n<pre><code> key = (r_q_temp - 1) * n + c_q_temp\n</code></pre>\n\n<p>Specifically, <code>r_q_temp - 1</code>. Why are you subtracting <code>1</code> from <code>r_q_temp</code>? On a 10x10 grid, does it make any difference if <code>(1,1)</code> maps to <code>11</code> or <code>1</code>, as long as it is the only coordinate that does so? Subtracting <code>1</code> just reduces the value of <code>key</code> by <code>n</code> for all <code>key</code> values. But you chose to create those key values here:</p>\n\n<pre><code> obstacle_dir[(obstacle[0] - 1) * n + obstacle[1]] = None\n</code></pre>\n\n<p>All you need to do is use the same calculation ... removing the subtract 1 from that key calculation, and the obstacles will be stored under the new, more efficient-to-calculate key values. Since you are using a dictionary, the exact key values don't matter; only that they are unique.</p>\n\n<p>But while we are looking at this <code>obstacle_dir</code> ... why is it a dictionary? The only value ever stored in it is <code>None</code>. You only ever test the existence of the key in the dictionary ... so you could use a <code>set()</code>, which is more memory efficient, and as such, could be faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T11:24:12.797", "Id": "455642", "Score": "0", "body": "I agree with your optimizations for how the code is currently written, but my gut is saying that this can be done in O(1) time. After all, if you have a 100x100 board, the maximum vertical and horizontal reach that you can have is 99 (because the queen cannot attack itself). The same actually goes for the diagonals, if you rotate them. If the queen is on, say, `(5, 5)`, the maximum reach for diagonals will be `(5 - 1) + (100 - 5)`. You can check if an obstacle is on a diagonal easily by offsetting `y = mx` (of course you also have to go the opposite direction)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T14:43:30.027", "Id": "455666", "Score": "0", "body": "@ChatterOne While you have a point, keep in mind **CodeReview** is a code reviewing site, not a programming challenge answering, grading or tutoring site. The OP wrote that they “_optimized it best to what (they) could ... follows basically the same algorithm... but it still runs about 2x slower_”. I wasn’t trying to show them the best algorithm; I was reviewing _their code_, showing them where they could optimize their code further, leaving basically the same algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T10:13:16.980", "Id": "455718", "Score": "0", "body": "@ChatterOne I am aware there are other way to go about this problem and I would have turn to those if this hadn't work. \nFor now I just wanted to know that what I'm doing wrong in my code that it is slower than a code that follows the same algorithm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T10:19:49.860", "Id": "455720", "Score": "0", "body": "@AJNeufeld first of all thank you for taking time to review my code. Your answer is very detailed and addressed my question in a way I can understand. \n\n- Now you asked why am I subtracting 1 from every index when forming a directory, or why don't I use a set instead. The thing is I didn't understand what he was doing as I'm not familiar with directories. I saw that it ran faster so 'copy pasta' .I haven't formally studied python. I am just having fun with coding in my free time.\n\nI was hoping you can explain what he was doing with directories and how to do it better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T22:41:43.303", "Id": "455828", "Score": "0", "body": "Sorry. **Code Review** requires “_the code be posted by the author or maintainer of the code (...) and that the poster know why the code is written the way it is._” It may not be obvious, but I tried to avoid commenting on u/Alviy’s code, and just concentrated on reviewing your code. If you do not understand “_what he was doing as (you’re) not familiar with dictionaries_”, you shouldn’t be asking for review of the code on **Code Review**. You should ask for help elsewhere (but can probably glean useful knowledge from @Setris’s answer post)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T05:35:16.343", "Id": "233143", "ParentId": "233123", "Score": "2" } }, { "body": "<p>To answer your first question of why there was such a big speedup when comparing your first version to your updated version (which took inspiration from Alviy's solution), it's because the first version is doing an expensive lookup within a loop that runs many times:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># obstacles is List[List[int]]\nif [r_q_temp,c_q_temp] in obstacles # [...]\n</code></pre>\n\n<p>In the above snippet, we are doing an <span class=\"math-container\">\\$O(k)\\$</span> search (where <span class=\"math-container\">\\$k\\$</span> is the length of <code>obstacles</code>) for <code>[r_q_temp, c_q_temp]</code> in <code>obstacles</code>, and we're doing this every time we advance the queen by one space!</p>\n\n<p>The updated version uses a dictionary <code>obstacle_dir</code>, where lookup operations are on average <span class=\"math-container\">\\$O(1)\\$</span>, which makes a huge difference:</p>\n\n<pre><code>v1: 3.901795560005121 seconds per run (total 5 runs)\nv2: 0.07246560000348837 seconds per run (total 5 runs)\n</code></pre>\n\n<p><code>v1</code> is the first version, and <code>v2</code> is the updated version.</p>\n\n<p>And actually, if we just make two small changes to your first version (let's call it <code>v1_tweaked</code>), it runs faster than your updated version:</p>\n\n<ol>\n<li><p>Instead of an obstacle dictionary, create an obstacle set of (row, column) tuples. Like dictionaries, sets in Python also have an average <span class=\"math-container\">\\$O(1)\\$</span> lookup time. In this case, a set is the more appropriate data structure because we only need to test membership; we don't need to map the board coordinates to anything.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Set[Tuple[int, int]]\nobstacles = {tuple(obstacle) for obstacle in obstacles}\n</code></pre></li>\n<li><p>Checking if a space contains an obstacle now looks like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if (r_q_temp, c_q_temp) in obstacles # [...]\n</code></pre></li>\n</ol>\n\n<pre><code>v1: 3.901795560005121 seconds per run (total 5 runs)\nv2: 0.07246560000348837 seconds per run (total 5 runs)\nv1_tweaked: 0.06353590001817792 seconds per run (total 5 runs)\n</code></pre>\n\n<hr>\n\n<p>EDIT: There appears to be some difference in the way you and I are timing the functions, because when I ran <code>v2</code> (the updated version), <code>v1_tweaked</code> (my adjusted version of your <code>v1</code>), and Arviy's version, both <code>v2</code> and <code>v1_tweaked</code> ran faster than Arviy's version:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from functools import partial\nimport timeit\n\nn, k = 100000, 100000\nr_q, c_q = 1, 1\nobstacles = [[1000, 1000], [714, 169], ...]\n\nv2 = partial(queensAttack_v2, n, k, r_q, c_q, obstacles)\nv1_tweaked = partial(queensAttack_v1_tweaked, n, k, r_q, c_q, obstacles)\nf_arviy = partial(queensAttack_Arviy, n, k, r_q, c_q, obstacles)\n\ndef measure(f, fname, num_trials=1):\n t = timeit.timeit(f'{fname}()', setup=f'from __main__ import {fname}', number=num_trials)\n print(f'{fname}: {t / num_trials} seconds per run (total {num_trials} runs)')\n\nif __name__ == '__main__':\n TRIALS = 50\n measure(v2, 'v2', num_trials=TRIALS)\n measure(v1_tweaked, 'v1_tweaked', num_trials=TRIALS)\n measure(f_arviy, 'f_arviy', num_trials=TRIALS)\n</code></pre>\n\n<pre><code>v2: 0.07151672399835661 seconds per run (total 50 runs)\nv1_tweaked: 0.06288900200044736 seconds per run (total 50 runs)\nf_arviy: 0.0828415279998444 seconds per run (total 50 runs)\n</code></pre>\n\n<p>I am using the <a href=\"https://docs.python.org/3.8/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code></a> module, which is the recommended way to measure execution time of code snippets (more accurate than saving the time with <code>time.time()</code> before and after and calculating the difference).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:08:30.703", "Id": "455723", "Score": "0", "body": "Thank you. I understand it now. I guess I'll have to study what sets, dictionaries are. Also, can you explain what Alviy was doing with obstacle_dir[(obstacle[0] - 1) * n + obstacle[1]] = None . I still don't understand that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:24:48.413", "Id": "455724", "Score": "0", "body": "@NaveenDookia My guess is that Alviy was trying to generate a unique value (from `obstacle[0]` and `obstacle[1]`) that could be stored as the key to a dictionary, not knowing that one can just store the tuple `(obstacle[0], obstacle[1])` as the key (or even better, just use a set as I mentioned earlier). So the intent of the function `(obstacle[0] - 1) * n + obstacle[1]` is to translate a `List[int]` (which cannot be used as a key to a dictionary, because it is a mutable data structure) into an `int` (which can be used as a key to a dictionary, but in this case there are faster alternatives)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:26:35.447", "Id": "455727", "Score": "0", "body": "Okay. That makes sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:46:44.727", "Id": "455731", "Score": "0", "body": "@NaveenDookia Please see the above edit -- you should be using the `timeit` module to measure execution time of your code, not doing it manually via `time.time()`. That could be the reason why your test results differ from mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T13:13:46.430", "Id": "455738", "Score": "0", "body": "I'm a little confused by the naming scheme. I know that `v1_tweaked` uses set for lookup but `v2` was arviy's code wasn't it? and then what is f_arviy?\n\nAnyhow, I agree with your conclusions, lookup in list > lookup in dir > lookup in set.\n\nBut the thing is even if you use set for lookup in both codes my code still seem slower. I'll retime it with `timeit` and see what happenes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T14:09:59.673", "Id": "455742", "Score": "0", "body": "I retimed the codes with `timeit` and after all the tweaks from you and @AJNeufeld my code ends up faster. Thank you both, I got to learn so much." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T11:33:23.020", "Id": "233155", "ParentId": "233123", "Score": "2" } } ]
{ "AcceptedAnswerId": "233143", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T15:39:10.223", "Id": "233123", "Score": "1", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "HackerRank Problem - \"Queen's attack II\"" }
233123
<p>Quincunx is that little game where you drop a ball or disk down rows of nails in a pyramid formation until they land in a slot. This was a project for my class, but it's already been submitted. I am just looking for personal feedback since the professor does not give much in-depth feedback on these assignments. The goals of the program were to:</p> <ol> <li><p>Ask the user for how many slots they want the game to have (which also determines how many rows of nails there are).</p></li> <li><p>Ask how many balls/disks they wish to drop.</p></li> <li><p>Create a path for each ball dropped to determine what slot it lands in.</p></li> <li><p>Create a histogram to visually represent how many balls are in each slot. It should look like a bell curve.</p></li> </ol> <pre><code> import java.util.Scanner; public class Quincunx { public static void main(String[] args) { Scanner ballNumber = new Scanner(System.in); //Scanners for slots and number of balls Scanner slotNumber = new Scanner(System.in); System.out.println("Enter the Number of slots you want."); int numberOfSlots = slotNumber.nextInt(); System.out.println("Enter the number of balls you wish to drop into the slots"); int numberOfBalls = ballNumber.nextInt(); System.out.println("You are dropping " + numberOfBalls + " balls into " + numberOfSlots + " slots"); //Displaying what the user entered int Slots[] = new int[numberOfSlots]; //create an array for the slots based on how many slots the user wants int rowsOfNails = numberOfSlots - 1; //create the rows of nails to determine path size eachBallPath(numberOfBalls, rowsOfNails, Slots); for (int i = 0; i &lt; Slots.length; i++) { System.out.println("Slot " + i + " has " + Slots[i] + " balls in it"); } makeAsteriskHistogram(Slots); } public static void eachBallPath(int numberOfBalls, int rowsOfNails, int Slots[]) { for (int i = 1; i &lt;= numberOfBalls; i++) { //loop to make a path fr each ball String path = new String(pathTaken(rowsOfNails)); //generate and print the path of a ball System.out.println("Ball " + i + " took the path " + path + " and landed in slot " + ballInSlot(path, Slots)); } } public static int ballInSlot(String path, int Slots[]) { //Take the path string and find the number of times it went right to decide which slot it landed in int frequencyOfRight = 0; char R = 'R'; for (int i = 0; i &lt; path.length(); i++) { char currentLetter = path.charAt(i); // compare each character of the string to 'R' and add to frequency if R is detected if (currentLetter == R) frequencyOfRight++; } Slots[frequencyOfRight] = Slots[frequencyOfRight] + 1; //the number f Rs is the slot, add a value of 1 to a slot each time a ball lands there return frequencyOfRight; } public static String pathTaken(int rowsOfNails) { String path = new String(""); //start the path a ball takes for (int i = 0; i &lt; rowsOfNails; i++) { //do this for every row of nails, as each row is a chance to go left or right double random = Math.random(); //random number to determine left or right if (random &lt; 0.5) path = path + "L"; if (random &gt;= 0.5) path = path + "R"; } return path; } public static void makeAsteriskHistogram(int Slots[]) { //find the max value within the dataset to create a scale for the histogram int max = Slots[0]; for (int i = 0; i &lt; Slots.length; i++) { if (Slots[i] &gt; max) max = Slots[i]; } //end of the loop that found the max value for scaling the histogram for (int k = 0; k &lt; Slots.length; k++) { System.out.print("_______"); //lines to clearly seperate the graph from the previous output } System.out.println(); System.out.println("----------Number of Balls in Slot----------"); //space for aesthetic/organization System.out.print("#######|"); //aesthetic for (int i = 1; i &lt;= max; i++) { //create a horizontal scale for the values of the bars if (i &lt; 10) System.out.print("0"+ i + " "); else System.out.print(i + " "); } System.out.println(); System.out.print("#######|--"); for (int i = 0; i &lt;= max; i++) { //add dashed lines under the value scale for aesthetic System.out.print("-----"); } System.out.println(); //new line for the labels on the other axis for (int i = 0; i &lt; Slots.length; i++) { if (i &lt; 10) System.out.print(" Slot " + i + "|"); if ( i &gt;= 10) System.out.print("Slot " + i + "|");//create the label for (int j = 1; j &lt;= Slots[i]; j++) { //nested loop to print the appropiate amount of *'s to show how many in a slot System.out.print(" * "); } System.out.println();// new line for next slot } } //end of makeAsterisksHistogram method } //End of Class file </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T01:10:55.657", "Id": "455619", "Score": "5", "body": "If you wrote this without an IDE, please make sure to use one in the future. The linter will help you greatly with indenting and coding standards errors." } ]
[ { "body": "<p><strong>Don't instantiate a new <code>Scanner</code> object for every input</strong></p>\n\n<p>You only ever need 1 Scanner.</p>\n\n<p><strong>Format Strings</strong></p>\n\n<p>You can use <code>System.out.printf</code> to print formatted strings, such as:</p>\n\n<pre><code>System.out.printf(\"You are dropping %d balls into %d slots\\n\", numberOfBalls, numberOfSlots); \n</code></pre>\n\n<p><strong>Put comments above the line of code, not in the same line.</strong></p>\n\n<pre><code>// like this\nsomeCode();\n\nsomeCode(); // NOT like this\n</code></pre>\n\n<p><strong>Use java naming standards</strong> </p>\n\n<p>private &amp; method scoped variables should begin with a lower case letter. The formatting in stackexchange gives you a hint, it thinks <code>Slots</code> is a class since it begins with an uppercase:</p>\n\n<pre><code>// should be int slots[].\nint Slots[] = new int[numberOfSlots];\n</code></pre>\n\n<p><strong>Give names that make sense</strong></p>\n\n<p><code>eachBallPath</code> doesn't really make sense as a method name. <code>printEachBallPath</code> would make more sense. <code>printBallPaths</code> would make even more sense.</p>\n\n<p>Or if you'd like, <code>calculateBallPaths</code>, and have the method return an Array that can be printed elsewhere.</p>\n\n<p>Same for <code>ballInSlot</code> and <code>pathTaken</code>. Maybe <code>getBallInSlot</code> and <code>getPathTaken</code>. If you don't like using <code>get</code> for methods other than getters, I'd suggest <code>calculatePathTaken</code> &amp; <code>calculateBallInSlot</code>.</p>\n\n<p><strong>Add method documentation also known as <code>JavaDocs</code> when a method is unclear.</strong></p>\n\n<p>Taking the a glance at the method <code>ballInSlot</code> from the view of another programmer:</p>\n\n<pre><code>public static int ballInSlot(String path, int Slots[]) {\n...\nreturn frequencyOfRight;\n</code></pre>\n\n<p>It's really hard to tell what this method is actually doing. If you cannot make it clear through naming, it might be an indication the method is too complicated and should be split into multiple methods. </p>\n\n<p>However sometimes this isn't possible / doesn't help. In these cases you should:</p>\n\n<p><strong>Add a method documentation AKA Java Docs:</strong></p>\n\n<pre><code>/**\n * explanation of the method\n * @param path explanation of the parameter 'path'\n * @param Slots explanation of parameter 'Slots'\n * @return what does the method return?\n */\n</code></pre>\n\n<p>IMO every public method should be documented, and every unclear private method. Some people believe every method should be documented. However it's pretty standard to document methods that are unclear.</p>\n\n<p><strong>Regarding the code below:</strong></p>\n\n<p><strong>always use curly braces even when the code is 1 length long.</strong> </p>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/questions/2715/should-curly-braces-appear-on-their-own-line\">A good explanation</a>:</p>\n\n<blockquote>\n <p>Skimping on braces might save you a few keystrokes the first time, but\n the next coder who comes along, adds something to your else clause\n without noticing the block is missing braces is going to be in for a\n lot of pain.</p>\n \n <p>Write your code for other people.</p>\n</blockquote>\n\n<p>use <code>else if</code> or <code>else</code> whenever it makes sense to do so</p>\n\n<p>You can use shorthand <code>+=</code>, <code>-=</code>, <code>*=</code>, <code>/=</code> etc, instead of <code>variable = + variable</code> etc.</p>\n\n<pre><code>if (random &lt; 0.5)\n path = path + \"L\";\nif (random &gt;= 0.5)\n path = path + \"R\";\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T17:12:27.850", "Id": "455590", "Score": "1", "body": "thank you. I agree that my method names are probably very confusing, I just didnt think of what else to name them at the time. I wanted to avoid doing something like getBalInSlot as that is usually used for getter methods in the programming class this was for\n\nAlso, my professor advised against brackets for single-line if statements and similar, why should they actually be used?\n\nAlso thanks for pointing out I didnt use proper convention for the slots array, I tried to follow it elsewhere and I guess that slipped by me.\n\nWhat kind of documentation should be added to the methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T17:24:53.650", "Id": "455592", "Score": "0", "body": "@Daedric_Man_guy I've updated my answer with more explanations" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T17:29:26.210", "Id": "455593", "Score": "0", "body": "I would appreciate a little more explanation of what you mean by documentation, I have comments that explain what each method is trying to do. Is proper documentation meant to a few steps further and break down how each line of code performs the intended task and why the task is being performed the way it is, instead of just saying \"loop to make a path for each ball\", maybe instead make it say \"This loop generates a random number between 0 and 1 for each row of nails on the board to simulate a random turn. If the number if less than 0.5, the ball goes left, if it is >=0.5, it goes right\" ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T17:30:51.470", "Id": "455594", "Score": "0", "body": "Also, is comments above the lines of code standard convention? I ask this because my textbook always puts comments next to the relevant line of code, and my professor does too since he teaches out of the textbook" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T17:40:42.443", "Id": "455595", "Score": "0", "body": "@Daedric_Man_guy I've never heard of comments being on the same line. It's pretty standard to have them on the line above. It's possible your instructor is very old fashioned, or maybe used languages other than Java. In any you should follow what your instructor does & make your own decisions after the course" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T17:41:21.267", "Id": "455596", "Score": "0", "body": "@Daedric_Man_guy I've updated my answer, I was referring to JavaDoc's" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T13:21:16.303", "Id": "455880", "Score": "0", "body": "@Daedric_Man_guy [here's](https://www.leepoint.net/flow/if/30if-braces.html#:~:targetText=The%20semicolon%20indicates%20an%20empty,creating%20this%20kind%20of%20error.) an explanation of why you should always use braces. Those kinds of mistakes are really difficult to find!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T17:05:22.957", "Id": "233126", "ParentId": "233124", "Score": "6" } }, { "body": "<p>Thanks for sharing your code.</p>\n\n<p>Unfortunately your code has a lot of issues to be addressed:</p>\n\n<h1>Code Style</h1>\n\n<h2>Code format</h2>\n\n<p>Your code looks messy because you don't use indentation to structure blocks.\nLearn how to invoke the <em>auto formatter</em> of your IDE or how to apply it automatically \nwhen saving.</p>\n\n<h2>Comments</h2>\n\n<p>You have lots of <em>inline comments</em> that repeat what the code does.\nSuch comments are useless at best, dangerous in long living projects since the tend \nto stay unchanged while the code develops. \nThis way they turn into lies because they now say something dirrerent then the code \nitself.</p>\n\n<p>So write <em>inline comments</em> that explain <strong>why</strong> the code is like it is. </p>\n\n<p>When ever you feel you need an <em>inline comment</em> think twice if better <em>identifier names</em> \ncould support better readability.</p>\n\n<h2>Naming</h2>\n\n<p>Finding good names is the hardest part in programming. So always take your time to think about your identifier names.</p>\n\n<h3>Naming conventions</h3>\n\n<p>Please keep to the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-135099.html\" rel=\"nofollow noreferrer\">Java Naming Conventions</a>.\nThis dies nt only include the <em>camelCase</em> style, but also how identifiers are \"constructed\". \nE.g. names of methods should start with a <em>verb</em> and explain what their main task is.</p>\n\n<p>example:<br>\nyour method <code>eachBallPath()</code> should better be <code>printPathsOfAllBalls()</code> or<br>\nmethod <code>ballInSlot()</code> should better be <code>findFrequencyOfRight()</code>.</p>\n\n<h3>Choose names from the problem domain</h3>\n\n<p>Always use expressive names for your identifiers taken from the <em>problem domain</em>, not from the technical solution.\nAn example from you code is the variable <code>currentLetter</code> which would better be <code>currentTurn</code>.</p>\n\n<h3>Avoid Single letter names</h3>\n\n<p>Do not use single letter names or abbreviations. \nThere are only few exceptions like loop variables or <strong>very</strong> common abbreviations. \nWhile reading this code your brain has to do additional work to resolve single letters to their meaning. </p>\n\n<p>E.g. you have a valiable <code>R</code> that could be <code>rightTurn</code>.</p>\n\n<p>In conjunction with the previous issue the better code would read as:</p>\n\n<pre><code> int frequencyOfRight = 0;\n char rightTurn = 'R';\n for (int i = 0; i &lt; path.length(); i++) {\n char currentTurn = path.charAt(i); \n if (currentTurn == rightTurn)\n frequencyOfRight++;\n }\n</code></pre>\n\n<h1>General Coding</h1>\n\n<h2>avoid magic numbers</h2>\n\n<p>Your code uses lots of literal values. \nUsually this applies to <em>numbers</em> only but I for myself extend this to <em>Strings</em> too.\nYou should create <em>constants</em> for them with expressive names to make your code more \nreadable. </p>\n\n<p>example:</p>\n\n<pre><code>private static final String RIGHT_TURN = \"R\";\nprivate static final String LEFT_TURN = \"L\";\nprivate static final double TURN_RIGHT_CHANCE = 0.5;\n\n// ... \n\n String path = new String(\"\"); \n for (int i = 0; i &lt; rowsOfNails; i++) { \n double random = Math.random(); \n if (random &lt; TURN_RIGHT_CHANCE)\n path = path + LEFT_TURN;\n if (random &gt;= TURN_RIGHT_CHANCE)\n path = path + RIGHT_TURN;\n }\n return path;\n</code></pre>\n\n<h2>avoid unnecessary evaluations</h2>\n\n<p>The code above has another issue: you have two <code>if</code> condition to separate the opposit \ncases. \nWhy donn't simply use the <code>else</code> key word?</p>\n\n<pre><code> if (random &lt; TURN_RIGHT_CHANCE)\n path = path + LEFT_TURN;\n else\n path = path + RIGHT_TURN;\n</code></pre>\n\n<p>You might also go one step further an use the \"elvis operator\" (ternary operator):</p>\n\n<pre><code> path = random &lt; TURN_RIGHT_CHANCE ? LEFT_TURN : RIGHT_TURN;\n</code></pre>\n\n<h2>avoid explicit String object creation</h2>\n\n<p>The code <code>String path = new String(\"\")</code> is in your small program logically the same as <code>String path = \"\"</code>.\nBut it can have subtle impact on performance and logic. \nJust don't do it unless you really know why.</p>\n\n<h2>don't share singelton resources</h2>\n\n<p>In the beginning you create two instances of the <code>Scanner</code> class wrapping the same <code>System.in</code> \nobject. \nThis is a really bad idea.</p>\n\n<p>On top these <code>Scanner</code> instances have misleading names.\nThey pretend to hold the <em>number of balls</em> and the <em>number of slots</em> respectively, but \nin fact they hold the <em>user input</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T18:09:38.713", "Id": "455599", "Score": "0", "body": "Thank you, so basically similar stuff the other guy pointed out, mostly style errors (due to my professor not covering standard style conventions in too much depth. ) Also, I dont think jGrasp has an autoformat, or at least I am not aware of it after digging through some menus (We are recommended to use jGrasp in this course) and then some potential issues with readability and variable names and the two scanner issue" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T13:17:54.963", "Id": "455878", "Score": "0", "body": "@Daedric_Man_guy If you're \"recommended\" in the meaning of \"forced with kinder words\" then use jGrasp. If it's really only a recomendation and you're free to choose your own, I suggest IntelliJ or Eclipse instead. They're a bit harder to install and setup the first time, but will help you a lot more with coding standards later on (with just a few keystrokes you can have those auto-format your entire classes to the more usual Java coding standards)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T22:07:54.703", "Id": "455965", "Score": "1", "body": "@Imus *\"They're a bit harder to install and setup the first time\"* **---** Um... I don't know about `IntelliJ` but the *install process* of `eclipse` is *unzipping the archive*. How could anything be easier?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T17:48:43.753", "Id": "233128", "ParentId": "233124", "Score": "3" } } ]
{ "AcceptedAnswerId": "233126", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T16:07:00.260", "Id": "233124", "Score": "5", "Tags": [ "java", "simulation" ], "Title": "A type of game simulation dropping disks" }
233124
<p>I have been trying to get a better handle on the operator&lt;=>, so I wrote two different string wrappers. The <code>Strong_String</code> wrapper uses <code>std::strong_ordering</code> to allow the <code>std::sort</code> function to sort words like a dictionary sorts words (<em>i.e.</em> a capitalized word occurs before the lowercase word, but not before all lowercase words). The <code>Weak_String</code> wrapper uses <code>std::weak_ordering</code> to allow the <code>std::sort</code> function to sort words in a case insensitive manner.</p> <p>However, the current version distinguishes between two words being equal (<em>i.e.</em> the same character order and same cases) vs. being equivalent (<em>i.e.</em> the same character order, but with different cases). Is there a use case for this behavior? or would simple case insensitivity be preferred while maintaining the capitalization pattern of the string? </p> <p>Additionally, suggestions for code improvement are always welcome.</p> <pre><code>#include &lt;compare&gt; #include &lt;cstring&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;cassert&gt; class Strong_String { std::string s; public: Strong_String(const char* cstr) :s{ cstr } {} Strong_String(std::string&amp; s_) : s{s_} {} Strong_String(std::string&amp;&amp; s_) noexcept : s{std::move(s_)} {} bool operator==(const Strong_String&amp; rhs) noexcept; std::strong_ordering operator&lt;=&gt;(const Strong_String&amp; rhs) const; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Strong_String&amp; s); }; bool Strong_String::operator==(const Strong_String&amp; rhs) noexcept { return s == rhs.s; } std::strong_ordering Strong_String::operator&lt;=&gt;(const Strong_String&amp; rhs) const { if (s == rhs.s) return std::strong_ordering::equal; if (s.size() &lt;= rhs.s.size() &amp;&amp; std::equal(s.cbegin(), s.cend(), rhs.s.cbegin(), [](const char c, const char d) { return std::tolower(c) == std::tolower(d); })) { if (s.size() &lt; rhs.s.size()) return std::strong_ordering::less; const auto cmp = strcmp(s.c_str(), rhs.s.c_str()); if (cmp &lt; 0) return std::strong_ordering::less; return std::strong_ordering::greater; } if (s.size() &gt; rhs.s.size() &amp;&amp; std::equal(rhs.s.cbegin(), rhs.s.cend(), s.cbegin(), [](const char c, const char d) { return std::tolower(c) == std::tolower(d); })) { return std::strong_ordering::greater; } std::string t, rhs_t; std::transform(s.begin(), s.end(), std::back_inserter(t), [](unsigned char c) -&gt; unsigned char { return tolower(c); }); std::transform(rhs.s.begin(), rhs.s.end(), std::back_inserter(rhs_t), [](unsigned char c) -&gt; unsigned char { return tolower(c); }); const auto cmp = strcmp(t.c_str(), rhs_t.c_str()); if (cmp &lt; 0) return std::strong_ordering::less; return std::strong_ordering::greater; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Strong_String&amp; str) { out &lt;&lt; str.s; return out; } class Weak_String { std::string s; public: Weak_String(const char* cstr) :s{ cstr } {} Weak_String(std::string&amp; s_) : s{ s_ } {} Weak_String(std::string&amp;&amp; s_) noexcept : s{ std::move(s_) } {} bool operator==(const Weak_String&amp; rhs) noexcept; std::weak_ordering operator&lt;=&gt;(const Weak_String&amp; rhs) const; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Weak_String&amp; s); }; bool Weak_String::operator==(const Weak_String&amp; rhs) noexcept { return this-&gt;s == rhs.s; // Distinguish between equal and equivalent // return (*this &lt;=&gt; rhs) == 0; // Just Case Insensitive } std::weak_ordering Weak_String::operator&lt;=&gt;(const Weak_String&amp; rhs) const { if (s == rhs.s) return std::weak_ordering::equivalent; if (s.size() &lt;= rhs.s.size() &amp;&amp; std::equal(s.cbegin(), s.cend(), rhs.s.cbegin(), [](const char c, const char d) { return std::tolower(c) == std::tolower(d); })) // Are the first characters equivalent { if (s.size() &lt; rhs.s.size()) return std::weak_ordering::less; return std::weak_ordering::equivalent; } if (s.size() &gt; rhs.s.size() &amp;&amp; std::equal(rhs.s.cbegin(), rhs.s.cend(), s.cbegin(), [](const char c, const char d) { return std::tolower(c) == std::tolower(d); })) // Are the first characters equivalent { return std::weak_ordering::greater; } std::string t, rhs_t; std::transform(s.begin(), s.end(), std::back_inserter(t), [](unsigned char c) -&gt; unsigned char { return tolower(c); }); std::transform(rhs.s.begin(), rhs.s.end(), std::back_inserter(rhs_t), [](unsigned char c) -&gt; unsigned char { return tolower(c); }); const auto cmp = strcmp(t.c_str(), rhs_t.c_str()); if (cmp &lt; 0) return std::weak_ordering::less; return std::weak_ordering::greater; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Weak_String&amp; str) { out &lt;&lt; str.s; return out; } template &lt;typename T&gt; void helper(T s, T t) { if (s == t) { std::cout &lt;&lt; s &lt;&lt; " is equal to " &lt;&lt; t &lt;&lt; "\n"; } else std::cout &lt;&lt; s &lt;&lt; " is not equal to " &lt;&lt; t &lt;&lt; "\n"; if (s &lt; t) { std::cout &lt;&lt; s &lt;&lt; " is less than " &lt;&lt; t &lt;&lt; "\n"; } else std::cout &lt;&lt; s &lt;&lt; " is not less than " &lt;&lt; t &lt;&lt; "\n"; if (s &gt; t) { std::cout &lt;&lt; s &lt;&lt; " is greater than " &lt;&lt; t &lt;&lt; "\n"; } else std::cout &lt;&lt; s &lt;&lt; " is not greater than " &lt;&lt; t &lt;&lt; "\n"; if (s &lt;= t) { std::cout &lt;&lt; s &lt;&lt; " is less than or equal to " &lt;&lt; t &lt;&lt; "\n"; } else std::cout &lt;&lt; s &lt;&lt; " is not less than or equal to " &lt;&lt; t &lt;&lt; "\n"; if ((s &lt;=&gt; t) == 0) { std::cout &lt;&lt; s &lt;&lt; " is equivalent to " &lt;&lt; t &lt;&lt; "\n"; } else std::cout &lt;&lt; s &lt;&lt; " is not equivalent to " &lt;&lt; t &lt;&lt; "\n"; std::cout &lt;&lt; "\n"; } int main() { std::cout &lt;&lt; "strong_ordering String:\n"; Strong_String ss{ "hello" }; Strong_String st{ "HELLO" }; helper(ss, st); assert(ss != st &amp;&amp; "Not Equal"); assert(!(ss &lt; st) &amp;&amp; "Not Less Than"); assert(ss &gt; st &amp;&amp; "Greater Than"); assert(!(ss &lt;= st) &amp;&amp; "Not Less Than or Equal To"); assert((ss &lt;=&gt; st) != 0 &amp;&amp; "Not Equivalent"); std::vector&lt;Strong_String&gt; strong_vector = { "cat","dog","CAT","DOG","fish", "RAT","FISH","rat","doggy","rAT","raT" }; std::sort(strong_vector.begin(), strong_vector.end()); [[gsl::suppress(26486)]] { for (const auto astring : strong_vector) std::cout &lt;&lt; astring &lt;&lt; "\n"; } std::cout &lt;&lt; "\n"; std::cout &lt;&lt; "weak_ordering String:\n"; Weak_String ws{ "hello" }; Weak_String wt{ "HELLO" }; helper(ws, wt); assert(ws != wt &amp;&amp; "Not Equal"); assert(!(ws &lt; wt) &amp;&amp; "Not Less Than"); assert(!(ws &gt; wt) &amp;&amp; "Not Greater Than"); assert(ws &lt;= wt &amp;&amp; "Less Than or Equal To"); assert((ws &lt;=&gt; wt) == 0 &amp;&amp; "Equivalent"); std::vector&lt;Weak_String&gt; weak_vector = { "cat","DOG","CAT","dog","fish", "RAT","FISH","rat","doggy","rAT","raT" }; std::sort(weak_vector.begin(), weak_vector.end()); [[gsl::suppress(26486)]] { for (const auto astring : weak_vector) std::cout &lt;&lt; astring &lt;&lt; "\n"; } std::cout &lt;&lt; "\n"; } </code></pre> <p>output: (using visual studio 2019 with the "Preview" c++ compiler option)</p> <pre><code>strong_ordering String: hello is not equal to HELLO hello is not less than HELLO hello is greater than HELLO hello is not less than or equal to HELLO hello is not equivalent to HELLO CAT cat DOG dog doggy FISH fish RAT rAT raT rat weak_ordering String: hello is not equal to HELLO hello is not less than HELLO hello is not greater than HELLO hello is less than or equal to HELLO hello is equivalent to HELLO cat CAT DOG dog doggy fish FISH RAT rat rAT raT C:\Users\David\source\repos\junk2\Debug\junk2.exe (process 21200) exited with code 0. To automatically close the console when debugging stops, enable Tools-&gt;Options-&gt;Debugging-&gt;Automatically close the console when debugging stops. Press any key to close this window . . . ~~~ </code></pre>
[]
[ { "body": "<p>My main suggestion for this code is for the <code>helper</code> function. It's not a good idea to only compare a few selected strings from the set of all interesting strings. It's far more efficient to just have a list of strings that are already ordered, and then ensure that this ordering is represented by the <code>&lt;=&gt;</code> operator under test.</p>\n\n<p>To do this, each element should be compared to each element, including itself. The code I usually use to do this is:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;cassert&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;iostream&gt;\n\nint sign(int i)\n{\n return i &lt; 0 ? -1 : i &gt; 0 ? +1 : 0;\n}\n\ntemplate&lt;typename T&gt;\nint spaceship(T a, T b)\n{\n return a &lt; b ? -123 : a &gt; b ? +123 : 0;\n}\n\nstd::string op(int cmp)\n{\n return cmp &lt; 0 ? \"&lt;\" : cmp &gt; 0 ? \"&gt;\" : \"==\";\n}\n\ntemplate&lt;typename T&gt;\nvoid test_spaceship(const std::vector&lt;T&gt; &amp;elements)\n{\n bool error = false;\n\n for (std::size_t i = 0; i &lt; elements.size(); ++i) {\n for (std::size_t j = 0; j &lt; elements.size(); ++j) {\n int expected = spaceship(i, j);\n int actual = spaceship(elements[i], elements[j]);\n if (sign(expected) != sign(actual)) {\n std::cerr &lt;&lt; __func__ &lt;&lt; \":\\n\";\n std::cerr &lt;&lt; \" expected \" &lt;&lt; elements[i] &lt;&lt; \" \"\n &lt;&lt; op(expected) &lt;&lt; \" \" &lt;&lt; elements[j] &lt;&lt; \"\\n\";\n std::cerr &lt;&lt; \" but got \" &lt;&lt; elements[i] &lt;&lt; \" \"\n &lt;&lt; op(actual) &lt;&lt; \" \" &lt;&lt; elements[j] &lt;&lt; \"\\n\";\n error = true;\n }\n }\n }\n std::flush(std::cerr);\n assert(!error);\n}\n\nint main()\n{\n std::vector&lt;std::string&gt; elements{\n \"\",\n \"first\",\n \"second\",\n \"zfourth\", // intentionally in the wrong order\n \"third\",\n \"zzfifth\"\n };\n\n test_spaceship(elements);\n std::cout &lt;&lt; \"ok\\n\";\n std::string s;\n std::getline(std::cin, s);\n}\n</code></pre>\n\n<p>Of course you would have to adjust the code a bit to test your <code>Strong_String</code> instead of my <code>std::string</code>, but the general idea should get clear.</p>\n\n<p>If you have some strings that are considered equal by your operator <code>&lt;=&gt;</code>, you would have to adjust the above code to have a <code>std::vector&lt;std::vector&lt;T&gt;&gt;</code>, but that should be equally easy.</p>\n\n<hr>\n\n<p>My other favorite topic is the <a href=\"https://stackoverflow.com/questions/7131026/is-it-safe-to-call-the-functions-from-cctype-with-char-arguments\">cctype header</a> since you must never feed a plain character to functions like <code>isalnum</code> or <code>toupper</code>. Furthermore by doing this, you limit your program to 8-bit character sets, unless <code>CHAR_BIT</code> is greater than 8 on your machine, and chances are small for that.</p>\n\n<p>You should rather treat your strings as Unicode strings, and that brings a whole new topic of decisions, such as sorting strings from different scripts and languages. But that's still better than being caught in the 1990s with their limited <a href=\"https://en.wikipedia.org/wiki/Code_page\" rel=\"nofollow noreferrer\">code pages</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:10:27.227", "Id": "455667", "Score": "0", "body": "Thanks for the systematic test, I'll be sure to use it in my code. Can you tell me why `for (const auto astring : weak_vector) std::cout << astring << \"\\n\";` is giving me a \"Don't pass a pointer that may be invalid to a function. Parameter 0 '@weak_vector' in call to 'Weak_String::Weak_String' may be invalid (lifetime.3).\" warning (C26486)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T18:19:23.127", "Id": "455679", "Score": "0", "body": "No, I cannot. But have a close look at the error message. The keyword [`lifetime.3`](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1179r0.pdf) looks like a reference to the C++ standard or a related document, and C26486 has an error number for exactly one reason: to search for it unambiguously." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T20:09:19.793", "Id": "233133", "ParentId": "233129", "Score": "5" } }, { "body": "<p>After reading Roland Illig's review and altering the code according to his recommendations, I went searching other improvements. The first thing I realized is that the code for the <code>operator&lt;=&gt;</code> function in <code>Strong_String</code> and <code>Weak_String</code> was really inefficient. So, I rewrote the function as follows:</p>\n\n<pre><code>std::strong_ordering Strong_String::operator&lt;=&gt;(const Strong_String&amp; rhs) const\n{\n const auto cmp = [](const unsigned char c, const unsigned char d) {\n return std::tolower(c) == std::tolower(d);\n };\n\n if (s == rhs.s) return std::strong_ordering::equal;\n auto values = std::mismatch(s.cbegin(), s.cend(), \n rhs.s.cbegin(), rhs.s.cend(), cmp);\n if (values.first == s.cend()) {\n if (values.second == rhs.s.cend()) { // no mismatches same length\n const auto comp = strcmp(s.c_str(), rhs.s.c_str()); // uppercase first\n if (comp &lt; 0) return std::strong_ordering::less;\n return std::strong_ordering::greater;\n }\n return std::strong_ordering::less; // s is shorter than rhs.s\n }\n if (values.second == rhs.s.cend()) return std::strong_ordering::greater;\n if (tolower(*(values.first)) &lt; tolower(*(values.second))) {\n return std::strong_ordering::less;\n }\n return std::strong_ordering::greater;\n}\n</code></pre>\n\n<p>In addition to being more compact and easier to read, this has the advantage of not having any unnecessary copying or additional looping, and it gets rid of code redundancy naming the lambda function. I have replaced the <code>std::equal</code> function with the <code>std::mismatch</code> function. This allows me to determine if the strings are the same as well as capture the differential character.</p>\n\n<p>Well, that felt better, but when digging deeper, it seemed like the code for the class <code>Weak_String</code> and the class <code>Strong_String</code> were nearly identical. Further, I could not decide which version of the <code>Weak_String</code> class I liked better, when <code>operator==</code> was true only when the case matched or when just the character order was sufficient. So, with all these similar types of strings that I might want to use in some future project, decided to remove the redundancy through making a <em>templated class</em> <code>Multi_String</code>. I also create an <em>enum class</em> to distinguish the different kinds of strings.</p>\n\n<p><code>Multi_String.hpp</code></p>\n\n<pre><code>#ifndef MULTI_STRING\n#define MULTI_STRING\n#pragma once\n\n#include &lt;compare&gt;\n#include &lt;cstring&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;cassert&gt;\n\nenum class String_Type : uint8_t {\n regular,\n dictionary,\n case_equivalent,\n case_insensitve\n};\n\ntemplate &lt;String_Type ST&gt;\nclass Multi_String;\ntemplate &lt;String_Type ST&gt;\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Multi_String&lt;ST&gt;&amp; str);\n\ntemplate &lt;String_Type ST&gt;\nclass Multi_String\n{\n std::string s;\npublic:\n Multi_String(const char* cstr) : s{ cstr } {}\n Multi_String(const std::string&amp; s_) : s{ s_ } {}\n Multi_String(std::string&amp;&amp; s_) noexcept : s{ std::move(s_) } {}\n auto operator&lt;=&gt;(const Multi_String&lt;ST&gt;&amp; rhs) const;\n bool operator==(const Multi_String&lt;ST&gt;&amp; rhs) noexcept;\n const char* c_str() const noexcept;\n\n friend std::ostream&amp; operator&lt;&lt; (std::ostream&amp; out, const Multi_String&lt;ST&gt;&amp; s);\n};\n\n\ntemplate&lt;String_Type ST&gt;\nconst char* Multi_String&lt;ST&gt;::c_str() const noexcept\n{\n return s.c_str();\n}\n\n#pragma warning(push)\n#pragma warning(disable:26486)\n#pragma warning(disable:26489)\ntemplate&lt;String_Type ST&gt;\nauto Multi_String&lt;ST&gt;::operator&lt;=&gt;(const Multi_String&lt;ST&gt;&amp; rhs) const\n{\n const auto cmp = [](const unsigned char c, const unsigned char d) {\n return std::tolower(c) == std::tolower(d);\n };\n if (s == rhs.s) return std::weak_ordering::equivalent;\n auto values = std::mismatch(s.cbegin(), s.cend(), rhs.s.cbegin(),\n rhs.s.cend(), cmp);\n if (values.first == s.cend()) {\n if (values.second == rhs.s.cend()) // no mismatches same length\n return std::weak_ordering::equivalent;\n return std::weak_ordering::less; // s is shorter than rhs.s\n }\n if (values.second == rhs.s.cend()) return std::weak_ordering::greater;\n if (tolower(*(values.first)) &lt; tolower(*(values.second))) {\n return std::weak_ordering::less;\n }\n return std::weak_ordering::greater;\n}\n\ntemplate&lt;&gt;\nauto Multi_String&lt;String_Type::regular&gt;::operator&lt;=&gt;\n(const Multi_String&lt;String_Type::regular&gt;&amp; rhs) const\n{\n if (s == rhs.s) return std::strong_ordering::equal;\n if (s &lt; rhs.s) return std::strong_ordering::less;\n return std::strong_ordering::greater;\n}\n\ntemplate&lt;&gt;\nauto Multi_String&lt;String_Type::dictionary&gt;::operator&lt;=&gt;\n (const Multi_String&lt;String_Type::dictionary&gt;&amp; rhs) const\n{\n const auto cmp = [](const unsigned char c, const unsigned char d) {\n return std::tolower(c) == std::tolower(d);\n };\n if (s == rhs.s) return std::strong_ordering::equal;\n auto values = std::mismatch(s.cbegin(), s.cend(),\n rhs.s.cbegin(), rhs.s.cend(), cmp);\n if (values.first == s.cend()) {\n if (values.second == rhs.s.cend()) { // no mismatches same length\n const auto comp = strcmp(s.c_str(), rhs.s.c_str()); // uppercase first\n if (comp &lt; 0) return std::strong_ordering::less;\n return std::strong_ordering::greater;\n }\n return std::strong_ordering::less; // s is shorter than rhs.s\n }\n if (values.second == rhs.s.cend()) return std::strong_ordering::greater;\n if (tolower(*(values.first)) &lt; tolower(*(values.second))) {\n return std::strong_ordering::less;\n }\n return std::strong_ordering::greater;\n}\n#pragma warning (pop)\n\ntemplate&lt;String_Type ST&gt;\nbool Multi_String&lt;ST&gt;::operator==(const Multi_String&lt;ST&gt;&amp; rhs) noexcept {\n return this-&gt;s == rhs.s; // Distinguish between equal and equivalent\n}\n\ntemplate&lt;&gt;\nbool Multi_String&lt;String_Type::case_insensitve&gt;::operator==\n(const Multi_String&lt;String_Type::case_insensitve&gt;&amp; rhs) noexcept {\n return (*this &lt;=&gt; rhs) == 0; // Case Insensitive\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, \n const Multi_String&lt;String_Type::regular&gt;&amp; str) {\n out &lt;&lt; str.s;\n return out;\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, \n const Multi_String&lt;String_Type::dictionary&gt;&amp; str) {\n out &lt;&lt; str.s;\n return out;\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, \n const Multi_String&lt;String_Type::case_equivalent&gt;&amp; str) {\n out &lt;&lt; str.s;\n return out;\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, \n const Multi_String&lt;String_Type::case_insensitve&gt;&amp; str) {\n out &lt;&lt; str.s;\n return out;\n}\n\n#endif // !MULTI_STRING\n</code></pre>\n\n<p>I tried, but I was unable to combine the two identical versions of <code>cmp</code> within the body of the class. I was also unable to get a cleaner version of <code>operator&lt;&lt;</code>, but since there are only four cases, this was OK.</p>\n\n<p>Additionally, I wanted to compare my <em>case insensitive</em> string to that of Mr. Sutter's GOTW #29 which manipulates the <code>class trait</code> of the <code>std::basic_string</code>. Both functions perform identically in Mr. Sutter's tests. I show this code here:</p>\n\n<pre><code>// Herb Sutter solution to make case-insensitive strings\n// Manipulate the \"class traits\" to lose case sensitivity\n// for more see: http://gotw.ca/gotw/029.htm\n// \n// CI_String.hpp\n//\n#ifndef CI_STRING\n#define CI_STRING\n\n#pragma once\n\n#include &lt;string&gt;\n#include &lt;cassert&gt;\nusing std::char_traits;\nusing std::basic_string;\n\nstruct ci_char_traits : public char_traits&lt;char&gt;\n // just inherit all the other functions\n // that we don't need to override\n{\n static bool eq(char c1, char c2);\n static bool ne(char c1, char c2);\n static bool lt(char c1, char c2);\n static int compare(const char* s1, const char* s2, size_t n);\n static const char* find(const char* s, int n, char a);\n};\n\nusing ci_String = basic_string&lt;char, ci_char_traits&gt;;\n\n#endif // !CI_STRING\n\n//\n// CI_String.cpp\n//\n#include \"CI_String.hpp\"\n#pragma warning(push)\n#pragma warning(disable:26440)\n#pragma warning(disable:26489)\n#pragma warning(disable:26481)\n\nbool ci_char_traits::eq(char c1, char c2)\n{\n return toupper(c1) == toupper(c2);\n}\n\nbool ci_char_traits::ne(char c1, char c2)\n{\n return toupper(c1) != toupper(c2);\n}\n\nbool ci_char_traits::lt(char c1, char c2)\n{\n return toupper(c1) &lt; toupper(c2);\n}\n\nint ci_char_traits::compare(const char* s1, const char* s2, size_t n)\n{\n assert(s1 != nullptr);\n assert(s2 != nullptr);\n\n return _memicmp(s1, s2, n);\n}\n\nconst char* ci_char_traits::find(const char* s, int n, char a)\n[[gsl::suppress(26487)]]\n{\n assert(s != nullptr);\n while (n-- &gt; 0 &amp;&amp; toupper(*s) != toupper(a)) {\n ++s;\n }\n return s;\n}\n</code></pre>\n\n<p>As well as the reworked <strong>main</strong> program:</p>\n\n<pre><code>#include \"Multi_String.hpp\"\n#include \"CI_String.hpp\" \n#include &lt;compare&gt;\n#include &lt;cstring&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;cassert&gt;\n#include &lt;memory&gt;\n#include &lt;random&gt;\n\nconstexpr int sign(int i) noexcept\n{\n return i &lt; 0 ? -1 : i &gt; 0 ? +1 : 0;\n}\n\ntemplate&lt;typename T&gt;\nint spaceship(T a, T b) noexcept\n{\n return a &lt; b ? -123 : a &gt; b ? +123 : 0;\n}\n\nstd::string op(int cmp)\n{\n return cmp &lt; 0 ? \"&lt;\" : cmp &gt; 0 ? \"&gt;\" : \"==\";\n}\n\ntemplate&lt;typename T&gt;\nvoid test_spaceship(const std::vector&lt;T&gt;&amp; elements)\n{\n bool error = false;\n\n [[gsl::suppress(26446)]]\n for (std::size_t i = 0; i &lt; elements.size(); ++i) {\n for (std::size_t j = 0; j &lt; elements.size(); ++j) {\n const int expected = spaceship(i, j);\n const int actual = spaceship(elements[i], elements[j]);\n if (sign(expected) != sign(actual)) {\n std::cout &lt;&lt; __func__ &lt;&lt; \":\\n\";\n std::cout &lt;&lt; \" expected \" &lt;&lt; elements[i] &lt;&lt; \" \"\n &lt;&lt; op(expected) &lt;&lt; \" \" &lt;&lt; elements[j] &lt;&lt; \"\\n\";\n std::cout &lt;&lt; \" but got \" &lt;&lt; elements[i] &lt;&lt; \" \"\n &lt;&lt; op(actual) &lt;&lt; \" \" &lt;&lt; elements[j] &lt;&lt; \"\\n\";\n error = true;\n }\n }\n }\n std::flush(std::cerr);\n}\n\nusing EQ_String = Multi_String&lt;String_Type::case_equivalent&gt;;\nusing CI_String = Multi_String&lt;String_Type::case_insensitve&gt;;\nusing R_String = Multi_String&lt;String_Type::regular&gt;;\nusing D_String = Multi_String&lt;String_Type::dictionary&gt;;\n\n#pragma warning(push)\n#pragma warning(disable:26486)\nint main()\n{\n std::vector&lt;D_String&gt; dictionary_vector = { \"cat\",\"CAT\",\"DOG\",\"dog\",\n \"fish\",\"Dog\",\"\" };\n\n std::cout &lt;&lt; \"Before sort : \";\n for (const auto&amp; s : dictionary_vector) std::cout &lt;&lt; s &lt;&lt; \" \";\n std::cout &lt;&lt; \"\\n\";\n std::sort(dictionary_vector.begin(), dictionary_vector.end());\n\n std::cout &lt;&lt; \"After dictionary sort: \";\n std::vector&lt;CI_String&gt; ci_vector;\n std::vector&lt;EQ_String&gt; eq_vector;\n std::vector&lt;R_String&gt; regular_vector;\n std::vector&lt;ci_String&gt; sutter_vector;\n for (const auto&amp; s : dictionary_vector) {\n std::cout &lt;&lt; s &lt;&lt; \" \";\n ci_vector.emplace_back(s.c_str());\n eq_vector.emplace_back(s.c_str());\n regular_vector.emplace_back(s.c_str());\n sutter_vector.emplace_back(s.c_str());\n }\n std::cout &lt;&lt; \"\\n\\n\";\n\n std::cout &lt;&lt; \"CI_String:\\n\";\n test_spaceship(ci_vector);\n std::cout &lt;&lt; \"\\n\";\n\n std::cout &lt;&lt; \"EQ_String:\\n\";\n test_spaceship(eq_vector);\n std::cout &lt;&lt; \"\\n\";\n\n std::cout &lt;&lt; \"R_String:\\n\";\n test_spaceship(regular_vector);\n std::cout &lt;&lt; \"\\n\";\n\n auto ci_last = std::unique(ci_vector.begin(), ci_vector.end());\n if (ci_last == ci_vector.end())\n std::cout &lt;&lt; \"CI_vector is UNIQUE!\\n\";\n else std::cout &lt;&lt; \"CI_vector is not UNIQUE!\\n\";\n ci_vector.erase(ci_last, ci_vector.end());\n for(const auto &amp; s : ci_vector) std::cout &lt;&lt; s &lt;&lt; \" \";\n std::cout &lt;&lt; \"\\n\\n\";\n\n auto sutter_last = std::unique(sutter_vector.begin(), sutter_vector.end());\n if (sutter_last == sutter_vector.end())\n std::cout &lt;&lt; \"Sutter ci_vector is UNIQUE!\\n\";\n else std::cout &lt;&lt; \"Sutter ci_vector is not UNIQUE!\\n\";\n sutter_vector.erase(sutter_last, sutter_vector.end());\n for (const auto&amp; s : sutter_vector) std::cout &lt;&lt; s.c_str() &lt;&lt; \" \";\n std::cout &lt;&lt; \"\\n\\n\";\n\n auto rd = std::random_device();\n auto e1 = std::default_random_engine(rd());\n std::shuffle(eq_vector.begin(), eq_vector.end(), e1);\n std::cout &lt;&lt; \"EQ_vector shuffled: \";\n for (const auto&amp; s : eq_vector) std::cout &lt;&lt; s &lt;&lt; \" \";\n std::cout &lt;&lt; \"\\n\";\n std::sort(eq_vector.begin(), eq_vector.end());\n std::cout &lt;&lt; \"EQ_vector sort : \";\n for (const auto&amp; s : eq_vector) std::cout &lt;&lt; s &lt;&lt; \" \";\n std::cout &lt;&lt; \"\\n\";\n\n auto eq_last = std::unique(eq_vector.begin(), eq_vector.end());\n if (eq_last == eq_vector.end())\n std::cout &lt;&lt; \"EQ_vector is UNIQUE!\\n\";\n else std::cout &lt;&lt; \"EQ_vector is not UNIQUE!\\n\";\n eq_vector.erase(eq_last, eq_vector.end());\n for(const auto &amp; s : eq_vector) std::cout &lt;&lt; s &lt;&lt; \" \";\n std::cout &lt;&lt; \"\\n\\n\";\n\n CI_String weak_test{ \"AbCdE\" };\n assert(weak_test == \"abcde\");\n assert(weak_test == \"ABCDE\");\n assert(std::strcmp(weak_test.c_str(), \"AbCdE\") == 0);\n assert(std::strcmp(weak_test.c_str(), \"abcde\") != 0);\n\n std::cout &lt;&lt; \"success for CI_String: \" &lt;&lt; weak_test.c_str() &lt;&lt; \"\\n\\n\";\n\n ci_String sutter_test{ \"AbCdE\" };\n assert(sutter_test == \"abcde\");\n assert(sutter_test == \"ABCDE\");\n assert(std::strcmp(sutter_test.c_str(), \"AbCdE\") == 0);\n assert(std::strcmp(sutter_test.c_str(), \"abcde\") != 0);\n\n std::cout &lt;&lt; \"success for sutter ci_string: \"\n &lt;&lt; sutter_test.c_str() &lt;&lt; \"\\n\\n\";\n}\n#pragma warning(pop)\n</code></pre>\n\n<p>And Output:</p>\n\n<pre><code>Before sort : cat CAT DOG dog fish Dog\nAfter dictionary sort: CAT cat DOG Dog dog fish\n\nCI_String:\ntest_spaceship:\n expected CAT &lt; cat\n but got CAT == cat\ntest_spaceship:\n expected cat &gt; CAT\n but got cat == CAT\ntest_spaceship:\n expected DOG &lt; Dog\n but got DOG == Dog\ntest_spaceship:\n expected DOG &lt; dog\n but got DOG == dog\ntest_spaceship:\n expected Dog &gt; DOG\n but got Dog == DOG\ntest_spaceship:\n expected Dog &lt; dog\n but got Dog == dog\ntest_spaceship:\n expected dog &gt; DOG\n but got dog == DOG\ntest_spaceship:\n expected dog &gt; Dog\n but got dog == Dog\n\nEQ_String:\ntest_spaceship:\n expected CAT &lt; cat\n but got CAT == cat\ntest_spaceship:\n expected cat &gt; CAT\n but got cat == CAT\ntest_spaceship:\n expected DOG &lt; Dog\n but got DOG == Dog\ntest_spaceship:\n expected DOG &lt; dog\n but got DOG == dog\ntest_spaceship:\n expected Dog &gt; DOG\n but got Dog == DOG\ntest_spaceship:\n expected Dog &lt; dog\n but got Dog == dog\ntest_spaceship:\n expected dog &gt; DOG\n but got dog == DOG\ntest_spaceship:\n expected dog &gt; Dog\n but got dog == Dog\n\nR_String:\ntest_spaceship:\n expected cat &lt; DOG\n but got cat &gt; DOG\ntest_spaceship:\n expected cat &lt; Dog\n but got cat &gt; Dog\ntest_spaceship:\n expected DOG &gt; cat\n but got DOG &lt; cat\ntest_spaceship:\n expected Dog &gt; cat\n but got Dog &lt; cat\n\nCI_vector is not UNIQUE!\n CAT DOG fish\n\nSutter ci_vector is not UNIQUE!\n CAT DOG fish\n\nEQ_vector shuffled: CAT Dog DOG dog cat fish\nEQ_vector sort : CAT cat Dog DOG dog fish\nEQ_vector is UNIQUE!\n CAT cat Dog DOG dog fish\n\nsuccess for CI_String: AbCdE\n\nsuccess for sutter ci_string: AbCdE\n</code></pre>\n\n<p>Notice that the <code>case_equivalent</code> (EQ_String) and <code>case_insensitive</code> (CI_String) designations give the same equivalency answers when sorting, but find a very different set of unique members. Also notice that the order for the <code>regular</code> vs. <code>dictionary</code> sorts differ only in how the capital letters get sorted.\nI hope this helps</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T02:49:44.187", "Id": "233214", "ParentId": "233129", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-28T18:19:13.350", "Id": "233129", "Score": "6", "Tags": [ "c++", "beginner", "c++20" ], "Title": "Playing with operator<=> (operator spaceship) in c++" }
233129
<p>I wrote this program which generates anagrams for a given word. The init function will create a dictionary of words. it can be read from a text file or array. Here I'm reading words from an array to create my dictionary. I would like some advice on how to optimize this code or any changes or suggestions needed to improve efficiency of this code is appreciated. </p> <pre><code>import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class Solution { static Map&lt;String, ArrayList&lt;String&gt;&gt; dictionaryMap = new HashMap&lt;String, ArrayList&lt;String&gt;&gt;(); private void addToMap(String key, String word) { ArrayList&lt;String&gt; anagramList = dictionaryMap.get(key); if (anagramList == null) { anagramList = new ArrayList&lt;String&gt;(); anagramList.add(word); dictionaryMap.put(key, anagramList); } if (!anagramList.contains(word)) { anagramList.add(word); dictionaryMap.put(key, anagramList); } } private String createMap(String word) { Map&lt;Character, Integer&gt; characterCountMap = new HashMap&lt;Character, Integer&gt;(); StringBuffer buff = new StringBuffer(); char arr[] = word.toLowerCase().toCharArray(); Arrays.sort(arr); String sortString = Arrays.toString(arr); for (int i = 0; i &lt; sortString.length(); i++) { char c = sortString.charAt(i); if (characterCountMap.containsKey(c)) characterCountMap.put(c, characterCountMap.get(c) + 1); else characterCountMap.put(c, 1); } for (Map.Entry&lt;Character, Integer&gt; entry : characterCountMap.entrySet()) buff.append(entry.getKey() + entry.getValue()); return buff.toString(); } private Map&lt;String, ArrayList&lt;String&gt;&gt; init(String[] words) { for (String word : words) { addToMap(createMap(word), word); } return dictionaryMap; } private String[] getAnagrams(String word) { String key = createMap(word); List&lt;String&gt; al = dictionaryMap.get(key); String[] arr = al.toArray(new String[al.size()]); return arr; } public static void main(String[] args) { Solution obj = new Solution(); System.out.println("This is a debug message"); String arr[] = { "ate", "eat", "THIS", "EAT" }; obj.init(arr); for (String anagram : obj.getAnagrams("tea")) System.out.println(anagram); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T07:38:55.770", "Id": "455716", "Score": "0", "body": "Are you generating only exact anagrams or can an anagram consist of two or more words?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T09:38:55.080", "Id": "455717", "Score": "0", "body": "Welcome to Code Review. It seems me for every word you create a key in your map concatenating ascii code of chars and the number of occurrences after sorting and then anagrams have the same representation, could you give more informations about this algorithm?" } ]
[ { "body": "<p>Thanks for sharing your code.</p>\n\n<p>This is what I think about it</p>\n\n<h1>General Coding</h1>\n\n<h2>program against interfaces</h2>\n\n<p>Most of your variables are defines as <em>concrete types</em> (classes you actually instantiate). \nYou should better declare them as <em>interface types</em> so that it is possible to exchange \nthe concrete implementation without changing the code all over.</p>\n\n<p>example</p>\n\n<pre><code>static Map&lt;String, ArrayList&lt;String&gt;&gt; dictionaryMap = new HashMap&lt;String, ArrayList&lt;String&gt;&gt;();\n</code></pre>\n\n<p>should better be</p>\n\n<pre><code>static Map&lt;String, List&lt;String&gt;&gt; dictionaryMap = new HashMap&lt;String, ArrayList&lt;String&gt;&gt;();\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>static Map&lt;String, Collection&lt;String&gt;&gt; dictionaryMap = new HashMap&lt;String, ArrayList&lt;String&gt;&gt;();\n</code></pre>\n\n<p>Problem here is that you need to know what interfaces are available and what the \nconsequences are using them. The <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/overview-tree.html\" rel=\"nofollow noreferrer\">public API</a> \nis the place to find that information.</p>\n\n<h2>Be consistent</h2>\n\n<p>Choose the same approach for the same problem</p>\n\n<p>E.g. you use two different types of loops</p>\n\n<pre><code> for (int i = 0; i &lt; sortString.length(); i++) {\n char c = sortString.charAt(i);\n //...\n // vs.\n for (String word : words) {\n addToMap(createMap(word), word);\n //...\n</code></pre>\n\n<p>Unless you really need the index variable for something else then accessing the actual \nobject in the collection loops over you could (and should) stick to the <em>foreach</em> \nform</p>\n\n<pre><code> for (char c : sortString.toCharArray()) {\n</code></pre>\n\n<h2>Learn about the capabilities of the objects provided by the runtime</h2>\n\n<p>Especially the class <code>Map</code> has some interesting methods your code could benefit from: \nThe code</p>\n\n<pre><code> ArrayList&lt;String&gt; anagramList = dictionaryMap.get(key);\n if (anagramList == null) {\n anagramList = new ArrayList&lt;String&gt;();\n anagramList.add(word);\n dictionaryMap.put(key, anagramList);\n }\n</code></pre>\n\n<p>could be replaced by</p>\n\n<pre><code> ArrayList&lt;String&gt; anagramList = dictionaryMap.computeIfAbsent(key,()-&gt;new ArrayList&lt;String&gt;());\n</code></pre>\n\n<p>If you would know that beside (<code>Array-</code>)<code>List</code> which allows duplicates, the <em>Java \nRuntime</em> provides another collection type <code>Set</code> which does not hold duplicates, then \nyou could even get rid of the other <code>if</code> in this method too:</p>\n\n<pre><code>static Map&lt;String, Collection&lt;String&gt;&gt; dictionaryMap = new HashMap&lt;String, Collection&lt;String&gt;&gt;();\n\nprivate void addToMap(String key, String word) {\n dictionaryMap.computeIfAbsent(key,()-&gt; new HashSet&lt;String&gt;())\n .add(word);\n }\n</code></pre>\n\n<h2>Avoid arrays</h2>\n\n<p>instead of arrays better use <code>Collection</code> types like any implementations of the <code>List</code> \nand <code>Set</code> interfaces. They are more flexible and prevent you to copy data (yourself) \nwhen its size needs to be changed.</p>\n\n<h2>use the <code>static</code> key word with intention</h2>\n\n<p>You declared the variable <code>dictionaryMap</code> as a <em>class variable</em> although it is not \naccessed by any static method. Unless you understand the consequences you should not use the <code>static</code> key word.</p>\n\n<h2>narrow your interfaces</h2>\n\n<p>Your method <code>init()</code> has a return value which is not needed since there is no caller \nof this method dealing with this return value. Methods with return value usually \nare harder to refactor. Especially its harder to split them into smaller methods.</p>\n\n<h1>Naming</h1>\n\n<p>Finding good names is the hardest part in programming, so always take your time to \nthink about the names of your identifiers</p>\n\n<h2>Please read (and follow) the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-135099.html\" rel=\"nofollow noreferrer\">Java Naming Conventions</a>.</h2>\n\n<p>This does not only apply to the casing of the identifiers. \nIt also applies to how names are \"constructed\".\nE.g.: you named a method <code>getAnagrams()</code>. \nBy conventions the prefix <em>get</em> is reserved for methods, that do not do any processing \nbut simply return a property of the object.\nBut your method does a lot more than that.\nTherefore a better name could be <code>findAnagramsOf(String word)</code>.</p>\n\n<h2>avoid single character names</h2>\n\n<p>Since the number of characters is quite limited in most languages you will soon run \nout of names. This means that you either have to choose another character which is \nnot so obviously connected to the purpose of the variable. And/or you have to \"reuse\" \nvariable names in different contexts. Both makes your code hard to read and understand \nfor other persons. (Keep in mind that you are that other person yourself if you look \nat your code in a few month!)</p>\n\n<p>On the other hand in Java the length of identifier names is virtually unlimited. \nThere is no penalty in any way for long identifier names. So don't be stingy with \nletters when choosing names.</p>\n\n<h2>Choose your names from the problem domain</h2>\n\n<p>Some of your identifiers (or at least parts of them) have technical meaning. \nBut your identifiers should convey you <em>business solution</em>. </p>\n\n<p>example: <code>characterCountMap</code>, <code>c</code>, <code>sortString</code> or <code>arr</code>.</p>\n\n<p>Remember that the technical details may change while the meaning of your identifiers \nin respect to the business problem will remain.\nso this identifiers might better be: </p>\n\n<p><code>characterCounts</code>, <code>currentCharacter</code>, <code>sortedCharacters</code> or <code>wordCharacters</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T20:36:05.223", "Id": "455813", "Score": "1", "body": "I believe `getOrDefault` isn't the right method you want to use. `getOrDefault` doesn't write the value back into the map. It should be `computeIfAbsent`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T22:04:34.713", "Id": "455964", "Score": "0", "body": "@RoToRa yes, you're right. Thanks for spotting that. I updated the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T09:52:46.537", "Id": "456001", "Score": "1", "body": "It isn't quite right yet. You still have an `getOrDefault` example and also the second argument of `computeIfAbsent` needs to be a `Supplier<>` (`() -> new ArrayList<String>()` or `ArrayList<String>::new`)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T14:14:04.587", "Id": "233196", "ParentId": "233136", "Score": "7" } }, { "body": "<p>Your code is quite complicated. It's possible to do it in a much simpler way. But to do that, you have to know a trick about anagrams:</p>\n\n<blockquote>\n <p>Iff two words are anagrams of each other, their sorted characters are the same.</p>\n</blockquote>\n\n<p>This means that you don't need to count each character in a map, you can just take a string, sort its characters (like you already do), make it a string again (which you also do) and use this string as the key to the map.</p>\n\n<p>When you abstract the problem further, it can be seen as a map, in which multiple entries can be stored for each key. This is also something that your code already does. The crucial point is how the key is calculated. You already defined a method for that and called it <code>createMap</code>. That name is wrong. That method does not create a map, it computes the <em>key</em> instead.</p>\n\n<p>Your key generation method should be as simple as:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private String key(String word) {\n char[] chars = word.toLowerCase().toCharArray();\n Arrays.sort(chars);\n return new String(chars);\n}\n</code></pre>\n\n<p>One area where you can improve your code a lot is how you name the variables. Right now you named most of the variables based on their type. For example, <code>al</code> is a list. It probably was an <code>ArrayList</code> somewhere in the past, that's where the <code>a</code> might originate from. Or the <code>a</code> means <code>anagram</code>, in which case the variable should really have been called <code>anagrams</code>.</p>\n\n<p>In general, variable names should represent the <em>purpose</em> of the variable, not the <em>data type</em>. The data type is easy to see if you have a good editor, but the purpose is much more important to express.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T14:21:03.043", "Id": "233197", "ParentId": "233136", "Score": "2" } }, { "body": "<p>Let's start from beginning: you defined a class <code>Solution</code> containing a <code>map</code> like below:</p>\n\n<blockquote>\n<pre><code>public class Solution {\n static Map&lt;String, ArrayList&lt;String&gt;&gt; dictionaryMap = new HashMap&lt;String, ArrayList&lt;String&gt;&gt;();\n}\n</code></pre>\n</blockquote>\n\n<p>With the use of <code>ArrayList</code> the map can contains duplicates of string : to avoid this issue you can use a <code>Set</code> and specifically a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html\" rel=\"nofollow noreferrer\">TreeSet</a> because when you iterate over keys, they are ordered by their natural ordering. So the class can be rewritten like below:</p>\n\n<pre><code>public class Solution {\n private Map&lt;String, Set&lt;String&gt;&gt; map;\n\n public Solution() {\n this.map =new TreeMap&lt;&gt;();\n }\n}\n</code></pre>\n\n<p>Once you defined the class in this way you can define two methods <code>addWords</code> and <code>addWord</code> to add words to your dictionary like below:</p>\n\n<pre><code>public void addWords(String[] words) {\n for (String word : words) {\n addWord(word);\n }\n}\n\nprivate void addWord(String word) {\n String key = generateKey(word);\n\n if (!map.containsKey(key)) {\n map.put(key, new TreeSet&lt;String&gt;(Arrays.asList(word)));\n } else {\n Set&lt;String&gt; set = map.get(key);\n set.add(word);\n }\n}\n</code></pre>\n\n<p>You can check inside the method <code>addWord</code> the method <code>generateKey</code> is called to generate the key corresponding to the word you are trying to include in your dictionary; if the key is not already contained in your map a new <code>TreeSet</code> containing the word will be created and associated to the key in the map, otherwise the word is an anagram of a word already present in the dictionary and will be added to the existing <code>TreeSet</code>.</p>\n\n<p>The most important method of the program is the <code>generateKey</code> method that generate a representation of the word you want to insert in your dictionary, I'm using a representation formed by concatenation of chars of word and their occurrences sorted in alphabethic order:</p>\n\n<ul>\n<li>\"tea\" -> a1e1t1</li>\n<li>\"eat\" -> a1e1t1</li>\n</ul>\n\n<p>Below the code of the method generateKey;</p>\n\n<pre><code>private static String generateKey(String word) {\n Map&lt;Character, Integer&gt; map = new TreeMap&lt;&gt;();\n StringBuilder builder = new StringBuilder();\n char arr[] = word.toLowerCase().toCharArray();\n\n for (char key : arr) {\n int value = map.getOrDefault(key, 0);\n map.put(key, ++value);\n }\n\n Set&lt;Character&gt; set = map.keySet();\n for (Character ch : set) {\n builder.append(ch + Integer.toString(map.get(ch)));\n }\n\n return builder.toString();\n}\n</code></pre>\n\n<p>You can check I used inside the method a <code>TreeMap</code> to obtain characters keys already naturally ordered, so I don't need to use <code>sort</code> method like your code.</p>\n\n<p>The final method is the method <code>getAnagrams</code> that returns the list of anagrams of the word in a array that can be empty if the word or its anagrams are present in the dictionary (I would prefer this method returns an unmodifiable collection instead of array):</p>\n\n<pre><code>public String[] getAnagrams(String word) {\n String key = generateKey(word);\n Set&lt;String&gt; set = map.getOrDefault(key, new TreeSet&lt;&gt;());\n return set.stream().toArray(String[]::new);\n}\n</code></pre>\n\n<p>Here the complete code of class Solution:</p>\n\n<p><strong>Solution.java</strong></p>\n\n<pre><code>package codereview;\n\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeMap;\nimport java.util.TreeSet;\n\npublic class Solution {\n private Map&lt;String, Set&lt;String&gt;&gt; map;\n\n public Solution() {\n this.map =new TreeMap&lt;&gt;();\n }\n\n public void addWords(String[] words) {\n for (String word : words) {\n addWord(word);\n }\n }\n\n private void addWord(String word) {\n String key = generateKey(word);\n\n if (!map.containsKey(key)) {\n map.put(key, new TreeSet&lt;String&gt;(Arrays.asList(word)));\n } else {\n Set&lt;String&gt; set = map.get(key);\n set.add(word);\n }\n }\n\n private static String generateKey(String word) {\n Map&lt;Character, Integer&gt; map = new TreeMap&lt;&gt;();\n StringBuilder builder = new StringBuilder();\n char arr[] = word.toLowerCase().toCharArray();\n\n for (char key : arr) {\n int value = map.getOrDefault(key, 0);\n map.put(key, ++value);\n }\n\n Set&lt;Character&gt; set = map.keySet();\n for (Character ch : set) {\n builder.append(ch + Integer.toString(map.get(ch)));\n }\n\n return builder.toString();\n }\n\n public String[] getAnagrams(String word) {\n String key = generateKey(word);\n Set&lt;String&gt; set = map.getOrDefault(key, new TreeSet&lt;&gt;());\n return set.stream().toArray(String[]::new);\n }\n\n public static void main(String[] args) {\n Solution obj = new Solution();\n System.out.println(\"This is a debug message\");\n String words[] = { \"ate\", \"eat\", \"THIS\", \"EAT\" };\n obj.addWords(words);\n for (String anagram : obj.getAnagrams(\"tea\"))\n System.out.println(anagram);\n }\n}\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T10:30:43.407", "Id": "233222", "ParentId": "233136", "Score": "2" } } ]
{ "AcceptedAnswerId": "233196", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T01:14:59.003", "Id": "233136", "Score": "6", "Tags": [ "java" ], "Title": "find all anagrams of a given word" }
233136
<p>Currently I use jfreechart through swt. The current problem is tens of thousands of files (currently between 10,000 and 20,000, up to 100,000 later)</p> <p>I currently use <code>DefaultXYDataset</code> and <code>XYLineAndShapeRenderer</code> to load data after opening a file.</p> <p>There are a few problems:</p> <ol> <li><p>The chart on the screen is not immediate (within seconds). Work with setchart in the current file open listener.</p></li> <li><p>When resizing the shell, there is a delay in drawing the chart. This causes the program to run slowly.</p></li> <li><p>The jfreechart zoom function and mouse drag events are slow.</p></li> </ol> <p>My questions:</p> <ol> <li><p>Is there a quick way to draw when redrawing a new data chart in <code>chartcomposite</code>?</p></li> <li><p>Essentially, is <code>XYLineAndShapeRenderer</code> not good at rendering tens of thousands of data? If so, what is the best method?</p></li> <li><p>There is a slight speedup using <code>fastscatterplot</code> but I want the line to be a line rather than a dot. Is there a way to line <code>fastscatterplot</code>?</p></li> </ol> <p>This is my test code. The screen works very slowly even with 100,000 datasets. Are there speed issues in your current code?</p> <pre><code>import java.awt.BasicStroke; import java.awt.Color; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.experimental.chart.swt.ChartComposite; public class TestGui { private JFreeChart chart; private ChartComposite frame; public static void main(String[] args) { try { TestGui window = new TestGui(); window.open(); } catch (Exception e) { e.printStackTrace(); } } public void open() { Display display = Display.getDefault(); Shell shell = new Shell(); shell.setSize(600, 400); shell.setText("SWT Application"); shell.setLayout(new GridLayout(1, false)); // create chart = createChart(createDataset(getSeries())); // using chartcomposite frame = new ChartComposite(shell, SWT.NONE, chart, true); frame.setDisplayToolTips(false); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.widthHint = 600; data.heightHint = 366; frame.setLayoutData(data); shell.open(); shell.layout(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } //making chart private JFreeChart createChart(XYDataset dataset){ JFreeChart chart = ChartFactory.createXYLineChart( "", "x", "y", dataset, PlotOrientation.VERTICAL, false, false, false); XYPlot plot = chart.getXYPlot(); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false); renderer.setSeriesPaint(0, Color.RED); int seriesCount = plot.getSeriesCount(); for (int i = 0; i &lt; seriesCount; i++) { plot.getRenderer().setSeriesStroke(i, new BasicStroke(0)); } plot.setRenderer(renderer); plot.setBackgroundPaint(Color.white); plot.setRangeGridlinesVisible(true); plot.setRangeGridlinePaint(Color.BLACK); plot.setDomainGridlinesVisible(true); plot.setDomainGridlinePaint(Color.BLACK); return chart; } private XYDataset createDataset(double[] x) { XYSeries series = new XYSeries(""); for(int i = 0; i&lt;x.length; i++) { series.add(i,x[i],false); } XYSeriesCollection dataset = new XYSeriesCollection(); dataset.addSeries(series); return dataset; } private static double[] getSeries() { double[] series = new double[104857]; for(int i = 0; i &lt; series.length; i++) { series[i] = Math.sin(i * 33 * Math.PI / series.length) + Math.sin(i * 15 * Math.PI / series.length); } return series; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T09:31:21.667", "Id": "455639", "Score": "0", "body": "Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T02:44:14.077", "Id": "233138", "Score": "1", "Tags": [ "java", "gui" ], "Title": "How to quickly work a linechart created with jfreechart" }
233138
<p>This is a simple strlen function with registers documented:</p> <pre><code>;in rdi - string to measure ;out rax - len .my_strlen: test rdi, rdi jz ptr_error or rcx, 0xFFFFFFFFFFFFFFFF mov al, 0 cld repne scasb mov rax, 0xFFFFFFFFFFFFFFFF sub rax, rcx ret </code></pre> <p>NOTE: This code assumes a "C-Style string"; that is, a NUL-terminated string.</p>
[]
[ { "body": "<blockquote>\n<pre><code>or rcx, 0xFFFFFFFFFFFFFFFF\n</code></pre>\n</blockquote>\n\n<p>This is an optimization for size, but it does not break the dependency on the old value of <code>rcx</code> (at least not yet, maybe someday, it's not an impossible feature). That's a minor point compared to overall cost of a <code>strlen</code> but it's something to know so you can make the choice deliberately.</p>\n\n<blockquote>\n<pre><code>cld\n</code></pre>\n</blockquote>\n\n<p>Should be redundant, typical calling conventions specify that the direction flag is cleared at function call boundaries so your <code>strlen</code> shouldn't be called with it set to backwards. </p>\n\n<blockquote>\n<pre><code>mov rax, 0xFFFFFFFFFFFFFFFF\nsub rax, rcx\n</code></pre>\n</blockquote>\n\n<p>mov-ing a 64bit immediate is surprisingly slow, and also a huge instruction. An alternative is:</p>\n\n<pre><code>not rcx\nmov rax, rcx\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T05:11:02.830", "Id": "233142", "ParentId": "233141", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T04:18:31.460", "Id": "233141", "Score": "3", "Tags": [ "strings", "assembly", "x86" ], "Title": "x64 fasm strlen" }
233141
<p><a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi" rel="nofollow noreferrer">From Wikipedia</a></p> <p>The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:</p> <ol> <li>Only one disk can be moved at a time.</li> <li>Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.</li> <li>No larger disk may be placed on top of a smaller disk.</li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T06:22:56.960", "Id": "233144", "Score": "0", "Tags": null, "Title": null }
233144
A puzzle to build the Tower of Hanoi on an area of 3 rods with a number of disks of varying size.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T06:22:56.960", "Id": "233145", "Score": "0", "Tags": null, "Title": null }
233145
<p>I am new to writing utility functions. I wrote a python program to return a Python logger with custom settings. Please review this code and provide comments on how to improve it. I am looking for comments on </p> <ol> <li>Coding Style</li> <li>Coherence &amp; Coupling</li> <li>Readability</li> </ol> <p>I am intending to share this code across all projects. So any comments on this to improve are highly appreciated.</p> <pre><code>import logging import sys import logging.handlers def get_default_log_format(): """ Method to return the default log format""" log_format = logging.Formatter("%(module)s - %(asctime)s — %(name)s — %(levelname)s - %(funcName)s:%(lineno)d — %(message)s") return log_format def get_new_console_handler(log_format=None): """This method returns a console handler with the given log_format Keyword Arg: log_format accepts logging.Formatter object. """ console_handler = logging.StreamHandler(sys.stdout) if log_format is None: log_format = get_default_log_format() console_handler.setFormatter(log_format) return console_handler def get_new_file_handler(log_format=None, log_file_name="out.log"): file_handler = logging.FileHandler(log_file_name) if log_format is None: log_format = get_default_log_format() file_handler.setFormatter(log_format) return file_handler def get_new_rotating_file_handler(log_file_name="out.log", max_log_bytes=2000000, max_log_backup_files=20, log_format=None): """ This method returns a file handler with the given file name, max_log_bytes, max_log_backup_files and log_format. This log_format accepts logging.Formatter object""" # Here, max_log_bytes is the maximum size of file in Bytes and max_log_backup_files is the number of backup files to store. file_handler = logging.handlers.RotatingFileHandler(log_file_name, maxBytes=max_log_bytes, backupCount=max_log_backup_files) if log_format is None: log_format = get_default_log_format() file_handler.setFormatter(log_format) return file_handler def get_new_console_logger(logger_name, log_format=None, log_level=logging.DEBUG): handler = get_new_console_handler() logger = logging.getLogger(logger_name) logger.setLevel(log_level) logger.addHandler(handler) return logger def get_new_file_logger(logger_name, log_file, log_format=None, log_level=logging.DEBUG): handler = get_new_file_handler(log_format, log_file) if log_file is None: log_file = "execution.log" logger = logging.getLogger(logger_name) logger.setLevel(log_level) logger.addHandler(handler) return logger def get_new_file_console_logger(logger_name, log_file, log_format=None, log_level=logging.DEBUG): if log_file is None: log_file = "execution.log" logger = get_new_file_logger(logger_name, log_file) console_handler = get_new_console_handler() logger.addHandler(console_handler) return logger if __name__ == "__main__": # To get a console handler, run this code console_logger = get_new_console_logger(logger_name="logger1") console_logger.debug("Hello World") # To get a file logger, run this code file_logger = get_new_file_logger(logger_name="logger3", log_file="out.log") file_logger.critical("This is a critical message") # To get a console and file logger, run this code console_file_logger = get_new_file_console_logger(logger_name="my_logging2", log_file="out3.log") console_file_logger.error("Error: This is from console file logger") # logger.info("Begining of execution") # logger.info("logging Info message") # logger.debug("This is a debug message") # logger.debug(logging.DEBUG) # logger.info(logging.INFO) # logger.warning(logging.WARNING) # logger.error(logging.ERROR) # logger.critical(logging.CRITICAL) # logger.info("End of Execution") </code></pre>
[]
[ { "body": "<h3><em>Restructuring and consolidation</em></h3>\n\n<p><em>Logging configuration</em></p>\n\n<p>When having a <em>constant</em> logging options like posted <code>log_format</code> or <code>log_level=logging.DEBUG</code> you might have been used <a href=\"https://docs.python.org/3/library/logging.html#logging.basicConfig\" rel=\"nofollow noreferrer\"><code>logging.basicConfig</code></a> or even <a href=\"https://docs.python.org/3/library/logging.config.html#logging.config.dictConfig\" rel=\"nofollow noreferrer\"><code>dictConfig</code></a> to apply specified options globally to all underlying cases.<br>But since your intention is to allow the client create different specialized <em>loggers</em> with dynamic logging options, <em>\"base\"</em> config won't give much benefit. At least, it's good to remind of such a <em>base configuration</em> capability.</p>\n\n<hr>\n\n<p><em>Handlers</em></p>\n\n<p>All 3 handlers run the same common set of statements to ensure <em>logging format</em>:</p>\n\n<pre><code>if log_format is None:\n log_format = get_default_log_format()\nconsole_handler.setFormatter(log_format)\n</code></pre>\n\n<p>That calls for consolidation and reducing duplication.<br>Moreover, when creating some concrete logger instance a client may pass <code>log_format</code> as a raw format string like <code>log_format='%(funcName)s:%(lineno)d — %(message)s'</code>, not as <code>logging.Formatter</code> instance. Thus, for further optimizations I'll eliminate <code>get_default_log_format</code> function and declare a constant:</p>\n\n<pre><code>LOG_FMT = '%(module)s - %(asctime)s — %(name)s — %(levelname)s - %(funcName)s:%(lineno)d — %(message)s'\n</code></pre>\n\n<p>According to the scenario where the client/caller operates only on <code>.._logger</code> functions to instantiate concrete loggers, that points to direct relation between specific <em>logger</em> and respective <em>handler</em>(s). And assuming that duplicated common code should be moved out from all handlers - they ceased <em>pulling their weigh</em> and are removed in favor of direct handler usage. See the final implementation below.</p>\n\n<hr>\n\n<p><em><code>..._logger</code> functions</em></p>\n\n<p><em>\"logger\"</em> creation functions perform a common set of actions:</p>\n\n<pre><code>logger = logging.getLogger(logger_name)\nlogger.setLevel(log_level)\nlogger.addHandler(handler)\n</code></pre>\n\n<p>that also calls for consolidation.<br>The condition</p>\n\n<pre><code>if log_file is None:\n log_file = \"execution.log\"\n</code></pre>\n\n<p>is eliminated by simply making <code>log_file</code> a default argument <strong><code>log_file=\"execution.log\"</code></strong>.</p>\n\n<hr>\n\n<p>To perform consolidation and reducing duplication a <em>factory</em> function <strong><code>logger_factory(logger_name, handlers_list, log_format, log_level)</code></strong> is introduced. It concentrates a common behavior and also allows to attach multiple <em>handlers</em> to the same <em>logger</em>. </p>\n\n<p>The final optimized version:</p>\n\n<pre><code>import logging\nimport sys\nimport logging.handlers\n\nLOG_FMT = '%(module)s - %(asctime)s — %(name)s — %(levelname)s - %(funcName)s:%(lineno)d — %(message)s'\n\n\ndef logger_factory(logger_name, handlers_list, log_format, log_level):\n logger = logging.getLogger(logger_name)\n logger.setLevel(log_level)\n\n if not isinstance(handlers_list, (list, tuple)):\n handlers_list = [handlers_list]\n for handler in handlers_list:\n handler.setFormatter(logging.Formatter(log_format))\n logger.addHandler(handler)\n\n return logger\n\n\ndef create_console_logger(logger_name, log_format=LOG_FMT, log_level=logging.DEBUG):\n return logger_factory(logger_name, handlers_list=[logging.StreamHandler(sys.stdout)],\n log_format=log_format, log_level=log_level)\n\n\ndef create_file_logger(logger_name, log_file=\"execution.log\", log_format=LOG_FMT, log_level=logging.DEBUG):\n return logger_factory(logger_name, handlers_list=[logging.FileHandler(log_file)],\n log_format=log_format, log_level=log_level)\n\n\ndef create_rotating_file_logger(logger_name, log_file=\"out.log\", max_log_bytes=2000000, max_log_backup_files=20,\n log_format=LOG_FMT, log_level=logging.DEBUG):\n \"\"\" Creates rotating file logger with the given file name, max_log_bytes, max_log_backup_files and log_format.\n :param log_file: log file name\n :param max_log_bytes: the maximum size of file in Bytes\n :param max_log_backup_files: the number of backup files to store\n :param log_format: custom format as logging.Formatter object\n :param log_level: logging level\n :return: logging.Logger\n \"\"\"\n handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=max_log_bytes,\n backupCount=max_log_backup_files)\n return logger_factory(logger_name, handlers_list=[handler],\n log_format=log_format, log_level=log_level)\n\n\ndef create_file_console_logger(logger_name, log_file=\"execution.log\", log_format=LOG_FMT, log_level=logging.DEBUG):\n handlers = [logging.FileHandler(log_file), logging.StreamHandler(sys.stdout)]\n return logger_factory(logger_name, handlers_list=handlers,\n log_format=log_format, log_level=log_level)\n\n\nif __name__ == \"__main__\":\n # To get a console handler, run this code\n console_logger = create_console_logger(logger_name=\"logger1\")\n console_logger.debug(\"Hello World\")\n\n # To get a file logger, run this code\n file_logger = create_file_logger(logger_name=\"logger3\", log_file=\"out.log\")\n file_logger.critical(\"This is a critical message\")\n\n # To get a console and file logger, run this code\n console_file_logger = create_file_console_logger(logger_name=\"my_logging2\", log_file=\"out3.log\")\n console_file_logger.error(\"Error: This is from console file logger\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T18:54:04.137", "Id": "455684", "Score": "0", "body": "Thanks for the detailed answer. It helped me :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T19:00:36.957", "Id": "455685", "Score": "0", "body": "@Mithilesh_Kunal, you're welcome" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:12:35.447", "Id": "233167", "ParentId": "233146", "Score": "5" } } ]
{ "AcceptedAnswerId": "233167", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T08:06:37.350", "Id": "233146", "Score": "5", "Tags": [ "python", "python-3.x", "logging" ], "Title": "Python logging - wrapper" }
233146
<p>I have finished a raycaster, and I want to optimize it before I add other features, such as variable height walls, texture mapping and lighting. I'd like someone to review the code so I can improve it further.</p> <p><a href="https://pastebin.com/raw/91rLfcwd" rel="nofollow noreferrer">Pastebin</a></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;SDL2/SDL.h&gt; #include &lt;sys/time.h&gt; const int RESX = 960; const int RESY = 540; const float ROTSPEED = 0.03; const float MOVESPEED = 0.08; const float STRAFEMOVESPEED = 0.05657; char placeDist = 3; char MAP[32][32] = { {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}}; int main() { float posX = 3, posY = 4; float dirX = 1, dirY = 0; //direction vector float planeX = 0, planeY = 0.66; //camera plane float time = 0; float oldtime = 0; //for FPS calculations SDL_Window* window = NULL; //init SDL SDL_Renderer* renderer = NULL; SDL_Surface* surface = NULL; if( SDL_Init( SDL_INIT_VIDEO ) &lt; 0 ) { printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() ); } window = SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, RESX, RESY, SDL_WINDOW_SHOWN ); if( window==NULL) { printf( "SDL_Error: %s\n", SDL_GetError() ); } surface = SDL_GetWindowSurface( window ); renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED); if(renderer==NULL) { printf("Renderer error: %s\n", SDL_GetError() ); } char running = 1; const Uint8* keystate = SDL_GetKeyboardState( NULL ); clock_t t1, t2; while( running == 1 ) { t1 = clock(); SDL_Rect rect; rect.w = 1; SDL_Event e; SDL_SetRenderDrawColor( renderer, 0x11, 0x11, 0x11, 0xFF); SDL_RenderClear( renderer ); if( SDL_PollEvent( &amp;e ) &gt; 0) { if( e.type == SDL_QUIT) running = 0; } float oldPlaneX, oldDirX; if(keystate[SDL_SCANCODE_RIGHT]) { oldDirX = dirX; dirX = dirX * cos(ROTSPEED) - dirY * sin(ROTSPEED); dirY = oldDirX * sin(ROTSPEED) + dirY * cos(ROTSPEED); oldPlaneX = planeX; planeX = planeX * cos(ROTSPEED) - planeY * sin(ROTSPEED); planeY = oldPlaneX * sin(ROTSPEED) + planeY * cos(ROTSPEED); } if(keystate[SDL_SCANCODE_LEFT]) { oldDirX = dirX; dirX = dirX * cos(-ROTSPEED) - dirY * sin(-ROTSPEED); dirY = oldDirX * sin(-ROTSPEED) + dirY * cos(-ROTSPEED); oldPlaneX = planeX; planeX = planeX * cos(-ROTSPEED) - planeY * sin(-ROTSPEED); planeY = oldPlaneX * sin(-ROTSPEED) + planeY * cos(-ROTSPEED); } if(keystate[SDL_SCANCODE_D]) { if(keystate[SDL_SCANCODE_W] ^ keystate[SDL_SCANCODE_S]) { if(!MAP[(char)(posX-dirY*STRAFEMOVESPEED)][(char)posY]) posX-=dirY*STRAFEMOVESPEED; if(!MAP[(char)posX][(char)(posY-dirX*STRAFEMOVESPEED)]) posY+=dirX*STRAFEMOVESPEED; } else { if(!MAP[(char)(posX-dirY*MOVESPEED)][(char)posY]) posX-=dirY*MOVESPEED; if(!MAP[(char)posX][(char)(posY-dirX*MOVESPEED)]) posY+=dirX*MOVESPEED; } } if(keystate[SDL_SCANCODE_A]) { if(keystate[SDL_SCANCODE_W] ^ keystate[SDL_SCANCODE_S]) { if(!MAP[(char)(posX+dirY*STRAFEMOVESPEED)][(char)posY]) posX+=dirY*STRAFEMOVESPEED; if(!MAP[(char)posX][(char)(posY-dirX*STRAFEMOVESPEED)]) posY-=dirX*STRAFEMOVESPEED; } else { if(!MAP[(char)(posX+dirY*MOVESPEED)][(char)posY]) posX+=dirY*MOVESPEED; if(!MAP[(char)posX][(char)(posY-dirX*MOVESPEED)]) posY-=dirX*MOVESPEED; } } if(keystate[SDL_SCANCODE_W]) { if(keystate[SDL_SCANCODE_D] ^ keystate[SDL_SCANCODE_A]) { if(!MAP[(char)(posX+dirX*STRAFEMOVESPEED)][(char)posY]) posX+=dirX*STRAFEMOVESPEED; if(!MAP[(char)posX][(char)(posY+dirY*STRAFEMOVESPEED)]) posY+=dirY*STRAFEMOVESPEED; } else { if(!MAP[(char)(posX+dirX*MOVESPEED)][(char)posY]) posX+=dirX*MOVESPEED; if(!MAP[(char)posX][(char)(posY+dirY*MOVESPEED)]) posY+=dirY*MOVESPEED; } } if(keystate[SDL_SCANCODE_S]) { if(keystate[SDL_SCANCODE_D] ^ keystate[SDL_SCANCODE_A]) { if(!MAP[(char)(posX-dirX*STRAFEMOVESPEED)][(char)posY]) posX-=dirX*STRAFEMOVESPEED; if(!MAP[(char)posX][(char)(posY-dirY*STRAFEMOVESPEED)]) posY-=dirY*STRAFEMOVESPEED; } else { if(!MAP[(char)(posX-dirX*MOVESPEED)][(char)posY]) posX-=dirX*MOVESPEED; if(!MAP[(char)posX][(char)(posY-dirY*MOVESPEED)]) posY-=dirY*MOVESPEED; } } if(keystate[SDL_SCANCODE_SPACE]) { MAP[(char)(posX+dirX*placeDist)][(char)(posY+dirY*placeDist)] = 1; } if(keystate[SDL_SCANCODE_LCTRL]) { MAP[(char)(posX+dirX*placeDist)][(char)(posY+dirY*placeDist)] = 0; } if(keystate[SDL_SCANCODE_LSHIFT]) { MAP[(char)posX][(char)posY] = 0; } for(int z = 0; z &lt; RESX; z += 1 ) { //raycasting code rect.x = z; float cameraX = 2 * z/(float)RESX -1; // cam vector, -1 to 1 float raydX = dirX + planeX * cameraX; // frustum thingy float raydY = dirY + planeY * cameraX; unsigned char mapX = (char)posX; unsigned char mapY = (char)posY; float sdistX; float sdistY; float deltaX = fabsf(1/raydX); float deltaY = fabsf(1/raydY); float pWallDist; char stepX; char stepY; char side; //either 0 (NS), or 1 (EW) if(raydX &lt; 0) { stepX = -1; sdistX = (posX - mapX) * deltaX; // one side } else { stepX = 1; sdistX = (mapX + 1.0 - posX) * deltaX; // have to round the other way for this side. } if(raydY &lt; 0) { stepY = -1; sdistY = (posY - mapY) * deltaY; // one side } else { stepY = 1; sdistY = (mapY + 1.0 - posY) * deltaY; // have to round the other way for this side. } for( unsigned char step = 0; step &lt; 26; step +=1 ) { if(sdistX&lt;sdistY){ sdistX += deltaX; mapX += stepX; side = 0; } else { sdistY += deltaY; mapY += stepY; side = 1; } if(MAP[mapX][mapY] !=0) step = 27; } if(side == 0) pWallDist = (mapX - posX + (1-stepX) / 2) / raydX; else pWallDist = (mapY - posY + (1-stepY) / 2) / raydY; int lineHeight = (int)( RESY / pWallDist); signed int drawColour = 255-pWallDist*15; if(drawColour &lt; 0x11) drawColour = 0x11; SDL_SetRenderDrawColor( renderer, drawColour, drawColour, drawColour, 0xFF); rect.h = lineHeight*2; rect.y = (RESY/2 - lineHeight); SDL_RenderDrawRect( renderer, &amp;rect); } SDL_RenderPresent( renderer ); t2 = clock(); float ms = (float)(t2-t1)/1000.0; printf("%f\n", ms ); if(ms &lt; 16) SDL_Delay(16.0 - ms); } SDL_DestroyWindow( window ); SDL_Quit(); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T10:47:09.877", "Id": "455772", "Score": "1", "body": "Please **do not update** the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p><strong>Code:</strong></p>\n\n<pre><code>#include &lt;sys/time.h&gt;\n</code></pre>\n\n<p>Note that this isn't cross-platform. We can use <code>SDL_GetTicks()</code> instead.</p>\n\n<hr>\n\n<pre><code>const int RESX = 960;\nconst int RESY = 540;\nconst float ROTSPEED = 0.03;\nconst float MOVESPEED = 0.08;\nconst float STRAFEMOVESPEED = 0.05657;\nchar placeDist = 3;\n\nchar MAP[32][32] = {\n</code></pre>\n\n<p>I don't think any of these need to be globals. We could declare them in <code>main</code> instead. It might be worth grouping some of them into a <code>settings</code> struct.</p>\n\n<hr>\n\n<pre><code>char MAP[32][32]\n</code></pre>\n\n<p>We should use named variables, instead of magic numbers.</p>\n\n<hr>\n\n<pre><code> float posX = 3, posY = 4;\n float dirX = 1, dirY = 0; //direction vector\n float planeX = 0, planeY = 0.66; //camera plane\n</code></pre>\n\n<p>These aren't used until after we've initialized SDL, so we can (and should) declare them later.</p>\n\n<hr>\n\n<pre><code> if( SDL_Init( SDL_INIT_VIDEO ) &lt; 0 ) {\n printf( \"SDL could not initialize! SDL_Error: %s\\n\", SDL_GetError() );\n }\n</code></pre>\n\n<p>If we fail to initialize sdl, we probably shouldn't continue running the program! We could add a <code>return EXIT_FAILURE;</code> in there. The same problem exists with the window and renderer.</p>\n\n<p>It would be neater to move the SDL initialization into a separate function.</p>\n\n<hr>\n\n<pre><code> char running = 1;\n</code></pre>\n\n<p>We could use <code>&lt;stdbool.h&gt;</code> for this.</p>\n\n<hr>\n\n<pre><code> SDL_Rect rect;\n rect.w = 1;\n</code></pre>\n\n<p>This isn't used in the input handling, so it can be declared later.</p>\n\n<hr>\n\n<pre><code> float oldPlaneX, oldDirX;\n if(keystate[SDL_SCANCODE_RIGHT]) {\n oldDirX = dirX;\n dirX = dirX * cos(ROTSPEED) - dirY * sin(ROTSPEED);\n dirY = oldDirX * sin(ROTSPEED) + dirY * cos(ROTSPEED);\n oldPlaneX = planeX;\n planeX = planeX * cos(ROTSPEED) - planeY * sin(ROTSPEED);\n planeY = oldPlaneX * sin(ROTSPEED) + planeY * cos(ROTSPEED);\n }\n if(keystate[SDL_SCANCODE_LEFT]) {\n oldDirX = dirX;\n dirX = dirX * cos(-ROTSPEED) - dirY * sin(-ROTSPEED);\n dirY = oldDirX * sin(-ROTSPEED) + dirY * cos(-ROTSPEED);\n oldPlaneX = planeX;\n planeX = planeX * cos(-ROTSPEED) - planeY * sin(-ROTSPEED);\n planeY = oldPlaneX * sin(-ROTSPEED) + planeY * cos(-ROTSPEED);\n }\n</code></pre>\n\n<p>Yikes. We could really do with a <code>vec2</code> struct, and some math functions (<code>vec2_rotate</code>, <code>vec2_add</code>, <code>vec2_sub</code> etc.)</p>\n\n<p>It would be neater (and less repetitious) to apply the camera movement as a separate stage after getting the input. We just need to set a variable to <code>+1.f</code> when the right key is pressed, and <code>-1.f</code> when the left key is pressed. Then we multiply the <code>ROTSPEED</code> by this variable. e.g.:</p>\n\n<pre><code>struct vec2 {\n float x, y;\n};\n\nstruct vec2 vec2_rotate(struct vec2 v, float angle) {\n struct vec2 out;\n out.x = v.x * cos(angle) - v.y * sin(angle);\n out.y = v.x * sin(angle) + v.y * cos(angle);\n return out;\n}\n\n...\n\n float rotation = 0.f;\n if (keystate[SDL_SCANCODE_RIGHT]) rotation += +1.f;\n if (keystate[SDL_SCANCODE_LEFT]) rotation += -1.f;\n\n if (rotation != 0.f) {\n float angle = rotation * ROTSPEED;\n dir = vec2_rotate(dir, angle);\n plane = vec2_rotate(plane, angle);\n }\n</code></pre>\n\n<p>We can do a similar thing for the other movement inputs.</p>\n\n<hr>\n\n<p>Note that we need to take into account the frame-rate when applying the movement in order to be completely consistent with the speed at which the camera moves. <a href=\"https://gafferongames.com/post/fix_your_timestep/\" rel=\"nofollow noreferrer\">We might need to use an accumulator or something similar.</a></p>\n\n<hr>\n\n<pre><code> for (unsigned char step = 0; step &lt; 26; step += 1) {\n ...\n if (MAP[mapX][mapY] != 0) step = 27;\n }\n</code></pre>\n\n<p><code>26</code> deserves a variable name. We should also use <code>break;</code> to escape the loop instead of changing the loop variable (it won't stop working if we change the number of steps, or the loop condition).</p>\n\n<hr>\n\n<p>The raycasting code should really be moved into a separate function returning the distance.</p>\n\n<p>It would be a good idea to handle maps that aren't bounded by walls (we'd need to check that we don't step out of bounds).</p>\n\n<hr>\n\n<p><strong>Performance:</strong></p>\n\n<p>The ray-casting code is already very fast. Drawing to the screen and calling <code>SDL_RenderPresent</code> takes the most time, and there's probably not a lot we can do about that.</p>\n\n<p>Note that <code>SDL_RenderDrawRect</code> is actually for outlining rectangles, so it draws multiple lines internally. So technically we should be using <code>SDL_RenderFillRect</code> instead, though it doesn't seem to make much of a difference in performance.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T13:05:54.540", "Id": "233192", "ParentId": "233147", "Score": "4" } }, { "body": "<p>In all, this code is not bad, but there are some ways I think it might be improved.</p>\n\n<h2>Fix the bug</h2>\n\n<p>If the user hits the <kbd>space</kbd> key, it fills in a block and a left <kbd>cntl</kbd> removes it. Unfortunately, although the arena is fenced when the program starts, the user is not prevented from removing the fence blocks and wandering outside the allocated memory. This, of course, is a serious bug that should be addressed.</p>\n\n<h2>Decompose your program into functions</h2>\n\n<p>All of the logic here is in <code>main</code> in one rather long and dense chunk of code. It would be better to decompose this into separate functions.</p>\n\n<h2>Use <code>&lt;stdbool.h&gt;</code> for boolean types</h2>\n\n<p>The <code>running</code> variable is used as a boolean value, but is declared as a <code>char</code>. It would be clearer to readers of the code if instead of this:</p>\n\n<pre><code>char running = 1;\nwhile( running == 1 ) {\n</code></pre>\n\n<p>write this:</p>\n\n<pre><code>for (bool running = true; running; ) {\n</code></pre>\n\n<h2>Prefer logical evaluation to <code>if</code></h2>\n\n<p>The code contains these lines:</p>\n\n<pre><code>if( SDL_PollEvent( &amp;e ) &gt; 0) {\n if( e.type == SDL_QUIT) running = 0;\n}\n</code></pre>\n\n<p>Especially in combination with the suggestion above, I think this would be more clearly expressed like this:</p>\n\n<pre><code>running = !( SDL_PollEvent( &amp;e ) &gt; 0 &amp;&amp; e.type == SDL_QUIT);\n</code></pre>\n\n<h2>Write portable code where practical</h2>\n\n<p>The code uses <code>#include &lt;sys/time.h&gt;</code> and has these lines:</p>\n\n<pre><code>t2 = clock();\nfloat ms = (float)(t2-t1)/1000.0;\nprintf(\"%f\\n\", ms );\nif(ms &lt; 16) SDL_Delay(16.0 - ms);\n</code></pre>\n\n<p>This is not portable code. First, the standard location is <code>&lt;time.h&gt;</code> (no <code>sys</code>). Second, this assumes that <code>clock()</code> is measuring in seconds, but that's not actually required by the C standard. Instead, to get milliseconds, one could write this:</p>\n\n<pre><code>t2 = clock();\nfloat ms = (float)(t2-t1)/CLOCKS_PER_SEC*1000.0;\nprintf(\"%f\\n\", ms );\nif(ms &lt; 16) SDL_Delay(16.0 - ms);\n</code></pre>\n\n<p>Note, however, <code>SDL_Delay</code> is not that fine-grained and may not be doing what you intend. See <a href=\"https://gamedev.stackexchange.com/questions/97532/how-do-i-implement-a-fixed-delta-time-step-with-a-sdl-delay15ms-precision\">this game-dev answer</a> for details.</p>\n\n<h2>Be careful with signed vs. unsigned</h2>\n\n<p>In C, array access via subscripting is done with <em>unsigned</em> integer subscripts, but this code casts the subscript to <code>char</code> in many places. That's a potential problem because <code>char</code> is <em>signed</em> for some compilers. Better would be to use a <a href=\"https://en.cppreference.com/w/c/types/size_t\" rel=\"nofollow noreferrer\"><code>size_t</code></a> type.</p>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>There are a few numbers in the code, such as <code>0x11</code> and <code>16</code> and <code>27</code> that have a specific meaning in their particular context. By using named constants such as <code>wall_color</code> or <code>ms_per_loop</code>, the program becomes easier to read, understand and maintain. </p>\n\n<h2>Use an appropriate data structure</h2>\n\n<p>The code is full of separate lines that separately update an <span class=\"math-container\">\\$x\\$</span> and <span class=\"math-container\">\\$y\\$</span> coordinate. What would make the code simpler to read, understand and maintain, would be to create and use a structure for both like this:</p>\n\n<pre><code>typedef struct {\n float x;\n float y;\n} Point2D;\n\n\nvoid rotate(Point2D* p, float rotangle) {\n float oldX = p-&gt;x;\n p-&gt;x = p-&gt;x * cos(rotangle) - p-&gt;y * sin(rotangle);\n p-&gt;y = oldX * sin(rotangle) + p-&gt;y * cos(rotangle);\n}\n</code></pre>\n\n<p>This enables changing this:</p>\n\n<pre><code> if(keystate[SDL_SCANCODE_RIGHT]) {\n oldDirX = dirX;\n dirX = dirX * cos(ROTSPEED) - dirY * sin(ROTSPEED);\n dirY = oldDirX * sin(ROTSPEED) + dirY * cos(ROTSPEED);\n oldPlaneX = planeX;\n planeX = planeX * cos(ROTSPEED) - planeY * sin(ROTSPEED);\n planeY = oldPlaneX * sin(ROTSPEED) + planeY * cos(ROTSPEED);\n }\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code> if(keystate[SDL_SCANCODE_RIGHT]) {\n rotate(&amp;dir, ROTSPEED);\n rotate(&amp;plane, ROTSPEED);\n }\n</code></pre>\n\n<h2>Eliminate unused variables</h2>\n\n<p>Unused variables are a sign of poor code quality, so eliminating them should be a priority. In this code, <code>surface</code>, <code>oldtime</code> and <code>time</code> are unused. My compiler also tells me that. Your compiler is probably also smart enough to tell you that, if you ask it to do so. </p>\n\n<h2>Eliminate global variables where practical</h2>\n\n<p>The code declares and uses a number of global variables. Global variables obfuscate the actual dependencies within code and make maintainance and understanding of the code that much more difficult. It also makes the code harder to reuse. For all of these reasons, it's generally far preferable to eliminate global variables and to instead pass pointers to them. That way the linkage is explicit and may be altered more easily if needed. It may also be handy to collect such variables into structures.</p>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>The movement operations all include a lot of very similar repeated code. Instead of repeating code, it's generally better to make common code into a function. In this case, I'd replace the lengthy and repetitive code that handles the <kbd>D</kbd>, <kbd>A</kbd>, <kbd>W</kbd> and <kbd>S</kbd> keys with this:</p>\n\n<pre><code>float velocity = ((keystate[SDL_SCANCODE_D] ^ keystate[SDL_SCANCODE_A]) &amp;&amp;\n (keystate[SDL_SCANCODE_W] ^ keystate[SDL_SCANCODE_S])) ? STRAFEMOVESPEED : MOVESPEED;\nPoint2D oldpos = pos;\nif(keystate[SDL_SCANCODE_D]) {\n pos.x -= dir.y * velocity;\n pos.y += dir.x * velocity;\n}\nif(keystate[SDL_SCANCODE_A]) {\n pos.x += dir.y * velocity;\n pos.y -= dir.x * velocity;\n}\nif(keystate[SDL_SCANCODE_W]) {\n pos.x += dir.x * velocity;\n pos.y += dir.y * velocity;\n} \nif(keystate[SDL_SCANCODE_S]) {\n pos.x -= dir.x * velocity;\n pos.y -= dir.y * velocity;\n} \nadjustCollision(&amp;pos, &amp;oldpos, map);\n</code></pre>\n\n<p>This assumes that <code>pos</code> and <code>dir</code> are <code>Point2D</code> structures as mentioned above and that the <code>adjustCollision</code> function will prevent moving in a direction that is blocked by a wall.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T17:58:07.583", "Id": "233204", "ParentId": "233147", "Score": "3" } }, { "body": "<p>Math related review.</p>\n\n<p>Rather than use <code>double</code> functions, <code>float</code> functions make more sense for speed.</p>\n\n<pre><code>// dir.x = dir.x * cos(rotspeed) - dir.y * sin(rotspeed);\ndir.x = dir.x * cosf(rotspeed) - dir.y * sinf(rotspeed);\n// same for the remaining function.\n</code></pre>\n\n<p><strong>or</strong> if precision is important, consider changing all <code>float</code> objects to <code>double</code>.</p>\n\n<hr>\n\n<p>Likewise, rather than use <code>double</code> constants (which cause the computation to occur as <code>double</code>), use <code>float</code> constants. <em>Many</em> locations.</p>\n\n<pre><code>// sdistX = (map.x + 1.0 - pos.x) * deltaX\nsdistX = (map.x + 1.0f - pos.x) * deltaX\n</code></pre>\n\n<hr>\n\n<p><code>char</code> is a poor type to use for variables/casts involved in math computation here. It incurs twice the testing needed to see if it works as an <em>unsigned char</em> or <em>signed char</em>. Use <code>signed char</code> or <code>unsigned char</code>. Save <code>char</code> for text processing, not math.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T09:17:07.483", "Id": "233220", "ParentId": "233147", "Score": "1" } } ]
{ "AcceptedAnswerId": "233192", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T08:09:03.740", "Id": "233147", "Score": "6", "Tags": [ "performance", "c", "raycasting" ], "Title": "Optimizing a raycaster" }
233147
<p>I am fairly new into asp.net MVC c# I am working on request holiday app where an employee can request holidays. The problem is the app works fine, however, I am trying to set 8 hours a day when an employee requests a holiday I have scratching my head from 2 days already seen every topic in StackOverflow and here and still can't get to work if anyone has any suggestions it will be much appreciated. Here is a snippet of the calculation of the working days excluding weekends. Thank you in advance.</p> <pre><code> public static class DateHelpers { public static int DaysBetweenExcludingWeekends(DateTime startDate, DateTime endDate) { var days = 0; while (startDate &lt;= endDate) { if (startDate.DayOfWeek != DayOfWeek.Saturday &amp;&amp; startDate.DayOfWeek != DayOfWeek.Sunday) { days++; } startDate = startDate.AddDays(1); } return days; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T14:27:36.637", "Id": "455662", "Score": "0", "body": "Hello beetle_juice. Sadly CodeReview is for *working* code. Since your code has a problem, it's off-topic.. When your code works, please come back and we'll help you make it better :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T14:35:37.720", "Id": "455664", "Score": "0", "body": "Hi IEatBagels, my code works perfect, probably its badly asked question as I apologize for that, I just wanted to set the working hours to8 hours a day as at the moment when you request holiday by default are 24h.Also, I have done it somehow here is the snippet if (model.FromDate == model.ToDate)\n {\n model.FromDate = model.FromDate.AddHours(8);\n model.ToDate = model.ToDate.AddHours(16);\n }" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T14:36:27.357", "Id": "455665", "Score": "0", "body": "The problem is its working only when you request 1 day If request more than 1 day it's calculating 24hour day :)" } ]
[ { "body": "<p>You can throw an error if someone is trying to set a work day to a day that should be a day off. Then you just need to handle this error.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T13:28:04.877", "Id": "233159", "ParentId": "233153", "Score": "0" } } ]
{ "AcceptedAnswerId": "233159", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T10:08:15.453", "Id": "233153", "Score": "0", "Tags": [ "asp.net-mvc" ], "Title": "Calculate 8 hours business day in a weekdays only" }
233153
<p>I'm trying to process numerical input arguments for a function. Users can mix ints, floats, and "array-like" things of ints and float, as long as they are all length=1 or the same length>1.</p> <p>Now I convert them as follows:</p> <pre><code>convert to float convert to np.ndarray; dtype==float ---------------- ----------------------------------- float int np.float64 range object resulting in len == 1 range object resulting in len &gt; 1 len==1 list or tuple of int or float len &gt; 1 list or tuple of ints &amp; floats len==1 np.ndarray of dtype np.int or np.float len &gt; 1 np.ndarray of dtype np.int or np.float </code></pre> <p>then test all resulting arrays to make sure they are the same length. If so, I return a list containing floats and arrays. If not, return <code>None</code>.</p> <p>I want to avoid up-conversion of booleans and small byte-length ints.</p> <p>The script below appears to do what I want by brute force testing, but I wonder if there is a better way?</p> <hr> <p>Desired behaviors:</p> <ul> <li><p><code>fixem(some_bad_things)</code> returns <code>None</code></p></li> <li><p><code>fixem(all_good_things)</code> returns <code>[42.0, 3.14, 3.141592653589793, 2.718281828459045, 3.0, 42.0, 3.0, 42.0, array([1. , 2.3, 2. ]), array([3.14, 1. , 4. ]), array([1., 2., 2.]), array([3., 1., 4.]), array([0., 1., 2.]), array([0, 1, 2])]</code></p></li> <li><p>and <code>sum(fixem(all_good_things))</code> returns <code>array([149.13987448 149.29987448 156.99987448])</code></p></li> </ul> <hr> <pre><code>def fixit(x): result = None if type(x) in (int, float, np.float64): result = float(x) elif type(x) == range: y = list(x) if all([type(q) in (int, float) for q in y]): if len(y) == 1: result = float(y[0]) elif len(y) &gt; 1: result = np.array(y) elif type(x) in (tuple, list) and all([type(q) in (int, float) for q in x]): y = np.array(x) if y.dtype in (int, float): if len(y) == 1: result = float(y[0]) elif len(y) &gt; 1: result = y.astype(float) elif (type(x) == np.ndarray and len(x.shape) == 1 and x.dtype in (np.int, np.float)): if len(x) == 1: result = float(x[0]) elif len(x) &gt; 1: result = x.astype(float) return result def fixem(things): final = None results = [fixit(thing) for thing in things] floats = [r for r in results if type(r) is float] arrays = [r for r in results if type(r) is np.ndarray] others = [r for r in results if type(r) not in (float, np.ndarray)] if len(others) == 0: if len(arrays) == 0 or len(set([len(a) for a in arrays]))==1: # none or all same length final = floats + arrays return final import numpy as np some_bad_things = ('123', False, None, True, 42, 3.14, np.pi, np.exp(1), [1, 2.3, 2], (3.14, 1, 4), [1, 2, 2], (3, 1, 4), (3,), [42], (3.,), [42.], np.array([True, False]), np.array([False]), np.array(False), np.array('xyz'), np.array(42), np.array(42.), np.arange(3.), range(3)) all_good_things = (42, 3.14, np.pi, np.exp(1), [1, 2.3, 2], (3.14, 1, 4), [1, 2, 2], (3, 1, 4), (3,), [42], (3.,), [42.], np.arange(3.), range(3)) for i, things in enumerate((some_bad_things, all_good_things)): print(i, fixem(things)) print(sum(fixem(all_good_things))) # confirm </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T13:26:29.820", "Id": "455652", "Score": "0", "body": "I'm curious, where does this problem come from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T13:45:11.103", "Id": "455655", "Score": "0", "body": "@Georgy I don't understand exactly how to answer your question. I'm writing a script for others to use that will do a calculation based on numerical input. If they are all floats, it will perform a calculation and return one object; if one or more are array-like, it returns a collection of them." } ]
[ { "body": "<ol>\n<li><p>I suggest using <code>isinstance</code> instead of <code>type</code> to check the types of variables. You can read about it in details here: <a href=\"https://stackoverflow.com/q/1549801/7851470\">What are the differences between type() and isinstance()?</a>\nSo, for example, instead of writing:</p>\n\n<pre><code>if type(x) in (int, float, np.float64):\n</code></pre>\n\n<p>you would write:</p>\n\n<pre><code>if isinstance(x, (int, float)):\n</code></pre>\n\n<p>You can check that it works for <code>np.exp(1)</code> which is of type <code>np.float64</code>.</p></li>\n<li><p>When the <code>x</code> is of type <code>range</code> the following check is redundant: </p>\n\n<pre><code>if all([type(q) in (int, float) for q in y])\n</code></pre>\n\n<p>as the elements of <code>y</code> will be always integers. Also, there is no need to convert <code>range</code> to <code>list</code>. The following will also work:</p>\n\n<pre><code>result = float(x[0]) if len(x) == 1 else np.array(x)\n</code></pre></li>\n<li><p>To check if a list is empty in Python we usually write:</p>\n\n<pre><code>if not others:\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>if len(others) == 0:\n</code></pre></li>\n<li><p>Imports should be at the top of the script. Move the <code>import numpy as np</code> line there.</p></li>\n<li><p>In the future, when you have a function that can accept variables of different types and its behavior depends on which type it gets, you could try using <a href=\"https://docs.python.org/3.6/library/functools.html#functools.singledispatch\" rel=\"nofollow noreferrer\"><code>singledispatch</code></a>. I could come up with the following implementation:</p>\n\n<pre><code>from collections.abc import Iterable\nfrom functools import singledispatch\nfrom numbers import Real\n\nimport numpy as np\n\n\n@singledispatch\ndef fixit(x):\n return None\n\n@fixit.register\ndef _(x: Real):\n return float(x)\n\n\n@fixit.register\ndef _(x: Iterable):\n y = np.array(x)\n if y.dtype in (np.int, np.float) and len(y.shape) == 1:\n return float(y[0]) if len(y) == 1 else y.astype(float)\n else:\n return None\n</code></pre>\n\n<p>I didn't check it thoroughly but for your test cases it works. (but looks a bit ugly)</p></li>\n<li><p>A better way to solve your problem would be to convert immediately all the values to NumPy arrays of at least one dimension. We would require a <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.atleast_1d.html\" rel=\"nofollow noreferrer\"><code>np.atleast_1d</code></a> function for that:</p>\n\n<pre><code>def to_normalized_data(values):\n arrays = list(map(np.atleast_1d, values))\n sizes = set(map(np.size, arrays))\n has_bad_types = any(array.dtype not in (np.int32, np.float64) for array in arrays)\n if len(sizes) &gt; 2 or has_bad_types:\n return None\n max_size = max(sizes)\n singletons = [float(array[0]) for array in arrays if array.size == 1]\n iterables = [array.astype(float) for array in arrays if array.size == max_size]\n return singletons + iterables\n</code></pre>\n\n<pre><code>&gt;&gt;&gt; to_normalized_data(all_good_things)\n[42.0,\n 3.14,\n 3.141592653589793,\n 2.718281828459045,\n 3.0,\n 42.0,\n 3.0,\n 42.0,\n array([1. , 2.3, 2. ]),\n array([3.14, 1. , 4. ]),\n array([1., 2., 2.]),\n array([3., 1., 4.]),\n array([0., 1., 2.]),\n array([0., 1., 2.])]\n&gt;&gt;&gt; sum(to_normalized_data(all_good_things))\narray([149.13987448, 149.29987448, 156.99987448])\n&gt;&gt;&gt; print(to_normalized_data(some_bad_things))\nNone\n</code></pre></li>\n</ol>\n\n<hr>\n\n<p><strong>Answering your comments:</strong> </p>\n\n<ol>\n<li><blockquote>\n <p>For some reason my anaconda's numpy (1.17.3) returns int64 rather than\n int32 as you have in item 6</p>\n</blockquote>\n\n<p>Looks like this behavior is <a href=\"https://stackoverflow.com/q/36278590/7851470\">OS-specific</a>. Probably a better way to check the types of the obtained arrays would be by using <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.can_cast.html\" rel=\"nofollow noreferrer\"><code>np.can_cast</code></a>. So, instead of writing:</p>\n\n<pre><code>has_bad_types = any(array.dtype not in (np.int32, np.float64) for array in arrays)\n</code></pre>\n\n<p>we could write:</p>\n\n<pre><code>has_bad_types = not all(np.can_cast(array.dtype, np.float64) for array in arrays)\n</code></pre></li>\n<li><blockquote>\n <p>Item #6 doesn't reject two different lengths if no singletons are present. With <code>([1, 2, 3], [1, 2, 3, 4])</code> as input, the output is <code>[array([1., 2., 3., 4.])]</code> and <code>[1, 2, 3]</code> just falls through the cracks and disappears</p>\n</blockquote>\n\n<p>Welp, I missed this case... We can add it back as:</p>\n\n<pre><code>if len(sizes) &gt; 2 or 1 not in sizes or has_bad_types:\n</code></pre></li>\n<li><blockquote>\n <p>also my original script tested if <code>len(x.shape) == 1</code> in order to reject ndm > 1 arrays which item #6 doesn't, but that can be easily added back with something like testing for <code>set(map(np.ndim, arrays)) == set((1,))</code>. This is important because <code>np.size</code> won't distinguish between a length=4 1D array and a 2x2 array.</p>\n</blockquote>\n\n<p>Yep, that's right. Taking all the above into account, the final code could look like this:</p>\n\n<pre><code>def to_normalized_data(values):\n arrays = list(map(np.atleast_1d, values))\n sizes = set(map(np.size, arrays))\n have_bad_types = not all(np.can_cast(array.dtype, np.float64) for array in arrays)\n have_several_dimensions = set(map(np.ndim, arrays)) &gt; {1}\n if len(sizes) &gt; 2 or 1 not in sizes or have_bad_types or have_several_dimensions:\n return None\n max_size = max(sizes)\n singletons = [float(array[0]) for array in arrays if array.size == 1]\n iterables = [array.astype(float) for array in arrays if array.size == max_size]\n return singletons + iterables\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T09:19:30.783", "Id": "455999", "Score": "0", "body": "fyi I've just asked [Managing user defined and default values for instance attributes](https://codereview.stackexchange.com/q/233319/145009)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T11:14:11.760", "Id": "456009", "Score": "1", "body": "Bingo! Excellent, thank you for your time and effort!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:56:54.520", "Id": "233169", "ParentId": "233156", "Score": "6" } } ]
{ "AcceptedAnswerId": "233169", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T11:42:22.673", "Id": "233156", "Score": "5", "Tags": [ "python", "python-3.x", "numpy", "converting" ], "Title": "process numerical input arguments of mixed ints, floats, and \"array-like\" things of same length>1" }
233156
<p>Review on this draft please: clang-8 -std=c++17</p> <p>Simple wrapper class template for std::map &amp; std::list (or alternatively std:unordered_map &amp; std::vector) for the purpose of "retaining insertion order". This is quite a frequently asked question, eg </p> <p><a href="https://stackoverflow.com/questions/2266179/c-stl-map-i-dont-want-it-to-sort/2267198">https://stackoverflow.com/questions/2266179/c-stl-map-i-dont-want-it-to-sort/2267198</a></p> <p><a href="https://stackoverflow.com/questions/35053544/keep-the-order-of-unordered-map-as-we-insert-a-new-key/59100306#59100306">https://stackoverflow.com/questions/35053544/keep-the-order-of-unordered-map-as-we-insert-a-new-key/59100306#59100306</a></p> <p>And the only answers are <a href="https://www.boost.org/doc/libs/1_71_0/libs/multi_index/doc/index.html" rel="nofollow noreferrer">"Boost::multi_index"</a> or "roll your own with (unordered_)map + list|vector". The very slimline class template below attempts to put some structure to the latter for those who don't want to or can't include a huge sledgehammer. </p> <p>A couple of utility print function templates and some simple use cases are included for illustration only. There are a couple of questions in the comments regarding a clean way to expose the iterators. And, more generally, how to expose the API of the private list/map containers to the public interface in a controlled way without writing wrappers for every function overload:</p> <p>Same code as below <a href="https://godbolt.org/z/Mtgcxk" rel="nofollow noreferrer">on goldbolt</a>: </p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;list&gt; #include &lt;map&gt; #include &lt;random&gt; #include &lt;string&gt; #include &lt;vector&gt; template &lt;class KeyT, class ValueT&gt; class SequencedMap { using MapT = std::map&lt;KeyT, ValueT&gt;; using MapItT = typename MapT::iterator; using OrderValT = typename MapT::value_type*; using OrderT = std::list&lt;OrderValT&gt;; using OrderItT = typename OrderT::iterator; public: std::pair&lt;MapItT, bool&gt; insert_or_assign(const KeyT&amp; key, const ValueT&amp; value) { auto ins_res = map.insert_or_assign(key, value); auto [elem_it, was_new] = ins_res; if (was_new) order.push_back(&amp;*elem_it); return ins_res; } MapItT find(const KeyT&amp; key) const { return map.find(key); } ValueT&amp; operator[](const KeyT&amp; key) { // keep it simple. read or modify only. Not create! auto map_it = map.find(key); if (map_it == map.end()) throw std::logic_error( "Warning! You are trying to create a SequencedMap entry using [] operator. Use " "insert_or_assign for safety!"); return map_it-&gt;second; } OrderItT erase(const KeyT&amp; key) { auto map_it = map.find(key); if (map_it == map.end()) return order.end(); auto order_erased_it = order.erase(std::find(order.begin(), order.end(), &amp;*map_it)); map.erase(map_it); return order_erased_it; } // exposing the internal containers is not great, but need a clean way to expose their iterators // without too much code bloat. Preferable transparently change the MapT::value_type* to // MapT::value_type const MapT&amp; getMap() const { return map; } const OrderT&amp; getOrder() const { return order; } private: MapT map; OrderT order; }; // EOF class: Rest is demo usage code template &lt;class KeyT, class ValueT&gt; void print_in_insertion_order(const SequencedMap&lt;KeyT, ValueT&gt;&amp; smap) { for (auto&amp; pair_ptr: smap.getOrder()) { std::cout &lt;&lt; pair_ptr-&gt;first &lt;&lt; " -&gt; " &lt;&lt; pair_ptr-&gt;second &lt;&lt; "\n"; } } template &lt;class KeyT, class ValueT&gt; void print_in_map_order(const SequencedMap&lt;KeyT, ValueT&gt;&amp; smap) { for (auto&amp; pair: smap.getMap()) { std::cout &lt;&lt; pair.first &lt;&lt; " -&gt; " &lt;&lt; pair.second &lt;&lt; "\n"; } } int main() { using Key = std::string; using Value = int; SequencedMap&lt;Key, Value&gt; smap; // arbitrary ad-hoc temporary structure for the data (for demo purposes only) std::cout &lt;&lt; "insert data...\n"; for (auto p: std::vector&lt;std::pair&lt;Key, Value&gt;&gt;{ {"Mary", 10}, {"Alex", 20}, {"Johnny", 30}, {"Roman", 40}, {"Johnny", 50}}) { smap.insert_or_assign(p.first, p.second); } print_in_insertion_order(smap); std::cout &lt;&lt; "\nsorted by key\n"; print_in_map_order(smap); std::cout &lt;&lt; "\nretrieve by known key\n"; auto key = "Alex"; std::cout &lt;&lt; key &lt;&lt; " -&gt; " &lt;&lt; smap["Alex"] &lt;&lt; "\n"; std::cout &lt;&lt; "\nchange value by known key: Johnny++\n"; ++smap["Johnny"]; print_in_insertion_order(smap); std::cout &lt;&lt; "\ndelete by known key: Johnny\n"; smap.erase("Johnny"); print_in_insertion_order(smap); } </code></pre> <p>Done a really simple benchmark:</p> <pre><code>Bench SequencedMap: insert 100,000=252.06ms SequencedMap: iterate in insertion order=1.47723ms SequencedMap: modify 100,000 in insertion order=103.497ms SequencedMap: delete 10,000=7513.77ms Map: insert 100,000=227.629ms Map: iterate in map order=6.91042ms Map: modify 100,000 in map order=90.8201ms Map: delete 10,000=16.7736ms </code></pre> <p>All looks very reasonable, but we have a <strong>problem on delete</strong>, as I expected. Finding the pointer is a linear operation each time. So O(n^2) for the 10,000 deletions. Not sure how to solve that, except to make the datastructure more complicated. Eg a reverse pointer from the map entry back to the list. Feels like pointer spaghetti then. </p> <p>So, maybe a different idea: Ditch the std::list altogether, and instead of <code>std::map&lt;KeyT,ValueT&gt;</code> we use a <code>std::map&lt;KeyT,ValuePkgT&gt;</code> where:</p> <pre><code>struct ValuePkgT { ValueT value; next MapT::value_type*; // recursive type reference here? } </code></pre> <p>In other words the map value contains a struct which makes a "simple linked list" out of the map elements. Then we could have SeqeuencedMap actually inherit from std::map (is that bad?) publish a second set of iterators...eg SequencedMap::ibegin()/iend() (i=insertion_order) which use the internal linked list to iterate? </p> <p>Opinions? Problems? Wise to extend std::map?</p> <p><strong>EDIT</strong>: I have pursued these new ideas in another question, here:</p> <p><a href="https://codereview.stackexchange.com/questions/233177/sequencedmap-which-retains-insertion-order-mkii">SequencedMap which retains insertion order - MKII</a></p>
[]
[ { "body": "<h2>Reduce Lookups</h2>\n<p><code>ValueT&amp; operator[](KeyT key)</code> does 2 lookups, one in <code>map.count(key)</code> and one in <code>map[key]</code>. Using <code>map.find(key)</code> and then comparing the iterator against <code>std::end(map)</code> and then dereferencing it to return the value avoids that.</p>\n<h2>Consistent Parameter Types</h2>\n<p><code>ValueT&amp; operator[](KeyT key)</code> takes <code>KeyT</code> by value while other functions use <code>const KeyT &amp;</code>. There doesn't seem to be a reason for that and you should be consistent.</p>\n<h1>Support Move-Only Types</h1>\n<p>Take inspiration from the standard. All versions of <code>std::map::insert_or_assign</code> take a <code>ValueT &amp;&amp;</code> while you take a <code>const ValueT &amp;</code>. That means unlike the standard containers you do not support <code>std::unique_ptr</code> for example. I don't see anything else that is holding it back, so it's an easy improvement for minimal effort.</p>\n<h2>Bonus: Use All The New Cool Features</h2>\n<p>(this one is not entirely serious)<br />\nIn <code>insert_or_assign</code></p>\n<pre class=\"lang-cpp prettyprint-override\"><code> auto [elem_it, was_new] = ins_res;\n if (was_new) order.push_back(&amp;*elem_it);\n</code></pre>\n<p>can be written as</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> if (auto [elem_it, was_new] = ins_res; was_new) {\n order.push_back(&amp;*elem_it);\n }\n</code></pre>\n<p>I'm not sure it's better, but it's fancier. In theory it's better because it limits the scope of <code>elem_it</code> and <code>was_new</code>, but in practice in this case it just doesn't matter.</p>\n<h2>Nitpicking</h2>\n<p>Some of your variables can be <code>const</code> such as <code>ins_res</code> and <code>map_it</code>.</p>\n<h2>Extensions</h2>\n<p>You seem to want to keep it simple, so take these as suggestions of what could be done, not necessarily as part of the code review.</p>\n<h3>Transparent Comparators</h3>\n<p>It would be cool if you supported lookups that don't require to create a <code>KeyT</code>. For example <code>++smap[&quot;Johnny&quot;];</code> unnecessarily creates a temporary <code>std::string</code>. <code>std::string</code> can compare to <code>const char *</code> already. See <a href=\"https://stackoverflow.com/questions/20317413/what-are-transparent-comparators\">transparent comparators</a> and <a href=\"https://en.cppreference.com/w/cpp/container/map/find\" rel=\"noreferrer\"><code>std::map::find</code></a> for inspiration.</p>\n<h3>A Real Container</h3>\n<p>Maybe you could make <code>SequencedMap</code> <a href=\"https://en.cppreference.com/w/cpp/named_req/Container\" rel=\"noreferrer\">a real container</a> which then allows its use in all the standard algorithms.</p>\n<h2>When In Doubt Use <code>std::vector</code></h2>\n<p>It's a good default container unless benchmarks show you need something else. <code>std::list</code> is legendary for its terrible performance in almost all circumstances, even the ones that sound like they should be faster such as removing an element from the middle.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:14:31.780", "Id": "455668", "Score": "0", "body": "Many thanks. I will consider more carefully/ We were typing at same time. Can you have a look at benchmark - exposing the obvious delete/erase problem and the give some feedback on the idea of extending std::map and using the internal linked list?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:33:18.907", "Id": "455674", "Score": "0", "body": "I did the first 2. There were obvious improvements which I just missed. Removing the double loopup (which I was already doing during erase) sped up operator[] by 2x, obviously. Code and bench updated above.\n\nStruggling with Move-only types. changing signature to `ValueT&& value` gives: `rvalue reference to type 'int' cannot bind to lvalue of type 'int`, and if I use `std::forward<ValueT>(value)` in the call below it doesn't get better: same error.\n\nNot sure how to make that work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:43:13.780", "Id": "455676", "Score": "0", "body": "is the idea of extending std::map bad?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T16:16:41.210", "Id": "455677", "Score": "0", "body": "I sorted the universal references for the move values. The my insert_or_assign mthods needs its own template header like this:\n\n`template <class K, class V> std::pair<MapItT, bool> insert_or_assign(const K& key, V&& value) { const auto ins_res = map.insert_or_assign(key, std::forward<V>(value)); `\n\nIt can't rely on those types being templated at class level apparently for those params to be universal references." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:22:06.803", "Id": "455699", "Score": "0", "body": "I am going to go ahead and accept this answer. It was really helpful feedback for me, and I did all those things. Well, all except the more architectural stuff, because I had the above idea of a different datastructure which might solve delete performance and be less messy overall. \n\nI have finished my first draft of that solution, but will post this as a separate review questions.\n\nMany Thx! @nwp" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:04:35.900", "Id": "233166", "ParentId": "233157", "Score": "5" } } ]
{ "AcceptedAnswerId": "233166", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T11:50:48.023", "Id": "233157", "Score": "5", "Tags": [ "c++", "c++17", "template-meta-programming", "stl" ], "Title": "Wrapper class template for std::map + std::list to provide a SequencedMap which retains insertion order" }
233157
<p>I am retrieving a document(<code>UserDetails</code>) from <code>Couch</code> with a lock of 5 sec, than updating the document and saving it. Code is working, but I am not sure whether it will work in real time scenario <em>(in case of conflict)</em> or not. How to handle <code>TemporaryLockFailureException</code>? I also want feedback to refactor the method.</p> <pre><code>@Override public void submitUsersDetails(DashboardRequest request) { logger.debug("inside submitDashboardDetails"); CompletableFuture.runAsync(() -&gt; { try { bucket = cluster.openBucket(config.getString(PctConstants.COUCHBASE_BUCKET_NAME), config.getString(PctConstants.COUCHBASE_BUCKET_PASSWORD)); String documentID = PctConstants.USER_PROFILE; JsonDocument retrievedJsonDocument = bucket.getAndLock(documentID, 5); if (retrievedJsonDocument != null) { JsonNode json = Json.parse(retrievedJsonDocument.content().toString()); UserDetails userDetails = Json.fromJson(json, UserDetails.class); // UPDATING userDetails JsonObject jsonObject = JsonObject.fromJson(Json.toJson(userDetails).toString()); bucket.replace(JsonDocument.create(documentID, jsonObject, retrievedJsonDocument.cas())); logger.info("Successfully entered record into couchbase"); } else { logger.error("Fetching User_details unsuccessful"); throw new DataNotFoundException("User_details data not found"); } } catch (TemporaryLockFailureException e) { try { logger.debug("Inside lock failure **************************"); Thread.sleep(5000); String documentID = PctConstants.USER_PROFILE; JsonDocument retrievedJsonDocument = bucket.getAndLock(documentID, 5); if (retrievedJsonDocument != null) { JsonNode json = Json.parse(retrievedJsonDocument.content().toString()); UserDetails userDetails = Json.fromJson(json, UserDetails.class); // UPDATING userDetails JsonObject jsonObject = JsonObject.fromJson(Json.toJson(userDetails).toString()); bucket.replace(JsonDocument.create(documentID, jsonObject, retrievedJsonDocument.cas())); logger.info("Successfully entered record into couchbase"); submitDashboardDetails(request); } else { logger.error("Fetching User_details unsuccessful"); throw new DataNotFoundException("User_details data not found"); } } catch (InterruptedException e1) { e1.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); try { throw e; } catch (Exception e1) { e1.printStackTrace(); } } }, ec.current()).join(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T19:27:42.170", "Id": "455689", "Score": "1", "body": "\"How to handle `TemporaryLockFailureException`\" well, you're handling it at the moment, right? Is it not working the way it should? It helps to test it out in the real world *before* you get a review, so you know whether it works or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T19:29:10.810", "Id": "455690", "Score": "1", "body": "Can you clarify how this could would be used? How it's called? This can be of influence on how it should be refactored most efficiently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T19:39:00.620", "Id": "455691", "Score": "0", "body": "@Mast Yes exception handling works, I have copied the code from try block in catch block, I am not sure whether it's the correct way or not. So, wanted to get more input on that. This method is part of the DAO bean and getting called from the REST API controller." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T09:59:09.397", "Id": "455866", "Score": "0", "body": "Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T13:08:48.610", "Id": "233158", "Score": "1", "Tags": [ "java", "couchdb" ], "Title": "Playframework Java application with Couchbase database, retrieve and lock the document while saving" }
233158
<p>A <a href="https://en.wikipedia.org/wiki/Quine_(computing)" rel="noreferrer">quine</a> is a program whose only job it is to reproduce the source file that was used to create the executable in the first place.<br> This <a href="https://stackoverflow.com/questions/10367941/what-is-quine-meant-for?rq=1">stackoverflow post</a> provides some reasoning about its usefulness.<br> Below I present 5 different quines.</p> <h2>The nice quine</h2> <p>This program has an embedded copy of its complete source (minus that copy of course).<br> For simplicity I've substituted an asterisk for the carriage return and linefeed codes. I've also avoided the use of embedded dollar characters ($) and single quote characters (') because they would throw off the DOS PrintString function and the FASM parser respectively.</p> <pre class="lang-none prettyprint-override"><code> org 256 mov ah, 02h ; DOS.PrintChar mov si, text lodsb next: mov dl, al cmp al, 42 ; Asterisk -&gt; CRLF jne char mov dl, 13 int 21h mov dl, 10 char: int 21h lodsb cmp al, 36 ; Dollar jne next mov dl, 39 ; SingleQuote int 21h mov dx, text mov ah, 09h ; DOS.PrintString int 21h mov ah, 02h ; DOS.PrintChar mov dl, 36 ; Dollar int 21h mov dl, 39 ; SingleQuote int 21h mov dl, 13 ; CR int 21h mov dl, 10 ; LF int 21h mov ax, 4C00h ; DOS.Terminate int 21h text: db ' org 256** mov ah, 02h ; DOS.PrintChar* mov si, text* lodsb*next: mov dl, al* cmp al, 42 ; Asterisk -&gt; CRLF* jne char* mov dl, 13* int 21h* mov dl, 10*char: int 21h* lodsb* cmp al, 36 ; Dollar* jne next* mov dl, 39 ; SingleQuote* int 21h* mov dx, text* mov ah, 09h ; DOS.PrintString* int 21h* mov ah, 02h ; DOS.PrintChar* mov dl, 36 ; Dollar* int 21h* mov dl, 39 ; SingleQuote* int 21h* mov dl, 13 ; CR* int 21h* mov dl, 10 ; LF* int 21h* mov ax, 4C00h ; DOS.Terminate* int 21h**text: db $' </code></pre> <h2>Entering challenge mode, but not really participating one</h2> <h3>Q1 Short</h3> <p>It was this <a href="https://codegolf.stackexchange.com/questions/577/assembly-language-quine">codegolf post</a> that I found, that triggered me to investigate if I could write a very small quine.<br> I started by removing from the above program everything that wasn't crucial for it to be assembled correctly.</p> <ul> <li>I removed all of the indentation, the optional whitespace, and the tail comments.</li> <li>I chose the number representation that was shortest. e.g. <code>21h</code> becomes <code>33</code>.</li> <li>As long as there are no labels for which FASM has to know the origin, there's no need for this .COM program to start with an <code>ORG 256</code> directive.</li> <li>I stopped using labels. I wrote the address instead and because FASM at the time of compilation now thinks that the program runs at address 0 these are very short numbers.</li> <li>Instead of processing the text string in 2 different ways using 2 different DOS functions, I now traverse the string character by character and do it twice.</li> <li>I dismissed the carriage return and linefeed codes for the very last line of the program because FASM can do without them nicely.</li> <li>Provided the stack is untampered with, a .COM program can end with a mere <code>ret</code> instruction.</li> </ul> <pre class="lang-none prettyprint-override"><code>mov ah,2 mov dh,42 call 7 mov cx,150 mov si,292 mov dl,[si] inc si cmp dl,dh jne 26 mov dl,13 int 33 mov dl,10 int 33 loop 13 mov dx,39 int 33 ret db 'mov ah,2*mov dh,42*call 7*mov cx,150*mov si,292*mov dl,[si]*inc si*cmp dl,dh*jne 26*mov dl,13*int 33*mov dl,10*int 33*loop 13*mov dx,39*int 33*ret*db ' </code></pre> <h3>Q2 Shorter</h3> <p>At some point an assembly programmer might come up with the idea to assemble the program from a series of <code>db</code> directives. That's reminiscent of the old days when programmers punched-in numbers directly instead of using nice mnemonics.<br> I've tried several versions but I found the hexadecimal dump to be shorter than the decimal dump.<br> To mark the end of a line, FASM only requires the linefeed code. The carriage return code is optional and so I've left it out. Without the carriage returns everything in the file looks out of place on the screen. Considering what was shaved off, that ugliness was but a small price to pay.</p> <pre class="lang-none prettyprint-override"><code>db BEh db 00h db 01h db BAh db 22h db 01h db B9h db 2Ah db 00h db ACh db D4h db 10h db 3Ch db 0Ah db 1Ch db 69h db 2Fh db 86h db C4h db 3Ch db 0Ah db 1Ch db 69h db 2Fh db A3h db 25h db 01h db B4h db 09h db CDh db 21h db E2h db E8h db C3h db 64h db 62h db 20h db 32h db 32h db 68h db 0Ah db 24h </code></pre> <p>The equivalent program:</p> <pre class="lang-none prettyprint-override"><code>mov si,256 mov dx,290 mov cx,42 lodsb aam 16 cmp al,10 sbb al,69h das xchg al,ah cmp al,10 sbb al,69h das mov [293],ax mov ah,09h int 21h loop 9 ret db 'db 22h',10,'$' </code></pre> <h3>Q3 Again shorter (judged by source length)</h3> <p>I really should have put all of those numbers in a single <code>db</code>.<br> This time the decimal version proved to be the shorter one. And just for the fun of it, I've iterated it backwards. Efforts to remove the redundant leading zeroes amounted to a longer quine, so no.</p> <pre class="lang-none prettyprint-override"><code>db 191,219,001,190,043,001,186,041,001,185,044,000,176,036,253,170,172,212,010,004,048,170,136,224,212,010,005,048,048,170,136,224,170,184,044,009,226,233,205,033,195,100,098,032 </code></pre> <p>The equivalent program:</p> <pre class="lang-none prettyprint-override"><code>mov di,475 mov si,299 mov dx,297 mov cx,44 mov al,'$' std stosb lodsb aam add al,'0' stosb mov al,ah aam add ax,'00' stosb mov al,ah stosb mov ax,092Ch loop 15 int 21h ret db 'db ' </code></pre> <h3>Q4 Shortest</h3> <p>Still putting the whole program in a single <code>db</code>, but using a quote, thereby avoiding the need for a conversion routine.<br> This required a lot of puzzling but it worked and produced a quine of just 30 bytes. By carefully choosing the instructions, I could avoid using character codes that the editor would have trouble displaying. The Norton Editor chokes on character codes [0,31] and 255.</p> <pre class="lang-none prettyprint-override"><code>db '1Ҳ�׸NH��E"�db�� &amp;�ī����!�' </code></pre> <p>The character codes involved:</p> <blockquote class="spoiler"> <p> 31 D2 B2 FC 89 D7 B8 4E 48 D1 E8 89 45 22 B8 64 62 AB B8 20 26 FE C4 AB 80 C4 E2 CD 21 C3</p> </blockquote> <p>The equivalent program:</p> <pre class="lang-none prettyprint-override"><code>xor dx,dx mov dl,252 mov di,dx mov ax,487Eh shr ax,1 mov [di+34],ax mov ax,6264h stosw mov ax,2620h inc ah stosw add ah,226 int 21h ret </code></pre> <h2>Summary</h2> <p>Next table shows how the quines' sourcefiles gradually became smaller.</p> <pre class="lang-none prettyprint-override"><code> Q0 Q1 Q2 Q3 Q4 ------------------------------ .ASM 1837 319 294 178 35 .COM 960 186 42 44 30 </code></pre> <p>Every program was tested using FASM 1.0<sup>1</sup> in MS-DOS 6.20</p> <blockquote> <p>C:\FASM1>fasm q4.asm q4.com<br> flat assembler version 1.0<br> 1 passes, 30 bytes.</p> <p>C:\FASM1>q4 > q4_.asm</p> <p>C:\FASM1>fc q4.asm q4_.asm<br> Comparaison des fichiers en cours : Q4.ASM et Q4_.ASM<br> FC: aucune différence trouvée</p> </blockquote> <p><sup>1</sup><sub>In case you wonder why I use an old version of FASM. I'm checking out FASM 1.0 in preparation for <a href="https://board.flatassembler.net/topic.php?t=21201" rel="noreferrer">the upcoming celebration of the 20th anniversary of the first official release</a>.</sub></p> <h2>And finally</h2> <p>Because this is <strong>Code Review</strong>, you are invited to suggest any improvements that I can make to any or all of these 5 little programs.<br> I leave it up to you to decide if <em>a smaller quine</em> should refer to <em>a smaller source file</em> or to <em>a smaller executable file</em>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-20T16:30:02.490", "Id": "458414", "Score": "1", "body": "I've posted my revised code in [this follow-up question](https://codereview.stackexchange.com/questions/234396/a-progression-of-quines-follow-up)" } ]
[ { "body": "<p><a href=\"https://hg.ulukai.org/ecm/quine/file/eac01194cb9a/q.asm\" rel=\"nofollow noreferrer\">My equivalent</a> to your nice quine is a bit nicer, and differs in other ways.</p>\n\n<p>It is nicer in that the payload at the end of the source is split into several lines. It still uses over-wide lines because the indentation and the blanks before comments are repeated verbatim, and each line is prefixed with a <code>db \"</code> directive (the prefix) that is itself indented.</p>\n\n<p>It differs a bit in that I only escape any <code>\"</code> as <code>@</code>, and don't use any literal <code>@</code> characters in the program code or its comments. Instead, in the comments I refer to \"code 40h characters\", and in the code compare al to <code>40h</code>. When displaying the payload, I scan for LFs (code 10) and wrap the individual lines (excluding the literal linebreak characters) in the <em>prefix</em> and <em>suffix</em> messages.</p>\n\n<p>My program also uses interrupt 21h function 40h instead of your mix of functions 09h and 02h. This allows me to use dollar characters <code>$</code> as literals in both the program code and the payload, which are needed to calculate string lengths in NASM without adding labels at the end of the strings.</p>\n\n<hr>\n\n<p>I also evolved my nice quine (q.asm), first modifying only the payload to create <a href=\"https://hg.ulukai.org/ecm/quine/file/eac01194cb9a/halfqt.asm\" rel=\"nofollow noreferrer\">halfqt.asm</a>, and then running that to create <a href=\"https://hg.ulukai.org/ecm/quine/file/eac01194cb9a/qt.asm\" rel=\"nofollow noreferrer\">the shorter qt.asm</a>.</p>\n\n<p>Like your Q1:</p>\n\n<ul>\n<li><p>Dropped indentation, and most comments.</p></li>\n<li><p>Used shorter number bases (<code>int 33</code> etc).</p></li>\n</ul>\n\n<p>Unlike your Q1:</p>\n\n<ul>\n<li><p>Kept org 256 (and cpu 8086).</p></li>\n<li><p>Kept using labels, though all just one letter now.</p></li>\n<li><p>Kept same program logic, including the process termination call.</p></li>\n<li><p>Kept the linebreak at the end of file.</p></li>\n</ul>\n\n<hr>\n\n<p>Finally, I modified the program code (but not payload) of qt.asm to create <a href=\"https://hg.ulukai.org/ecm/quine/file/eac01194cb9a/annotqt.asm\" rel=\"nofollow noreferrer\">the annotated variant</a>. You can read this to learn in more detail about my decisions for the qt.asm variant.</p>\n\n<hr>\n\n<p>Sizes:</p>\n\n<ul>\n<li><p>7535 q.asm</p></li>\n<li><p>3003 q.com</p></li>\n<li><p>4948 halfqt.asm</p></li>\n<li><p>838 halfqt.com</p></li>\n<li><p>2218 qt.asm</p></li>\n<li><p>838 qt.com</p></li>\n<li><p>4072 annotqt.asm</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T16:37:18.790", "Id": "233598", "ParentId": "233161", "Score": "3" } }, { "body": "<h2>a. Shortest minus 1</h2>\n\n<p>The Q4 program contains a 2-byte <code>xor dx,dx</code> that you can rapidly replace by\n the 1-byte <code>cwd</code> instruction. Just bring that <code>mov ax,484Eh</code> on top. The\n positive number in <code>AX</code> will make <code>cwd</code> clear <code>DX</code>.</p>\n\n<pre><code>B8 4E 48 mov ax,484Eh (*)\n99 cwd\nB2 FC mov dl,252\n89 D7 mov di,dx\nD1 E8 shr ax,1\n89 45 21 mov [di+33],ax\nB8 64 62 mov ax,6264h\nAB stosw\nB8 20 26 mov ax,2620h\nFE C4 inc ah\nAB stosw\n80 C4 E2 add ah,226\nCD 21 int 21h\nC3 ret\n</code></pre>\n\n<p>(*) I've had to correct a typo! You erroneously wrote 487Eh.</p>\n\n<hr>\n\n<h2>b. Shortest minus 3</h2>\n\n<p>When DOS starts a .COM program the general purpose registers have a certain\n value and you can take advantage of this fact.</p>\n\n<p><em>Please note that the values that these general purpose registers have when the program is loaded by DOS are <strong>not officially documented</strong>. I myself would certainly never rely on it for any serious program, but since this Quine project is almost always some kind of challenge (even though you say that it is not!), I believe this is a genuine opportunity to shorten the code.</em></p>\n\n<p>Here's the list (<code>DX</code> equals <code>CS=DS=ES=SS</code>):</p>\n\n<pre><code>AX=0000 BX=0000 CX=00FF SI=0100 DI=FFFE BP=091C\n</code></pre>\n\n<p>This is also true for emulators like <a href=\"https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjVyqXZgbDmAhWMxIUKHfAUAZIQFjAAegQIBhAB&amp;url=https%3A%2F%2Fwww.dosbox.com%2Fdownload.php%3Fmain%3D1&amp;usg=AOvVaw38peVDaamECsmPiuqiIufd\" rel=\"nofollow noreferrer\">DOSBox 0.74</a> and <a href=\"https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=2&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwiegvf-gbDmAhUEtRoKHYR_D_QQFjABegQIBxAB&amp;url=http%3A%2F%2Fwww.vdosplus.org%2F&amp;usg=AOvVaw3YF00dZ4-UrTBk3tbGg-pI\" rel=\"nofollow noreferrer\">vDOS 2016.10.01</a>. They show\n the exact same numbers!</p>\n\n<p>This is how I would write your Q4 program and bring it down to just 27 bytes:</p>\n\n<pre><code>01 F7 add di,si ;This sets DI=254\nFD std\nB8 40 4E mov ax,4E40h\nD1 E8 shr ax,1\nAB stosw ;Space and SingleQuote\n89 FA mov dx,di ;Here DX=252\nB8 64 62 mov ax,6264h\nAB stosw ;Characters d and b\nB8 4E 48 mov ax,484Eh\nD1 E8 shr ax,1\n89 45 21 mov [di+33],ax ;SingleQuote and DollarSign (*)\n95 xchg ax,bp ;This sets AH=09h\nCD 21 int 21h\nC3 ret\n</code></pre>\n\n<p>(*) +33 is because <code>DI</code> points to 6 bytes before a program of 27 bytes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T13:55:12.690", "Id": "457379", "Score": "1", "body": "It is an annoyingly persistent myth that non-segment registers other than IP and SP have particular values at startup. I wrote and published [this assembly language program](http://www.beroset.com/asm/showregs.asm) 24 years ago to demonstrate that very point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T15:59:28.973", "Id": "457394", "Score": "1", "body": "@Edward I'm well aware of the fact that these general purpose registers don't have a well defined documented value at startup. I would certainly never rely on it for any serious program, but since this Quine business is almost always some kind of __challenge__, I believe this to be __a valid exception__. As a side note, I'm happy to see that the values that you got from your program back then, seem not too different from those that I got from 3 different execution environments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T16:26:37.847", "Id": "457396", "Score": "0", "body": "I'm glad to hear that. I'm hoping you see that your first sentence in that comment and the first sentence under \"shortest minus 3\" are contradictory. Please clarify that part of your answer to avoid misleading others who might not be as experienced as you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-13T15:55:16.140", "Id": "457546", "Score": "1", "body": "@Edward Added a short comment. Thank you for drawing my attention to it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-12T11:37:46.020", "Id": "233918", "ParentId": "233161", "Score": "2" } } ]
{ "AcceptedAnswerId": "233598", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T13:47:48.070", "Id": "233161", "Score": "9", "Tags": [ "assembly", "x86" ], "Title": "A progression of quines" }
233161
<p>I wrote this code since I'm going through the hackerrank challenges, however, it takes way too long to run. Its function is described on the title, but just to clear it up, we need to count the minimum amount of swaps needed to order a set of ascending integers.</p> <pre><code>def minimumSwaps(arr): count = 0 correct = [(x+1) for x in range(len(arr))] while arr != correct: for i in arr: if i != arr.index(i)+1: a = i b = arr[i-1] arr[i-1] = a arr[arr.index(i)] = b count += 1 break return count if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) res = minimumSwaps(arr) print(str(res)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:23:53.113", "Id": "455670", "Score": "0", "body": "That won't work on input `200 1 45` ---> `IndexError: list index out of range`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:25:49.923", "Id": "455672", "Score": "0", "body": "The input format should be:\n1st Line: integer of the size of the array\n2nd Line: the array itself" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:32:28.297", "Id": "455673", "Score": "0", "body": "I mentioned about \"2nd Line: the array itself\" - it throws an error. Besides, the result of statement `n = int(input())` is not used anywhere in your code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:35:49.530", "Id": "455675", "Score": "0", "body": "Oh, sorry again, the second line should be n space-separated integers that form the array. So the complete input should look something like: 4 (new line) 4 2 1 3" } ]
[ { "body": "<p>I don't have time to really look at the code well or do a full review, but what did stick out to me was the repeated calls to <code>arr.index(i)</code>. That's an expensive call that will require, in the worst case, a full iteration of <code>arr</code> <em>each time</em>.</p>\n\n<p>At the very least, that call should be done once then cached. Really though, that information is already available to you without searching if you use <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"noreferrer\"><code>enumerate</code></a>:</p>\n\n<pre><code>def minimum_swaps(arr):\n count = 0\n correct = [(x+1) for x in range(len(arr))]\n while arr != correct:\n for i, x in enumerate(arr): # I changed what was i to x, then made i the index\n if x != i+1:\n a = x\n b = arr[x-1]\n arr[x-1] = a\n arr[i] = b\n count += 1\n break\n\n return count\n</code></pre>\n\n<p>I also renamed some variables. <code>i</code> is an awful name for an element that <em>isn't</em> itself an index, and the function name should be in snake_case instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:23:36.263", "Id": "455669", "Score": "0", "body": "Wow, this just changed the run time from 200 seconds to 0.1628 seconds (literally). Thanks a lot man" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:25:13.697", "Id": "455671", "Score": "1", "body": "@AndréFradinho Ya, no problem. Be aware of what the functions you're using are doing behind the scenes, and be wary of excessive use of any function that is repeatedly searching through a list or other sequence." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T15:17:03.067", "Id": "233168", "ParentId": "233162", "Score": "8" } } ]
{ "AcceptedAnswerId": "233168", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T14:16:35.823", "Id": "233162", "Score": "6", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "Count swaps needed to order a list of integers" }
233162
<p>I started learning VBA for an internship, 3 months ago. This is the last project I have worked on. It does all the tasks it has to do, it's all about code review. I will be grateful for all suggestions for optimization of solutions/other solutions, good practices (writing, commenting on the code) and everything else that you think may help me in the future.</p> <p>The workbook is used to automate the sending of an e-mail by the applicant to the classifier (appropriate people in the company who can complete the process), and then for the classifier it automates the filling of a special excel sheet with which further steps are taken. Additionally, this workbook is on a network drive. Target users download it to their local drive and may sometimes need to be updated, hence the "check workbook update" function (this function caused me a lot of problems, I'm curious about other solutions. I'm aware that the current one is not the best). The list of classifiers is also monitored for changes because it also changes regularly</p> <p>Everywhere in the code where "xyz" is intentional. the program was written in Polish and I actually translate it only for the needs of this post, so I am sorry if somewhere there are remains of Polish and places not the best translations</p> <h2>Code in "Backend" worksheet</h2> <pre><code> Option Explicit Dim externalFile As Workbook Dim backend As Worksheet Const numberOfRowsBeforeRecords = 1 Sub CheckingComplianceClassifierList() 'Checking if the workbook with the list of classifiers has not changed since the last time using this workbook and update this list in this workbook if needed Module3.OptimizeCodeBegin Dim lastModifiedExternalFile As Date 'last updated classifier workbook Dim cellWithModifiedDate As Range Dim externalFilePath As String Set backend = ThisWorkbook.Worksheets("Backend") externalFilePath = backend.Range("B2").Value2 Set externalFile = Module3.OpenAndSetFile(externalFilePath) If Not externalFile Is Nothing Then 'case when the OpenAndSetFile function does not work (probably, the wrong path) lastModifiedExternalFile = FileDateTime(externalFilePath) Set cellWithModifiedDate = backend.Range("B1") If cellWithModifiedDate.Value2 &lt; lastModifiedExternalFile Then 'last check &lt; modification date Dim classifiersAmount As Integer With externalFile.Worksheets(1) classifiersAmount = .Cells(.Rows.Count, "A").End(xlUp).Row - numberOfRowsBeforeRecords 'checks the amount of classifiers in an external file End With PrepareWorksheet classifiersAmount 'Cleaning classifier tables RewriteClassifiers classifiersAmount ProcessClose 'removes filters, closes the external file cellWithModifiedDate.Value2 = Now() 'updates date Else externalFile.Close False End If End If Module3.OptimizeCodeEnd End Sub Sub PrepareWorksheet(classifiersAmount As Integer) 'clearing the classifier tables - needed if the number in some area decreases With backend If .Range("A7") &lt;&gt; "" Then .ListObjects("TabelaMechanical").DataBodyRange.Delete 'if cell A7 (first table cell) is empty, it means that the table is already cleared If .Range("B7") &lt;&gt; "" Then .ListObjects("TabelaPower").DataBodyRange.Delete If .Range("C7") &lt;&gt; "" Then .ListObjects("TabelaInteriors").DataBodyRange.Delete If .Range("D7") &lt;&gt; "" Then .ListObjects("TabelaCSS").DataBodyRange.Delete End With End Sub Sub RewriteClassifiers(classifiersAmount As Integer) 'Sub which takes data from the external spreadsheet and pastes it into it Dim externalData As Worksheet Dim namesColumn As Range Dim lastRow As Integer lastRow = classifiersAmount + numberOfRowsBeforeRecords Set externalData = externalFile.Worksheets(1) Set namesColumn = externalData.Range("C2:C" &amp; lastRow) 'column containing the name of classifiers FilterAndCopy "Mechanical Systems", externalData, namesColumn, "A7" 'Sub FilterAndCopy(workingArea As String, externalData As Worksheet, namesColumn As Range, destination As String) FilterAndCopy "Power&amp;Control", externalData, namesColumn, "B7" FilterAndCopy "Interiors", externalData, namesColumn, "C7" FilterAndCopy "CSS", externalData, namesColumn, "D7" End Sub Sub ProcessClose() externalFile.Worksheets(1).Cells.AutoFilter externalFile.Close SaveChanges:=False End Sub Sub FilterAndCopy(workingArea As String, externalData As Worksheet, namesColumn As Range, destination As String) externalData.Cells.AutoFilter Field:=11, Criteria1:=workingArea namesColumn.SpecialCells(xlCellTypeVisible).Copy 'copies visible cells from the column containing the name of the classifier backend.Range(destination).PasteSpecial xlPasteValues End Sub Sub CheckingComplianceTemplate() Set backend = ThisWorkbook.Worksheets("Backend") Dim lastModifiedExternalFile As Date Dim externalFilePath As String externalFilePath = backend.Range("E2").Value2 lastModifiedExternalFile = FileDateTime(externalFilePath) Dim cellWithModifiedDate As Range Set cellWithModifiedDate = backend.Range("E1") Dim permissionCell As Range Set permissionCell = backend.Range("E3") If cellWithModifiedDate.Value2 &lt; lastModifiedExternalFile Then 'last check &lt; modification date, a positive result means that the template has been modified since the last check permissionCell.Value2 = False MsgBox "Your version of the spreadsheet is out of date. Download current template - location: xyz" Else permissionCell.Value2 = True cellWithModifiedDate = Now() End If End Sub </code></pre> <h2>Code in "ThisWorkbook"</h2> <pre><code> Option Explicit Private Sub Workbook_BeforeClose(Cancel As Boolean) ThisWorkbook.Worksheets("backend").CheckingComplianceTemplate If ThisWorkbook.Worksheets("backend").Range("E3").Value2 = True Then ThisWorkbook.Worksheets("backend").Range("E1").Value2 = DateAdd("s", 10, Now()) End If Module3.OptimizeCodeEnd End Sub Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) ThisWorkbook.Worksheets("backend").CheckingComplianceTemplate If ThisWorkbook.Worksheets("backend").Range("E3").Value2 = True Then ThisWorkbook.Worksheets("backend").Range("E1").Value2 = DateAdd("s", 10, Now()) End If End Sub Private Sub Workbook_Open() With ThisWorkbook .Worksheets(2).Protect UserInterfaceOnly:=True, Password:="xyz" .Worksheets(3).Protect UserInterfaceOnly:=True, Password:="xyz" End With Arkusz4.CheckingComplianceClassifierList Arkusz4.CheckingComplianceTemplate End Sub </code></pre> <h2>Code in "Module2" module</h2> <pre><code> Option Explicit Dim batchLoad As Workbook Dim classifications As Worksheet, backend As Worksheet Dim recordAmount As Integer Const numberRowsBeforeRecordsClassificationWorksheet = 8 Sub BatchLoadFillingProcess() ThisWorkbook.Worksheets("backend").CheckingComplianceTemplate If ThisWorkbook.Worksheets("backend").Range("E3") = True Then 'cell E3 stores the value true / false set on the basis of checking compliance with the template on a network drive Module3.OptimizeCodeBegin PrepareWorksheet 'assign/calculate global variables/objects If CheckSignature = True Then 'compares the saved signature with what it should be If Verification = True Then 'Verification whether all started rows have all columns filled in and whether part of the classifier is filled in correctly FillingBatchLoad SaveBatchLoad Else batchLoad.Close SaveChanges:=False 'close BatchLoada's template End If Module3.OptimizeCodeEnd Else batchLoad.Close SaveChanges:=False 'close BatchLoada's template End If End If End Sub Sub PrepareWorksheet() Set classifications = ThisWorkbook.Worksheets("Classification") Set backend = ThisWorkbook.Worksheets("backend") Dim templatePath As String templatePath = backend.Range("H1") Workbooks.Open Filename:=templatePath, ReadOnly:=True Set batchLoad = ActiveWorkbook Dim recordRange As Range Set recordRange = ThisWorkbook.Worksheets(1).Range("B9:B59") recordAmount = Application.WorksheetFunction.CountA(recordRange) End Sub Function CheckSignature() As Boolean Dim currentSignature As String, project As String, classifier As String, correctSignature As String currentSignature = backend.Range("B5").Value2 project = classifications.Range("F3").Value2 classifier = classifications.Range("F5").Value2 classifier = Replace(classifier, " ", "") correctSignature = project &amp; classifier &amp; recordAmount If correctSignature = currentSignature Then CheckSignature = True Else CheckSignature = False MsgBox "Wrong Signature" End If End Function Function Verification() As Boolean Dim recordAmount As Integer Verification = VerificationRowFilling 'function checks if columns B to H are filled in every started row If Verification = True Then Verification = ClassifierRowVerification 'function checks if the classifier did not fill rows that the applicant did not fill End If End Function Function VerificationRowFilling() As Boolean 'Define the range of filled rows Dim rangeFilledRows As Range Set rangeFilledRows = Range(classifications.Cells(numberRowsBeforeRecordsClassificationWorksheet + 1, 2), classifications.Cells(numberRowsBeforeRecordsClassificationWorksheet + recordAmount, 8)) 'The condition checks whether the number of filled cells in the range (left side) corresponds to the number of cells in the range (right side) 'there is no option to fill more cells than it is in range, so else is synonymous with equality If WorksheetFunction.CountA(rangeFilledRows) &lt; rangeFilledRows.Count Then VerificationRowFilling = False MsgBox "Not all columns in the started rows are filled" Else VerificationRowFilling = True End If End Function Function ClassifierRowVerification() As Boolean 'define the range that we will check Dim amountRowsFilledByApplicant As Integer amountRowsFilledByApplicant = numberRowsBeforeRecordsClassificationWorksheet + recordAmount Dim rangeOutOfFilledRange As Range Set rangeOutOfFilledRange = Range(classifications.Cells(amountRowsFilledByApplicant + 1, 2), classifications.Cells(60, 8)) 'Note: 60th row is out of table, but if the last row was 59, the condition check below gives an incorrect result if all rows in the table are filled (amountRowsFilledByApplicant + 1 = 59 + 1 = 60) 'checking if there are any filled cells in the unwanted range Dim amountOfFilledCellsInUnwantedRange As Integer amountOfFilledCellsInUnwantedRange = Application.WorksheetFunction.CountA(rangeOutOfFilledRange) 'return the appropriate flag, display the message If amountOfFilledCellsInUnwantedRange = 0 Then 'no filled cells outside the wanted range ClassifierRowVerification = True Else ClassifierRowVerification = False MsgBox "filling cells outside records filled by the applicant" End If End Function Sub FillingBatchLoad() 'Function that fulfills the BatchLoad template based on the data entered in this spreadsheet Dim currentSpreadsheetRow As Range, currentBatchLoadRow As Range Dim loopCounter As Integer Const naglowekBatchLoada = 1 For loopCounter = 1 To recordAmount 'defining the row from which we take data and to which we save data in a given iteration With classifications Set currentSpreadsheetRow = .Range(.Cells(loopCounter + numberRowsBeforeRecordsClassificationWorksheet, 2), .Cells(loopCounter + numberRowsBeforeRecordsClassificationWorksheet, 8)) End With With batchLoad.Worksheets(1) Set currentBatchLoadRow = .Range(.Cells(loopCounter + naglowekBatchLoada, 1), .Cells(loopCounter + naglowekBatchLoada, 31)) End With currentBatchLoadRow(1).Value2 = currentSpreadsheetRow(1).Value2 'xyz currentBatchLoadRow(2).Value2 = currentSpreadsheetRow(4).Value2 'xyz currentBatchLoadRow(3).Value2 = currentSpreadsheetRow(2).Value2 'xyz currentBatchLoadRow(4).Value2 = "?" 'xyz currentBatchLoadRow(5).Value2 = "?" 'xyz currentBatchLoadRow(6).Value2 = "?" 'xyz currentBatchLoadRow(7).Value2 = "?" 'xyz currentBatchLoadRow(8).Value2 = currentSpreadsheetRow(5).Value2 'xyz currentBatchLoadRow(13).Value2 = classifications.Range("F3").Value2 'xyz currentBatchLoadRow(14).Value2 = backend.Range("B4").Value2 'xyz currentBatchLoadRow(16).Value2 = "?" 'xyz currentBatchLoadRow(17).Value2 = "?" 'xyz currentBatchLoadRow(18).Value2 = currentSpreadsheetRow(6).Value2 'xyz currentBatchLoadRow(20).Value2 = currentSpreadsheetRow(7).Value2 'xyz currentBatchLoadRow(21).Value2 = "?" 'xyz currentBatchLoadRow(23).Value2 = backend.Range("B3").Value2 'xyz currentBatchLoadRow(24).Value2 = "?" 'xyz currentBatchLoadRow(25).Value2 = classifications.Range("F4").Value2 'xyz Next loopCounter End Sub Sub SaveBatchLoad() Dim tytul As String tytul = "BatchLoad for project - " &amp; classifications.Range("F3").Value2 'classifications.Range("F3") it's project's number batchLoad.Activate Dim batchLoadPath As String batchLoadPath = Application.GetSaveAsFilename(InitialFileName:=tytul, FileFilter:="Excel Files (*.xlsb), *.xlsb") If batchLoadPath &lt;&gt; "False" Then 'batchLoadPath = False means that the user has not selected any location batchLoad.SaveAs Filename:=batchLoadPath batchLoad.Close SaveChanges:=False 'close BatchLoad's template Workbooks.Open Filename:=batchLoadPath Else MsgBox "Please enter the path" batchLoad.Close SaveChanges:=False End If End Sub </code></pre> <h2>Code in "Module3" module</h2> <pre><code> Option Explicit Dim CalcState As Long Dim EventState As Boolean, PageBreakState As Boolean, DisplayAlertsState As Boolean Sub OptimizeCodeBegin() Application.ScreenUpdating = False 'EventState = Application.EnableEvents 'Application.EnableEvents = False CalcState = Application.Calculation Application.Calculation = xlCalculationManual PageBreakState = ActiveSheet.DisplayPageBreaks ActiveSheet.DisplayPageBreaks = False DisplayAlertsState = Application.DisplayAlerts Application.DisplayAlerts = False End Sub Sub OptimizeCodeEnd() ActiveSheet.DisplayPageBreaks = PageBreakState Application.Calculation = CalcState 'Application.EnableEvents = EventState Application.DisplayAlerts = DisplayAlertsState Application.ScreenUpdating = True End Sub Sub CalculateRunTime_Seconds() 'PURPOSE: Determine how many seconds it took for code to completely run 'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault Dim StartTime As Double Dim SecondsElapsed As Double 'Remember time when macro starts StartTime = Timer '***************************** 'Insert Your Code Here... '***************************** 'Determine how many seconds code took to run SecondsElapsed = Round(Timer - StartTime, 2) 'Notify user in seconds MsgBox "This code ran successfully in " &amp; SecondsElapsed &amp; " seconds", vbInformation End Sub Function OpenAndSetFile(path) As Workbook If Dir(path) = "" Then 'dir(path) returns the file name, "" means that no file was found MsgBox "file path not found" Exit Function Else Set OpenAndSetFile = Workbooks.Open(Filename:=path, ReadOnly:=True) End If End Function Sub Cleaning() Dim orderRange As Range, applicantRange As Range, classifierRange As Range If MsgBox("Do you want to clear the spreadsheet from the entered data??", vbYesNo, "Cleaning") = vbYes Then With ThisWorkbook.Worksheets("Classification") Set orderRange = .Range("F3:F5") Set applicantRange = .Range("B9:F59") Set classifierRange = .Range("G9:H59") End With orderRange.ClearContents applicantRange.ClearContents classifierRange.ClearContents End If End Sub </code></pre> <h2>Code in "Module4" module</h2> <pre><code>Option Explicit Dim amountRecords As Integer Const numberRowsBeforeRecordsClassificationWorksheet = 8 Sub SendingEmailToClassifier() ThisWorkbook.Worksheets("backend").CheckingComplianceTemplate If ThisWorkbook.Worksheets("backend").Range("E3") = True Then 'cell E3 stores the value true / false set on the basis of checking compliance with the template on a network drive Module3.OptimizeCodeBegin If Verification = True Then PrepareWorksheet 'finding classifier and applicant email SendingEmail 'preparation, content generation and sending an e-mail Else ThisWorkbook.Worksheets("Backend").Range("B3:B4").ClearContents End If Module3.OptimizeCodeEnd End If End Sub Sub PrepareWorksheet() ThisWorkbook.Worksheets("Backend").Range("B3").Value2 = ClassiferEmail ThisWorkbook.Worksheets("Backend").Range("B4").Value2 = ApplicantEmail End Sub Function Verification() As Boolean Dim CollumnInTabel As Range Set CollumnInTabel = ThisWorkbook.Worksheets("Classification").Range("B9:B59") 'first of the columns inside the table amountRecords = Application.WorksheetFunction.CountA(CollumnInTabel) If amountRecords &gt; 0 Then 'A positive result means that at least one record has been entered Verification = VerificationNoBlankRows 'check if there are no empty lines between the entered records Else MsgBox "Enter at least one record" Exit Function End If If Verification = True Then Verification = VerificationRowFilling 'checking if every started record has columns A-F filled Else Exit Function End If If Verification = True Then Verification = VerificationClassifierEmpty() 'checking if the classifier area is empty Else Exit Function End If If Verification = True Then Verification = VerificationOrderRange 'checking if order range is filled Else Exit Function End If End Function Function VerificationOrderRange() As Boolean '' Check if the cells F3-F5 are filled and return the appropriate message, if needed VerificationOrderRange = True With ThisWorkbook.Worksheets("Classification") If .Range("F3") = "" Then MsgBox "Cell F3 (Project number) is empty" VerificationOrderRange = False Exit Function End If If .Range("F4") = "" Then MsgBox "Cell F4 (Working area) is empty" VerificationOrderRange = False Exit Function End If If .Range("F5") = "" Then MsgBox "Cell F5 (Classifier) is empty" VerificationOrderRange = False Exit Function End If End With End Function Function VerificationNoBlankRows() As Boolean 'verification function which checks if there are no gaps between the entered records 'records should be entered one by one if there is a row after the row, which is the sum of the number of entered records and the number of rows before the records, there is a blank row somewhere 'define the range that we will check Dim CorrectFilledRows As Integer CorrectFilledRows = amountRecords + numberRowsBeforeRecordsClassificationWorksheet With ThisWorkbook.Worksheets("Classification") Dim rangeOutOfFilledRange As Range Set rangeOutOfFilledRange = .Range(.Cells(CorrectFilledRows + 1, 2), .Cells(60, 6)) 'Note: 60th row is out of table, but if the last row was 59, the condition check below gives an incorrect result if all rows in the table are filled (amountRowsFilledByApplicant + 1 = 59 + 1 = 60) End With 'checking if there are any filled cells Dim amountOfFilledCellsInUnwantedRange As Integer amountOfFilledCellsInUnwantedRange = Application.WorksheetFunction.CountA(rangeOutOfFilledRange) 'return the appropriate flag, display the message If amountOfFilledCellsInUnwantedRange = 0 Then VerificationNoBlankRows = True Else VerificationNoBlankRows = False MsgBox "Empty lines between entered records" End If End Function Function VerificationRowFilling() As Boolean With ThisWorkbook.Worksheets("Classification") Dim rangeOfFilledRange As Range Set rangeOfFilledRange = .Range(.Cells(numberRowsBeforeRecordsClassificationWorksheet + 1, 2), .Cells(numberRowsBeforeRecordsClassificationWorksheet + amountRecords, 6)) End With 'The condition checks whether the number of filled cells in the range (left side) corresponds to the number of cells in the range (right side) 'there is no option to fill more cells than it is in range, so else is synonymous with equality If WorksheetFunction.CountA(rangeOfFilledRange) &lt; rangeOfFilledRange.Count Then VerificationRowFilling = False MsgBox "Not all columns in the started records are filled" Else VerificationRowFilling = True End If End Function Function VerificationClassifierEmpty() As Boolean With ThisWorkbook.Worksheets("Classification") Dim classifierRange As Range Set classifierRange = .Range("G9:H59") End With If WorksheetFunction.CountA(classifierRange) = 0 Then 'no filled cells in the given range (part of the table for the classifier) VerificationClassifierEmpty = True Else VerificationClassifierEmpty = False MsgBox "Classifier range should be empty" End If End Function Sub SendingEmail() Dim OutApp As Object, Outmail As Object Set OutApp = CreateObject("Outlook.Application") OutApp.Session.logon Set Outmail = OutApp.CreateItem(0) On Error Resume Next 'fill out email With Outmail .To = ThisWorkbook.Worksheets("Backend").Range("B3").Value2 &amp; "test" .Subject = GenerateEmailSubject .Display .HTMLBody = GenerateEmailContent &amp; .HTMLBody 'function generating the content of the e-mail (text, table preview) and adding a footer SaveSignature 'save the signature which will be used in filling BatchLoad ThisWorkbook.Save 'save the file so that after adding it as an attachment to the e-mail there would be all the data entered (records and signature) .Attachments.Add ThisWorkbook.FullName End With On Error GoTo 0 Set Outmail = Nothing Set OutApp = Nothing End Sub Function GenerateEmailSubject() As String Dim text As String text = "Adding classification to the project - " GenerateEmailSubject = text &amp; ThisWorkbook.Worksheets("Classification").Range("F3").Value2 End Function Function GenerateEmailContent() As String 'defining range of data to be copied to the e-mail Dim tableRange As Range Dim textRange As String textRange = "A1:F" &amp; numberRowsBeforeRecordsClassificationWorksheet + amountRecords + 1 Set tableRange = ThisWorkbook.Worksheets("Classification").Range(textRange) 'email content Dim head As String, body As String 'before tabel head = "&lt;HTML&gt;&lt;BODY&gt;Hello" body = "&lt;BR /&gt;I need to classify these parts for our project" 'tabel from excel body = body &amp; RangetoHTML(tableRange) 'after tabel body = body &amp; "&lt;BR /&gt;Thank you!" GenerateEmailContent = head &amp; body End Function Function ApplicantEmail() As String Dim text As String Dim olApp As Object Set olApp = CreateObject("outlook.application") text = olApp.Session.CurrentUser.Name 'example: "Surname, Name xyz xyz xyz - xyz xyz" Dim commaAfterSurname As Integer, spaceAfterName As Integer commaAfterSurname = InStr(1, text, ",") spaceAfterName = InStr(commaAfterSurname + 2, text, " ") Dim Name As String, Surname As String Surname = Left(text, commaAfterSurname - 1) Name = Mid(text, commaAfterSurname + 2, spaceAfterName - commaAfterSurname - 2) ApplicantEmail = UCase(Name) &amp; "." &amp; UCase(Surname) &amp; "@domain.com" End Function Function ClassiferEmail() As String 'prepare Dim path As String path = ThisWorkbook.Worksheets("Backend").Range("B2").Value2 Dim externalFile As Workbook Set externalFile = Module3.OpenAndSetFile(path) Dim classifier As String classifier = ThisWorkbook.Worksheets("Classification").Range("F5").Value2 Dim classifiersAmount As Integer Const numberRowsBeforeRecordsClassifierWorkBook = 1 With externalFile.Worksheets(2) classifiersAmount = .Cells(.Rows.Count, "A").End(xlUp).Row - numberRowsBeforeRecordsClassifierWorkBook End With 'finding classifier email externalFile.Worksheets(2).Cells.AutoFilter externalFile.Worksheets(2).Range("C1:D" &amp; classifiersAmount + 1).AutoFilter Field:=3, Criteria1:=classifier ClassiferEmail = externalFile.Worksheets(2).Range("D2:D" &amp; classifiersAmount + 1).SpecialCells(xlCellTypeVisible) externalFile.Close SaveChanges:=False End Function Function RangetoHTML(rng As Range) 'donwloaded from: https://www.reddit.com/r/excel/comments/37ppo4/how_to_copy_excel_cells_into_a_outlook_email/ ' Works in Excel 2000, Excel 2002, Excel 2003, Excel 2007, Excel 2010, Outlook 2000, Outlook 2002, Outlook 2003, Outlook 2007, and Outlook 2010. Dim fso As Object Dim ts As Object Dim TempFile As String Dim TempWB As Workbook TempFile = Environ$("temp") &amp; "/" &amp; Format(Now, "dd-mm-yy h-mm-ss") &amp; ".htm" ' Copy the range and create a workbook to receive the data. rng.Copy Set TempWB = Workbooks.Add(1) With TempWB.Sheets(1) .Cells(1).PasteSpecial Paste:=8 .Cells(1).PasteSpecial xlPasteValues, , False, False .Cells(1).PasteSpecial xlPasteFormats, , False, False .Cells(1).Select Application.CutCopyMode = False On Error Resume Next .DrawingObjects.Visible = True .DrawingObjects.Delete On Error GoTo 0 End With ' Publish the sheet to an .htm file. With TempWB.PublishObjects.Add( _ SourceType:=xlSourceRange, _ Filename:=TempFile, _ Sheet:=TempWB.Sheets(1).Name, _ Source:=TempWB.Sheets(1).UsedRange.Address, _ HtmlType:=xlHtmlStatic) .Publish (True) End With ' Read all data from the .htm file into the RangetoHTML subroutine. Set fso = CreateObject("Scripting.FileSystemObject") Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2) RangetoHTML = ts.ReadAll ts.Close RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _ "align=left x:publishsource=") ' Close TempWB. TempWB.Close SaveChanges:=False ' Delete the htm file. Kill TempFile Set ts = Nothing Set fso = Nothing Set TempWB = Nothing End Function Sub SaveSignature() Dim project As String, mail As String, signature As String project = ThisWorkbook.Worksheets("Classification").Range("F3").Value2 'Range("F3") is Project number mail = ThisWorkbook.Worksheets("backend").Range("B3").Value2 'Range("B3") is classifier email Dim atPosition As Integer atPosition = InStr(1, mail, "@") 'Search @ in the email adress mail = Left(mail, atPosition - 1) mail = Replace(mail, ".", "") signature = project &amp; mail &amp; amountRecords 'np gfdNAMESURNAME28 ThisWorkbook.Worksheets("backend").Range("B5").Value2 = signature End Sub </code></pre> <p><a href="https://i.stack.imgur.com/rIqAu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rIqAu.png" alt="Classification worksheet"></a></p> <p><a href="https://i.stack.imgur.com/AtYrN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AtYrN.png" alt="Backend worksheet"></a></p>
[]
[ { "body": "<p>I am not going to go through all of the code - instead I'll give you some basic information. This is not meant to be an answer, just more typing than a comment will allow. </p>\n\n<ol>\n<li><p>Name your modules. </p></li>\n<li><p>Use better indentation. Even though whitespace is ignored, that doesnt mean you shouldn't have tidier looking code as well. </p></li>\n<li><p>Since you're new to VBA I'll explain an important concept. Learning to work in memory is very important. Having to interact with the application's \"objects\" will significantly slow down your code. For example, you do lots of sheet manipulation in module4 and module2 - does this actuall need to occur? or is it OCD? Or could it be done all at once? Just some things to think about. When possilbe, learn to use arrays where you can. This leads to the next point...</p></li>\n<li><p>OptimizeCodeBegin and OptimizeCodeEnd - its good that your jamming things into functions and subs. You'll eventaully start building your own personal library of functions and classes. You may even have seperate files that you will use as a class/library repository that you can reference from other projects. However, these two specifically point out an issue in your code. In Excel's object model, these properties that youre turning off/on are a symptom of poor performing code. Using these often a tell tale sign of the need to do a code rewrite. Another big issue with them is that if your code bombs and they dont get turned back on, you have to restart excel to get back to proper funcitonality. Which leads me to the next point:</p></li>\n<li><p>Error handling - where is it? </p></li>\n<li><p>Learn what late binding is. Its a common interview question to test your knowledge but more importantly late binding is helpful when you do not know whether or not there will be version differences of excel (especially if youre distributing documents). This isnt relevant to your code per say, but its something you need to know how to use and understand when/why you would need to use it. </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T19:23:22.003", "Id": "455687", "Score": "0", "body": "_\"This is not meant to be an answer,\"_ That's not really a statement to encourage this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T19:43:38.440", "Id": "455692", "Score": "1", "body": "There's absolutely answer/review material in this post. Upvoted!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T19:46:37.923", "Id": "455693", "Score": "2", "body": "*For every sub/function you write, you need to be in the habit of the first things you type/copy&paste is your error handling code* - strong disagree though: it's critical to handle errors *at entry points*... but most procedures should *bubble up* errors they can't handle (so the caller gets to handle it). Systematically handling errors is harmful IMO." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:04:27.863", "Id": "455695", "Score": "0", "body": "@MathieuGuindon Fair and I agree - I was mostly tailoring this answer for someone who is newer. The point being that lacking error handling in this particular instance could lead to \"why is my excel not responding.\" Ive seen too many times where the topic as a whole is ignored." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:06:00.903", "Id": "455696", "Score": "0", "body": "@πάνταῥεῖ Well I mean the rest of the comment stating \"this is more than a comment will hold\" should kind fo clue you in. Convince the schmucks who set char limits to give me more and i wouldnt do stuff like this lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:13:41.317", "Id": "455698", "Score": "2", "body": "About late binding: any member call made against `Object` or `Variant` is late bound. Late binding is much more than member calls against objects defined in a library that isn't referenced - *implicit* late binding is literally everywhere, and very very much relevant to OP's code. For example anything chained to `Worksheets(...)` is late-bound, because `Sheets.Item` (`Worksheets` property is a `Sheets` collection object with an `Item` default member) returns an `Object`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T18:19:42.663", "Id": "233171", "ParentId": "233163", "Score": "2" } }, { "body": "<p>Excellent first post. The code is well laid out. It is obvious that you are very meticulous and it shows in your coding style.</p>\n\n<h2>Worksheet Code Names</h2>\n\n<p><code>Set backend = ThisWorkbook.Worksheets(\"Backend\")</code> was used 3 times in code and <code>ThisWorkbook.Worksheets(\"Backend\")</code> was used a total of 20 times. Whenever possible change the code-name of your worksheets to something meaningful. Changing <code>worksheets</code> code name creates a fully qualified reference which is unaffected by having its tab name changed and is visible to intellisense.</p>\n\n<h2>Use Named Ranges</h2>\n\n<p><code>Worksheets(\"Backend\").Range(\"B3\")</code> is referred to in 3 separate methods. If you move the <code>ClassiferEmail</code> location you will have to make sure that you find every reference or your code will break.</p>\n\n<blockquote>\n <p>ThisWorkbook.Worksheets(\"Backend\").Range(\"B3\").Value2 = ClassiferEmail</p>\n</blockquote>\n\n<p>Naming your ranges will allow you to change the layout of your worksheets without breaking your code. Named ranges should be qualified to their parent worksheets. To simplify the referencing I will add a property to the worksheet with the same name as the range (see code below).</p>\n\n<blockquote>\n<pre><code>Sub PrepareWorksheet()\n\n ThisWorkbook.Worksheets(\"Backend\").Range(\"B3\").Value2 = ClassiferEmail\n ThisWorkbook.Worksheets(\"Backend\").Range(\"B4\").Value2 = ApplicantEmail\n\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p>At first glance, I thought <code>ClassiferEmail</code> and <code>ApplicantEmail</code> were class level variable. It turns out that they are single use functions that set the worksheet value. The worksheet values are, however, referenced several times. It would be make more sense to give those names to the ranges and change the functions to subs (e.g. <code>SetClassiferEmail</code> and <code>SetApplicantEmail</code>).</p>\n\n<h2>Clearing ListObjects</h2>\n\n<p>This is very situational:</p>\n\n<blockquote>\n<pre><code>If .Range(\"A7\") &lt;&gt; \"\" Then .ListObjects(\"TabelaMechanical\").DataBodyRange.Delete\n</code></pre>\n</blockquote>\n\n<p>This is the right way:</p>\n\n<blockquote>\n<pre><code>If Not .ListObjects(\"TabelaMechanical\").DataBodyRange Is Nothing Then .ListObjects(\"TabelaMechanical\").DataBodyRange.Delete\n</code></pre>\n</blockquote>\n\n<p>I also add properties to my worksheets to refer to the ListObjects on it.</p>\n\n<h2>Miscellaneous</h2>\n\n<p>The <code>externalFile</code> is read-only, why both turning off <code>AutoFilter</code>? </p>\n\n<blockquote>\n<pre><code>Sub ProcessClose()\n\n externalFile.Worksheets(1).Cells.AutoFilter\n externalFile.Close SaveChanges:=False\n\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p>I prefer to keep the external files open while I am coding. THe line below is also useful in cases where the end user has is working on the external file.</p>\n\n<blockquote>\n<pre><code>If externalFile.ReadOnly Then externalFile.Close SaveChanges:=False\n</code></pre>\n</blockquote>\n\n<p>Only visible rows of filtered data are copied. There is no need to use <code>SpecialCells(xlCellTypeVisible)</code> when copying filtered data. </p>\n\n<blockquote>\n<pre><code>namesColumn.SpecialCells(xlCellTypeVisible).Copy\n</code></pre>\n</blockquote>\n\n<p>I like the use of the constants <code>Const numberOfRowsBeforeRecords = 1</code> bit using it in conjunction with \"C2\" defeats the purpose. Mainly</p>\n\n<h2>BackEnd Worksheet Code Refactored</h2>\n\n<pre><code>Const numberOfRowsBeforeRecords = 1\n\nSub CheckingComplianceClassifierList()\n\n 'Checking if the workbook with the list of classifiers has not changed since the last time using this workbook and update this list in this workbook if needed\n Module3.OptimizeCodeBegin\n\n Dim externalFile As Workbook\n Set externalFile = Module3.OpenAndSetFile(Me.ExternalFilePathCell.Value)\n\n If Not externalFile Is Nothing Then 'case when the OpenAndSetFile function does not work (probably, the wrong path)\n Dim lastModifiedExternalFile As Date 'last updated classifier workbook\n lastModifiedExternalFile = FileDateTime(Me.ExternalFilePathCell.Value)\n\n If Me.ModifiedDateCell.Value2 &lt; lastModifiedExternalFile Then 'last check &lt; modification date\n\n Dim classifiersAmount As Long\n\n With externalFile.Worksheets(1)\n classifiersAmount = .Cells(.Rows.Count, \"A\").End(xlUp).Row - numberOfRowsBeforeRecords 'checks the amount of classifiers in an external file\n End With\n\n PrepareWorksheet 'Cleaning classifier tables\n RewriteClassifiers externalFile, classifiersAmount\n Me.ModifiedDateCell.Value2 = Now() 'updates date\n End If\n\n If externalFile.ReadOnly Then externalFile.Close SaveChanges:=False\n End If\n\n Module3.OptimizeCodeEnd\nEnd Sub\n\nSub RewriteClassifiers(ByRef externalFile As Workbook, ByVal classifiersAmount As Long)\n 'Sub which takes data from the external spreadsheet and pastes it into it\n\n Dim lastRow As Integer\n lastRow = classifiersAmount + numberOfRowsBeforeRecords\n\n Dim externalData As Worksheet\n Set externalData = externalFile.Worksheets(1)\n\n Dim namesColumn As Range\n Set namesColumn = externalData.Range(\"C2\").Resize(classifiersAmount) 'column containing the name of classifiers\n\n FilterAndCopy \"Mechanical Systems\", externalData, namesColumn, Me.TabelaMechanical 'Sub FilterAndCopy(workingArea As String, externalData As Worksheet, namesColumn As Range, destination As String)\n FilterAndCopy \"Power&amp;Control\", externalData, namesColumn, Me.TabelaPower\n FilterAndCopy \"Interiors\", externalData, namesColumn, Me.TabelaInteriors\n FilterAndCopy \"CSS\", externalData, namesColumn, Me.TabelaCSS\n\nEnd Sub\n\nSub FilterAndCopy(workingArea As String, externalData As Worksheet, namesColumn As Range, table As ListObject)\n externalData.Cells.AutoFilter Field:=11, Criteria1:=workingArea\n namesColumn.Copy 'copies visible cells from the column containing the name of the classifier\n\n If Not table.DataBodyRange Is Nothing Then table.DataBodyRange.Delete\n table.Range.Offset(1).PasteSpecial xlPasteValues\nEnd Sub\n\nSub CheckingComplianceTemplate()\n If Me.ModifiedDateCell.Value2 &lt; FileDateTime(Me.ExternalFilePathCell.Value) Then 'last check &lt; modification date, a positive result means that the template has been modified since the last check\n Me.PermissionCell.Value2 = False\n MsgBox \"Your version of the spreadsheet is out of date. Download current template - location: xyz\"\n Else\n Me.PermissionCell.Value2 = True\n Me.ModifiedDateCell.Value2 = Now()\n End If\nEnd Sub\n\nPublic Property Get TabelaMechanical() As ListObject\n Set TabelaMechanical = Me.ListObjects(\"TabelaMechanical\")\nEnd Property\n\nPublic Property Get TabelaPower() As ListObject\n Set TabelaPower = Me.ListObjects(\"TabelaPower\")\nEnd Property\n\nPublic Property Get TabelaInteriors() As ListObject\n Set TabelaInteriors = Me.ListObjects(\"TabelaInteriors\")\nEnd Property\n\nPublic Property Get TabelaCSS() As ListObject\n Set TabelaCSS = Me.ListObjects(\"TabelaCSS\")\nEnd Property\n\nPublic Property Get ApplicantEmailCell() As Range\n Set ApplicantEmailCell = Me.Range(\"ApplicantEmail\")\nEnd Property\n\nPublic Property Get ClassiferEmailCell() As Range\n Set ClassiferEmailCell = Me.Range(\"ClassiferEmail\")\nEnd Property\n\nPublic Property Get PermissionCell() As Range\n Set PermissionCell = Me.Range(\"PermissionCell\")\nEnd Property\n\nPublic Property Get ModifiedDateCell() As Range\n Set ModifiedDateCell = Me.Range(\"ModifiedDate\")\nEnd Property\n\nPublic Property Get ExternalFilePathCell() As Range\n Set ExternalFilePathCell = Me.Range(\"ExternalFilePath\")\nEnd Property\n</code></pre>\n\n<hr>\n\n<h2>FillingBatchLoad</h2>\n\n<p>Again I like the use of constants but <code>numberRowsBeforeRecordsClassificationWorksheet</code> is 46 characters.<br>\n<code>loopCounter</code> is also too long for my taste. Using a single letter for the counter name will suffice when there is only one loop. There isn't really even a need for the loop. </p>\n\n<p>I would have refactored this sub but the range rely on the code below taken from a separate sub. There are much better ways to define ranges. </p>\n\n<blockquote>\n<pre><code>Set recordRange = ThisWorkbook.Worksheets(1).Range(\"B9:B59\")\nrecordAmount = Application.WorksheetFunction.CountA(recordRange)\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T08:07:21.037", "Id": "233219", "ParentId": "233163", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T14:18:21.143", "Id": "233163", "Score": "5", "Tags": [ "beginner", "vba", "excel" ], "Title": "VBA Workbook to automate e-mail delivery" }
233163
<p>I'm growing a web server in Haskell that interfaces with TCP sockets using <a href="https://hackage.haskell.org/package/network" rel="noreferrer">network</a>. To read the HTTP header of the client's message, I use the following function:</p> <pre><code>import Network.Socket hiding ( recv ) import Network.Socket.ByteString ( recv ) import qualified Data.ByteString as S import Data.ByteString.UTF8 as BSU ( fromString ) readHeader :: Socket -&gt; IO S.ByteString readHeader sock = go sock mempty where go sock prevContent = do newContent &lt;- recv sock maxNumberOfBytesToReceive let content = prevContent &lt;&gt; newContent -- Read the data from the socket unless it's empty which means -- that the client has closed its socket or we see an empty line -- which marks the end of the HTTP header if S.null newContent || emptyLine `S.isSuffixOf` content then return content else go sock content where -- Only read one byte at a time to avoid reading further than the -- empty line separating the HTTP header from the HTTP body maxNumberOfBytesToReceive = 1 emptyLine = BSU.fromString "\r\n\r\n" </code></pre> <p>The function only reads a byte at a time since I want to be able to read the rest of the client's message from the socket afterwards. But I'm curious whether the function could be more efficient.</p> <p>My first idea was to read more bytes (say 1024) from the socket, check if those bytes contain an empty line, save that part (the HTTP header) in a ByteString and put the bytes after the empty line back into the socket's buffer. But I'm not sure whether it's possible or wise to put data back into the socket's buffer.</p> <p>I'm also interested in any other code improvements that come to your mind.</p> <p>The whole project is <a href="https://gitlab.com/bullbytes/slokitu" rel="noreferrer">here</a>.</p> <p>Start it with <code>stack ghci</code> and then run <code>main</code>. Send it an HTTP request with <code>curl http://localhost:8080/</code></p>
[]
[ { "body": "<p>Perhaps you could wrap bare <code>Socket</code>s in an auxiliary datatype that enabled buffering. Something like:</p>\n\n<pre><code>data BufferedSocket = BufferedSocket [ByteString] Socket\n</code></pre>\n\n<p>Then you could define your own <code>recv</code> function like</p>\n\n<pre><code>recv :: BufferedSocket -&gt; Int -&gt; IO (BufferedSocket,ByteString)\n</code></pre>\n\n<p>which looked at the buffer before actually trying to read data from the socket. Note that this version of <code>recv</code> returns a modified copy of the <code>BufferedSocket</code>, because now we carry some state that isn't captured in the mutable <code>Socket</code> reference.</p>\n\n<p>(Perhaps this extra buffer state should be put in a separate mutable reference, an <a href=\"http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-IORef.html#t:IORef\" rel=\"nofollow noreferrer\"><code>IORef</code></a> for example. We are already in mutable-land after all.)</p>\n\n<p>We also need a function</p>\n\n<pre><code>putBack :: ByteString -&gt; BufferedSocket -&gt; BufferedSocket\n</code></pre>\n\n<p>for prepending the data.</p>\n\n<hr>\n\n<p>Another option could consist in using a streaming library like <a href=\"http://hackage.haskell.org/package/streaming\" rel=\"nofollow noreferrer\">streaming</a> or <a href=\"http://hackage.haskell.org/package/streaming-bytestring\" rel=\"nofollow noreferrer\">streaming-bytestring</a> and build a <a href=\"http://hackage.haskell.org/package/streaming-0.2.3.0/docs/Streaming.html#t:Stream\" rel=\"nofollow noreferrer\"><code>Stream</code></a> of <code>ByteString</code>s out of the <code>Socket</code>. Prepending would consist simply in concatenating a pure <code>Stream</code> that yields the <code>ByteString</code> to the effectful stream that reads from the socket, using <code>&gt;&gt;</code> or <code>*&gt;</code>.</p>\n\n<pre><code>let socketStream' = S.yield someByteStringValue *&gt; socketStream\n</code></pre>\n\n<p>Note that the old <code>socketStream</code> value should <em>not</em> be reused!</p>\n\n<p>This might have the disadvantage that you lose some control about how many bytes to \"physically\" read at each step, because typical <code>Stream</code>s don't take \"feedback\" from downstream about the number of bytes to receive next.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T20:03:04.980", "Id": "233207", "ParentId": "233165", "Score": "4" } } ]
{ "AcceptedAnswerId": "233207", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T14:57:45.990", "Id": "233165", "Score": "6", "Tags": [ "haskell", "http", "tcp" ], "Title": "Read HTTP header from TCP socket" }
233165
<p>I want to significantly tidy this code as its cluttered and repetitive</p> <pre><code>var myDate = "No MOT" if ((myData[0]["motTests"][0]["expiryDate"].string) != nil) { let theDate=myData[0]["motTests"][0]["expiryDate"].string let msYear = theDate!.prefix(4) let msMonth = theDate!.suffix(5).prefix(2) let msDay = theDate!.suffix(2) let mYear = Int (msYear) let mMonth = Int (msMonth) let mDay = Int(msDay) self.motDue = self.convertDate(aYear: mYear!, aMonth: mMonth!, aDay: mDay!) myDate=msDay+("/")+msMonth+"/"+msYear } if ((myData[0]["motTestExpiryDate"].string) != nil){ let theDate=myData[0]["motTestExpiryDate"].string let msYear = theDate!.prefix(4) let msMonth = theDate!.suffix(5).prefix(2) let msDay = theDate!.suffix(2) let mYear = Int (msYear) let mMonth = Int (msMonth) let mDay = Int(msDay) self.motDue = self.convertDate(aYear: mYear!, aMonth: mMonth!, aDay: mDay!) myDate=msDay+("/")+msMonth+"/"+msYear } self.myMOT.text=String(myDate) </code></pre> <p>The code checks to see if the vehicle has an MOT, if it does its sets myDate to the date. If not it checks when the first MOT is due and sets myDate to that's and if not myDate stays set to "No MOT"</p> <p>It works but needs improving.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T18:51:36.013", "Id": "455682", "Score": "1", "body": "Can you describe the exact format of `myData`, and the possible formats of the expiry date that you want to parse?" } ]
[ { "body": "<p>I'm not sure exactly what the code is trying to do, and I don't know Swift, so my answer is a bit of a mess.</p>\n\n<p>I'm assuming that:</p>\n\n<ul>\n<li><p>there is a date in the format of <code>YYYY/MM/dd</code>, so for example <code>2019/11/30</code></p></li>\n<li><p>that date could be in one of seperate places of a data structure</p></li>\n<li><p>the end result is a date which is extracted from two seperate places and is converted into a Swift date format class that can be used for other things</p></li>\n<li><p>I don't know what <code>self.convertDate</code> does; I assume that it is taking the date and returning a Swift date class of some kind, or adding X number of years to calculate when the next inspection will be.</p></li>\n</ul>\n\n<p>I got the date parsing code from <a href=\"https://stackoverflow.com/questions/36861732/convert-string-to-date-in-swift\">https://stackoverflow.com/questions/36861732/convert-string-to-date-in-swift</a></p>\n\n<p>Since the bodies of the two if statements are identical, I factored it out. This returns the parsed version of the date in a Swift class (I presume then it can be printed out in any way you want using Swift's date formatter.)</p>\n\n<p>This code is incomplete but is the best I could do:</p>\n\n<pre><code>var myDate = \"No MOT\"\nvar theDate = \"\"\nif ((myData[0][\"motTests\"][0][\"expiryDate\"].string) != nil) {\n theDate = myData[0][\"motTests\"][0][\"expiryDate\"].string\n} else if ((myData[0][\"motTestExpiryDate\"].string) != nil){\n theDate = myData[0][\"motTestExpiryDate\"].string\n}\n\nlet dateFormatter = DateFormatter()\ndateFormatter.dateFormat = \"yyyy/MM/dd\"\ndateFormatter.locale = Locale(identifier: \"en_US_POSIX\") // set locale to reliable US_POSIX\nlet date = dateFormatter.date(from:theDate)!\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T17:04:31.560", "Id": "233232", "ParentId": "233170", "Score": "0" } }, { "body": "<p>Best practice is to get away from manipulating date strings yourself. And use <code>Date</code> types in your model. </p>\n\n<p>So, when you parse the JSON, use <code>DateFormatter</code> to convert the non-user-friendly date strings to <code>Date</code> objects. And when presenting the dates in the UI, use another <code>DateFormatter</code> to present the date in a nice, user-friendly format. I’d also suggest using <code>JSONDecoder</code> for decoding the JSON into your model, so you don’t have to sprinkle your code with cryptic, error-prone, dictionary keys.</p>\n\n<p>So, first, I would suggest specifying a date formatter when you decode. Because most of the dates are in the form <code>yyyy.MM.dd</code>, I’d use that. So, for example:</p>\n\n<pre><code>do {\n let decoder = JSONDecoder()\n let formatter = DateFormatter()\n formatter.locale = Locale(identifier: \"en_US_POSIX\")\n formatter.dateFormat = \"yyyy.MM.dd\"\n decoder.dateDecodingStrategy = .formatted(formatter)\n let result = try decoder.decode([Vehicle].self, from: data)\n print(result)\n} catch {\n print(error)\n}\n</code></pre>\n\n<p>The trick, though, is that one field, <code>completedDate</code> in <code>MOTTest</code>, uses a different string format, namely, <code>yyyy.MM.dd HH:mm:ss</code>, so I’d have <code>JSONDecoder</code> just parse that as a string, but then have a computed property to translate that one date/time string into a <code>Date</code>:</p>\n\n<pre><code>struct Vehicle: Decodable {\n let registration: String\n let make: String\n let model: String\n let firstUsedDate: String\n let fuelType: String\n let primaryColour: String\n let vehicleId: String\n let registrationDate: Date\n let manufactureDate: Date\n let engineSize: String\n let motTests: [MOTTest]\n}\n\nstruct MOTTest: Decodable {\n private static let formatter: DateFormatter = {\n let formatter = DateFormatter()\n formatter.locale = Locale(identifier: \"en_US_POSIX\")\n formatter.dateFormat = \"yyyy.MM.dd HH:mm:ss\"\n return formatter\n }()\n\n let completedDateString: String\n var completedDate: Date? { MOTTest.formatter.date(from: completedDateString) }\n let testResult: String\n let expiryDate: Date?\n let odometerValue: String\n let odometerUnit: String\n let odometerResultType: String\n let motTestNumber: String\n let rfrAndComments: [ReasonForRejection]\n\n private enum CodingKeys: String, CodingKey {\n case completedDateString = \"completedDate\"\n case testResult, expiryDate, odometerValue, odometerUnit, odometerResultType, motTestNumber, rfrAndComments\n }\n}\n\nstruct ReasonForRejection: Decodable {\n let text: String\n let type: String\n let dangerous: Bool\n}\n</code></pre>\n\n<p>That way, <code>JSONDecoder</code> not only does the decoding for us to our model structure (avoiding that unstructured collection returned by <code>JSONSerialization</code>), but it also converts all of those <code>yyyy.MM.dd</code> strings to <code>Date</code> instances for us. And for <code>completedDate</code>, our computed property takes care of that for us.</p>\n\n<hr>\n\n<p>By the way, I used the following <a href=\"https://dvsa.github.io/mot-history-api-documentation/\" rel=\"nofollow noreferrer\">sample JSON</a>:</p>\n\n<pre><code>[\n {\n \"registration\": \"ZZ99ABC\",\n \"make\": \"FORD\",\n \"model\": \"FOCUS\",\n \"firstUsedDate\": \"2010.11.13\",\n \"fuelType\": \"Petrol\",\n \"primaryColour\": \"Yellow\",\n \"vehicleId\": \"4Tq319nVKLz+25IRaUo79w==\",\n \"registrationDate\": \"2010.11.13\",\n \"manufactureDate\": \"2010.11.13\",\n \"engineSize\": \"1800\",\n \"motTests\":[\n {\n \"completedDate\": \"2013.11.03 09:33:08\",\n \"testResult\": \"PASSED\",\n \"expiryDate\": \"2014.11.02\",\n \"odometerValue\": \"47125\",\n \"odometerUnit\": \"mi\",\n \"odometerResultType\": \"READ\",\n \"motTestNumber\": \"914655760009\",\n \"rfrAndComments\": []\n },\n {\n \"completedDate\": \"2013.11.01 11:28:34\",\n \"testResult\": \"FAILED\",\n \"odometerValue\": \"47118\",\n \"odometerUnit\": \"mi\",\n \"odometerResultType\": \"READ\",\n \"motTestNumber\": \"841470560098\",\n \"rfrAndComments\":[\n {\n \"text\": \"Front brake disc excessively pitted (3.5.1h)\",\n \"type\": \"FAIL\",\n \"dangerous\": true\n },\n {\n \"text\": \"Nearside Rear wheel bearing has slight play (2.6.2)\",\n \"type\": \"ADVISORY\",\n \"dangerous\": false\n }\n ]\n },\n {\n \"completedDate\": \"2018.05.20 11:28:34\",\n \"testResult\": \"FAILED\",\n \"odometerValue\": \"57318\",\n \"odometerUnit\": \"mi\",\n \"odometerResultType\": \"READ\",\n \"motTestNumber\": \"741489560458\",\n \"rfrAndComments\":[\n {\n \"text\": \"Nearside Parking brake efficiency below requirements (1.4.2 (a) (i))\",\n \"type\": \"MAJOR\",\n \"dangerous\": false\n },\n {\n \"text\": \"Front brake disc excessively pitted (3.5.1h)\",\n \"type\": \"DANGEROUS\",\n \"dangerous\": false\n },\n {\n \"text\": \"tyres wearing unevenly\",\n \"type\": \"USER ENTERED\",\n \"dangerous\": true\n }\n ]\n }\n ]\n },\n {\n \"registration\": \"YY09DEF\",\n \"make\": \"BMW\",\n \"model\": \"Z4\",\n \"firstUsedDate\": \"2009.01.25\",\n \"fuelType\": \"Petrol\",\n \"primaryColour\": \"Green\",\n \"vehicleId\": \"3Fv916dPLGx=43PRaKa45e++\",\n \"registrationDate\": \"2009.01.25\",\n \"manufactureDate\": \"2009.01.25\",\n \"engineSize\": \"1800\",\n \"motTests\":[\n {\n \"completedDate\": \"2012.01.10 10:27:56\",\n \"testResult\": \"PASSED\",\n \"expiryDate\": \"2013.01.09\",\n \"odometerValue\": \"12345\",\n \"odometerUnit\": \"mi\",\n \"odometerResultType\": \"READ\",\n \"motTestNumber\": \"345655760009\",\n \"rfrAndComments\": []\n }\n ]\n }\n]\n</code></pre>\n\n<hr>\n\n<p>Needless to say, if you want to decode manually, like you did in your question, just have two parsing date formatters, one for the <code>yyyy.MM.dd</code> format and another for the <code>yyyy.MM.dd HH:mm:ss</code> format. </p>\n\n<hr>\n\n<p>Finally, you might ask “how do I show these <code>Date</code> objects in my UI?” </p>\n\n<p>You define UI date formatters:</p>\n\n<pre><code>let dateOnlyFormatter: DateFormatter = {\n let formatter = DateFormatter()\n formatter.dateStyle = .medium\n return formatter\n}()\n\nlet dateTimeFormatter: DateFormatter = {\n let formatter = DateFormatter()\n formatter.dateStyle = .medium\n formatter.timeStyle = .medium\n return formatter\n}()\n</code></pre>\n\n<p>Then you can do things like:</p>\n\n<pre><code>if let date = result.first?.motTests.first?.expiryDate {\n let string = dateOnlyFormatter.string(from: date)\n print(\"Expiry date:\", string)\n}\n</code></pre>\n\n<blockquote>\n <p>Expiry date: 2 Nov 2014</p>\n</blockquote>\n\n<p>And</p>\n\n<pre><code>if let date = result.first?.motTests.first?.completedDate {\n let string = dateTimeFormatter.string(from: date)\n print(\"Completed date:\", string)\n}\n</code></pre>\n\n<blockquote>\n <p>Completed date: 3 Nov 2013 at 9:33:08</p>\n</blockquote>\n\n<p>Clearly, use whatever <code>dateStyle</code> and <code>timeStyle</code> you want. But the idea is that we’ll show these strings in a nice, localized format as dictated by the user’s device settings.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T19:03:01.347", "Id": "233238", "ParentId": "233170", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T18:07:09.207", "Id": "233170", "Score": "2", "Tags": [ "swift" ], "Title": "Identify MOT Dates which could be in various formats" }
233170
<p>I made a function that outputs the sum of the value of each letter in a word. For example if I input hello my function would output 52.</p> <pre><code>def words_to_marks(s): import string values = {} # dictionary to store value of each alphabet values_of_words = [] # to store final value of words for index, letters in enumerate(string.ascii_lowercase, 1): # creates the dictionary values[letters] = index final = [] # stores value of each number before adding for letter in s: letter_lower = letter.lower final.append(values[letter]) # appends the value of each letter into the list values_of_words.append(sum(final)) # sums all the values in the list submit = str(values_of_words) # converts into string so I can remove the brackets around the list return submit[1:-1] test = words_to_marks("friends") print(test) </code></pre> <p>I would really appreciate it if someone could point me to the right direction for how I should condense or improve my code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T19:52:11.483", "Id": "455694", "Score": "3", "body": "Hello, you'll need to explain in your post how you map a letter to its numerical value, because there are a gazillion ways to do this :)" } ]
[ { "body": "<p>Honestly, the initial <code>words_to_marks</code> function is full of \"anti-patterns/bad smells\".</p>\n\n<p>When reviewing in steps:</p>\n\n<ul>\n<li><p>instead of iterating over <code>string.ascii_lowercase</code> and generating/filling a dictionary of letter indices on <strong>each</strong> function call with:</p>\n\n<pre><code>for index, letters in enumerate(string.ascii_lowercase, 1): # creates the dictionary\n values[letters] = index\n</code></pre>\n\n<p>create a predefined top-level dict <code>lowercase_indices_map</code> at once:</p>\n\n<pre><code>import string\n\nlowercase_indices_map = {c:i for i, c in enumerate(string.ascii_lowercase, 1)}\n</code></pre></li>\n<li><p>converting each letter of the word with:</p>\n\n<pre><code>for letter in s:\n letter_lower = letter.lower\n</code></pre>\n\n<p>is completely redundant as the whole word can be <em>lowercased</em> at once <code>s = s.lower()</code></p></li>\n<li><p>and the <em>\"magic\"</em> like:</p>\n\n<pre><code>values_of_words.append(sum(final)) # sums all the values in the list\nsubmit = str(values_of_words) # converts into string so I can remove the brackets around the list\nreturn submit[1:-1]\n</code></pre>\n\n<p>is just an unnecessary thing that you should avoid doing in future. The sum of letter indices is simply calculated with a single <code>sum(...)</code> call.</p></li>\n</ul>\n\n<hr>\n\n<p>The whole idea fits in few lines of code:</p>\n\n<pre><code>import string\n\nlowercase_indices_map = {c:i for i, c in enumerate(string.ascii_lowercase, 1)}\n\ndef sum_letters_indices(word):\n word = word.lower()\n return sum(lowercase_indices_map[char] for char in word)\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre><code>print(sum_letters_indices(\"hello\")) # 52\nprint(sum_letters_indices(\"friends\")) # 75\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:00:14.297", "Id": "233174", "ParentId": "233172", "Score": "3" } } ]
{ "AcceptedAnswerId": "233174", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T19:02:36.723", "Id": "233172", "Score": "0", "Tags": [ "python", "beginner" ], "Title": "Assigning a numerical value to each alphabet in corresponding order and then summing any inputted word" }
233172
<p>Is there a better way to write this code.<br> Suppose I have 10 files to delete and I have to repeat code (<code>public function destroy()</code> ) 10 times.</p> <ol> <li><strong>First remove the database entry</strong>. </li> <li><strong>List item, then remove the file</strong>.</li> </ol> <p>OOP - "don't repeat yourself", it works but I repeat the code.</p> <pre><code>public function image_path() { return $this-&gt;upload_dir .DS. $this-&gt;filename; } public function image_path2() { return $this-&gt;upload_dir .DS. $this-&gt;filename2; } public function destroy() { if($this-&gt;delete()) { $target_path = PUBLIC_PATH.DS.'public'.DS.$this-&gt;image_path(); return unlink($target_path) ? true : false; } else { return false; } } public function destroy2() { if($this-&gt;delete()) { $target_path2 = PUBLIC_PATH.DS.'public'.DS.$this-&gt;image_path2(); return unlink($target_path2) ? true : false; } else { return false; } } </code></pre> <p><strong>delete_photo.php</strong></p> <pre><code> // Delete photo $result = $photo-&gt;destroy(); $result = $photo-&gt;destroy2(); </code></pre> <p><strong>photo class</strong></p> <pre><code>public function delete() { global $database; $sql = "DELETE FROM " . self::$table_name . " "; $sql .= "WHERE id='" . $database-&gt;escape_value($this-&gt;id) . "' "; $sql .= "LIMIT 1"; $result = $database-&gt;query($sql); return $result; } protected static $db_fields=array('id', 'filename', 'filename2', 'type', 'type2','size', 'size2', 'caption'); public $id; public $filename; public $filename2; public $type; public $type2; public $size; public $size2; public $caption; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:46:27.383", "Id": "455702", "Score": "0", "body": "why do you have `$filename1` and `$filename2`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:46:51.463", "Id": "455703", "Score": "0", "body": "Could you post the schema as well" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T21:40:07.453", "Id": "455704", "Score": "0", "body": "`$filename1` and `$filename2` to upload 2 or more files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T21:42:29.760", "Id": "455705", "Score": "0", "body": "sql schema? -> id, caption, filename, filname2, size, size2, type, type2" } ]
[ { "body": "<p>Yes, clearly you should write D.R.Y. code by not writing multiple methods that perform the same task.</p>\n\n<p>You only need one <code>image_path()</code> and one <code>destroy()</code> method, it is the data delivery to those methods that needs to change and then of course the methods need to be altered to iterate the data.</p>\n\n<p>If you expect to be handing multiple files the same way, I recommend a class variable (array of filenames) which can be filled as necessary, then iterated by your methods.</p>\n\n<p>This mean doing away with:</p>\n\n<pre><code>public $filename;\npublic $filename2;\n</code></pre>\n\n<p>and instead use:</p>\n\n<pre><code>public $filenames = [];\n</code></pre>\n\n<p>A final note about reducing syntax:</p>\n\n<pre><code>if($this-&gt;delete()) {\n $target_path = PUBLIC_PATH.DS.'public'.DS.$this-&gt;image_path();\n return unlink($target_path) ? true : false;\n} else {\n return false;\n}\n</code></pre>\n\n<p>Can be rewritten as:</p>\n\n<pre><code>if (!$this-&gt;delete()) {\n return false;\n}\nreturn unlink(PUBLIC_PATH . DS . 'public' . DS . $this-&gt;image_path());\n</code></pre>\n\n<p>or even shorter if you prefer inline conditions:</p>\n\n<pre><code>return !$this-&gt;delete() ? false : unlink(PUBLIC_PATH . DS . 'public' . DS . $this-&gt;image_path());\n</code></pre>\n\n<p>That said, there is nothing wrong with <code>if</code> blocks, but your <code>? true : false</code> is unnecessary, I try to avoid declaring single-use variables, and I prefer to write failure / false / early returns before positive outcomes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T10:56:23.803", "Id": "233188", "ParentId": "233175", "Score": "3" } } ]
{ "AcceptedAnswerId": "233188", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:17:13.083", "Id": "233175", "Score": "4", "Tags": [ "php", "file" ], "Title": "Delete file from server (php function)" }
233175
<p>I am in the process of trying to teach myself Python, and am at a point where I feel some general feedback on my styling/code efficiency would be super useful in order for me to progress.</p> <p>I have created a simple banking system in order to practice OOP (which I am still finding a little confusing).</p> <p>Would anyone be able to offer advice on any simple Python mistakes I am making or rules I am breaking? For example - would it be better to pass through certain parameters with the methods, eg</p> <p><code>def create_account (self, name, deposit): ....</code></p> <p>Could someone also shed some light as to whether an Abstract Base Class is needed with this code (another concept I am struggling a little to understand)?</p> <p>Thanks in advance!</p> <pre><code>from random import randint class Bank (): def __init__ (self): self.savingsAccount = {} def create_account(self): self.name = input("Please input your full name: ") while True: try: self.deposit = int(input("Please input the amount of your initial deposit: ")) except: print("Please input a valid integer amount. ") else: print ("You have deposited £{}".format(self.deposit)) break self.accountno = ''.join(["{}".format(randint(0, 9)) for num in range(0, 5)]) print ("Your account number is {}.".format(self.accountno)) self.savingsAccount[self.name] = [self.accountno, self.deposit] def access_account(self): while True: self.name = input("Please input your full name: ") if self.name in self.savingsAccount.keys(): while True: self.accountno = input("Please enter your account number: ") if self.accountno == self.savingsAccount[self.name][0]: break else: print ("There is no such account number associated with this name.") break else: print ("We cannot find this name in our system.") def display_balance (self): print ("You currently have £{} in your account.".format(self.savingsAccount[self.name][1])) def withdraw_money (self): while True: try: withdraw = int(input("How much money would you like to withdraw?")) except ValueError: print ("This value must be an integer.") else: if withdraw &lt;= self.savingsAccount[self.name][1]: print ("You have successfully withdrawn £{}.".format(withdraw)) self.savingsAccount[self.name][1] -= withdraw self.display_balance() break else: print ("Sorry, you do not have enough money in your account.") def deposit_money (self): while True: try: deposit = int(input("How much money would you like to deposit?")) except ValueError: print ("This value must be an integer.") else: print ("You have successfully deposited £{}.".format(deposit)) self.savingsAccount[self.name][1] += deposit self.display_balance() break def user_choice1(): while True: choice1 = input("Enter 1 to create an account.\nEnter 2 to access an existing account.\nEnter 3 to exit.\n") if choice1 not in ["1", "2", "3"]: print ("Please enter 1, 2 or 3..") else: break return choice1 def user_choice2(): while True: choice2 = input("Enter 1 to display balance.\nEnter 2 to withdraw money.\nEnter 3 to deposit money.\nEnter 4 to return to the main menu.\n") if choice2 not in ["1", "2", "3", "4"]: print ("Please enter 1, 2, 3 or 4.") else: break return choice2 def previous_page (): while True: return input("Would you like to return to the previous page? Enter yes or no:")[0].lower() == 'y' print ("Welcome to the bank!") bank=Bank() while True: userchoice1 = user_choice1() if userchoice1 == "1": bank.create_account() if not previous_page(): break else: continue elif userchoice1 == "2": bank.access_account() while True: userchoice2 = user_choice2() if userchoice2 == "1": bank.display_balance() if not previous_page(): break else: continue elif userchoice2=="2": bank.withdraw_money() if not previous_page(): break else: continue elif userchoice2=="3": bank.deposit_money() if not previous_page(): break else: continue elif userchoice2=="4": break else: break print ("Thankyou for using the bank!") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T10:45:11.810", "Id": "455722", "Score": "3", "body": "(1) An abstract base class makes sense if you at least can imagine one or more siblings of Bank which all have some behavior or properties in common. (2) You should not number functions, use names like e. g. \"user_choice_main\" and \"user_choice_account\" instead." } ]
[ { "body": "<h3>Removing Duplication</h3>\n\n<p>There are several places in your program where you repeat the same logic for prompting the user to enter an <code>int</code>, and then ask them to retry if they type something invalid, this is a good opportunity to create a general function to handle that:</p>\n\n<pre><code>def read_int(prompt_msg, error_msg):\n while True:\n try:\n return int(input(prompt_msg))\n except ValueError:\n print(error_msg)\n</code></pre>\n\n<p>Which you could use in several places to eliminate the <code>while True</code> / <code>try</code> / <code>except</code> / <code>break</code> logic which occurs in several places, for example to simplify the <code>deposit_money</code> method:</p>\n\n<pre><code>def deposit_money (self):\n deposit = read_int(\"How much money would you like to deposit?\", \"This value must be an integer.\")\n</code></pre>\n\n<p>Even without the duplication of this logic, splitting the code to read an <code>int</code> and retry away into a separate function significantly reduces the complexity of the <code>deposit_money</code> method and makes the intent clearer</p>\n\n<h3>Separation of Concerns</h3>\n\n<p>Your <code>withdraw_money</code> method changes the balance available combines together the code for re-asking the user if they try to go overdrawn as well as changing the account balance - ideally a function should \"do one thing, and do it well\", so there's an opportunity to split the check-and-re-ask code into another function. For example:</p>\n\n<pre><code>def read_withdraw_amount(self):\n while True:\n withdraw = read_int(\"How much money would you like to withdraw?\", \"This value must be an integer.\")\n if withdraw &gt; self.balance:\n print(\"Sorry, you do not have enough money in your account.\")\n else:\n return withdraw\n\ndef withdraw_money(self):\n withdraw = self.read_withdraw_amount()\n print(\"You have successfully withdrawn £{}.\".format(withdraw))\n self.balance -= withdraw\n self.display_balance()\n</code></pre>\n\n<h3>Object Oriented Programming</h3>\n\n<blockquote>\n <p>I have created a simple banking system in order to practice OOP (which I am still finding a little confusing).</p>\n</blockquote>\n\n<p>It's not at all un-common to find OOP confusing as it's a subjective art at the best of times; I would try to approach it with the mindset of keeping the two core principles in-mind of <strong>High Cohesion</strong> and <strong>Loose Coupling</strong>, which to summarise in plain English is roughly this:</p>\n\n<ul>\n<li><strong>High Cohesion</strong> is about grouping together functions/methods and state/data which are conceptually very closely related to each other - for example, your <code>deposit</code> and <code>withdraw</code> methods are both very closely related to the concept of the balance of a single bank account since they both affect the balance of one account at a time. </li>\n<li><strong>Loose Coupling</strong> is about minimising the extent to which functions/methods and classes need to depend upon each other. For example, your <code>Bank</code> class contains a list of all accounts, yet the <code>deposit</code> and <code>withdraw</code> methods only affect a single account at any one time, so conceptually there's no need for those methods to have any link to a class which manages a whole list of accounts. </li>\n</ul>\n\n<blockquote>\n <p>Could someone also shed some light as to whether an Abstract Base Class is needed with this code (another concept I am struggling a little to understand)?</p>\n</blockquote>\n\n<p>Inheritance and Abstract Base Classes are among many different possible ways of allowing code reuse - so a typical reason to use it would be having multiple classes which would otherwise require copies of similar or the same methods/behaviour; an abstract base class might be a suitable tool for sharing/reusing that code between those classes,</p>\n\n<p>However, code reuse in this way should only happen where there's a very strong conceptual \"identity\" link between those classes. Inheritance implies tight coupling, so the relationship between a <em>derived</em> class and a <em>base</em> class should be that the derived class is a <strong>specialisation</strong> of that base class (i.e. the code in a derived class specialises or extends whatever exists in the base class). </p>\n\n<p>There are no hard-and-fast rules about whether or not to use inheritance, since it really all links back to whatever problem/concept/real-world-thing you're trying to model using classes in the first place. </p>\n\n<p>However, base classes aren't <em>needed</em> in any kind of strict sense; there are often better ways of writing Object-Oriented code without using inheritance or base classes at all. Inheritance implies <em>tight coupling</em> between a derived class and a base class, so it's something which should be used with caution, and often avoided. </p>\n\n<p>There are other ways to reuse code, including Composition, which tends to provide looser coupling, and still provides all the same opportunities for code reuse. Composition allows a class to hold a reference to an object of another class without being so tightly-coupled to it. </p>\n\n<h3>Introducing a SavingsAccount class</h3>\n\n<p>One way which you could improve the Coupling and Cohesion of your program could be to introduce a <code>SavingsAccount</code> class which is <em>decoupled</em> from the Bank class, responsible for all methods whose purpose is only to access or modify a single <code>SavingsAccount</code> at any one time. </p>\n\n<p>For example:</p>\n\n<pre><code>class SavingsAccount:\n def __init__(self, balance):\n # the Account Number and Balance are now named class variables\n self.account_no = ''.join([\"{}\".format(randint(0, 9)) for num in range(0, 5)])\n self.balance = balance\n\n def print_account_no(self):\n print(\"Your account number is {}.\".format(self.account_no))\n\n def display_balance (self):\n print(\"You currently have £{} in your account.\".format(self.balance))\n\n def read_withdraw_amount(self):\n while True:\n withdraw = read_int(\"How much money would you like to withdraw?\", \"This value must be an integer.\")\n if withdraw &gt; self.balance:\n print(\"Sorry, you do not have enough money in your account.\")\n else:\n return withdraw\n\n def withdraw_money(self):\n withdraw = self.read_withdraw_amount()\n print(\"You have successfully withdrawn £{}.\".format(withdraw))\n self.balance -= withdraw\n self.display_balance()\n\n def deposit_money (self):\n deposit = read_int(\"How much money would you like to deposit?\", \"This value must be an integer.\")\n print(\"You have successfully deposited £{}.\".format(deposit))\n self.balance += deposit\n self.display_balance()\n</code></pre>\n\n<p>Just a note on the <code>__init__</code> method:</p>\n\n<pre><code>def __init__(self, balance):\n self.account_no = ''.join([\"{}\".format(randint(0, 9)) for num in range(0, 5)])\n self.balance = balance\n</code></pre>\n\n<p>When a <code>SavingsAccount</code> object is created, this method will run, so the code which creates the object will need to provide the initial balance. like this:</p>\n\n<pre><code># Create a SavingsAccount object with £100 starting balance\naccount = SavingsAccount(100)\n</code></pre>\n\n<p>There's a few benefits here:</p>\n\n<ul>\n<li>the <code>account_no</code> and <code>balance</code> for a <code>SavingsAccount</code> have a strong name which makes their intent much more obvious. Previously those were \"magic\" numbers of <code>[1]</code> and <code>[0]</code>, so it had readability issues in needing the person reading the code to realise/remember the difference between 0 and 1</li>\n<li>Provides clean logical separation between the <code>Bank</code> and the <code>SavingsAccount</code> - the <code>SavingsAccount</code> class has no connections to the <code>Bank</code> at all, it's entirely self-contained. </li>\n<li>Methods such as <code>deposit_money</code> and <code>withdraw_money</code> are less \"noisy\" since they no longer need to pluck the account from a list belonging to the <code>Bank</code>.</li>\n</ul>\n\n<p>With that in mind, the <code>Bank</code> class gets a whole lot smaller, and is no longer concerned with code whose responsibility is around the state of individual accounts in the list. The Bank knows how to create a new account, and how to provide access to an existing account:</p>\n\n<pre><code>class Bank:\n def __init__ (self):\n self.savingsAccount: Dict[str, SavingsAccount] = {}\n\n def create_account(self):\n name = input(\"Please input your full name: \")\n deposit = read_int(\"Please input the amount of your initial deposit: \", \"Please input a valid integer amount. \")\n print(\"You have deposited £{}\".format(deposit))\n account = SavingsAccount(deposit)\n self.savingsAccount[name] = account\n account.print_account_no()\n\n def access_account(self):\n while True:\n name = input(\"Please input your full name: \")\n if name in self.savingsAccount.keys():\n account = self.savingsAccount[name]\n while True:\n account_no = input(\"Please enter your account number: \")\n if account.account_no == account_no:\n break\n else:\n print(\"There is no such account number associated with this name.\")\n break\n else:\n print(\"We cannot find this name in our system.\")\n return account\n</code></pre>\n\n<p>The relationship between <code>Bank</code> and <code>SavingsAccount</code> is one of <em>Composition</em> -- i.e. the <code>Bank</code> owns zero-or-more <code>SavingsAccount</code> objects.</p>\n\n<p>Note that any code which needs to access or modify the fields (variables) within a <code>SavingsAccount</code> object, such as printing the account number, is now part of that <code>SavingsAccount</code> class too. </p>\n\n<p>Since the account-specific methods are no longer part of <code>Bank</code>, the code which needs to work with those methods will need a <code>SavingsAccount</code> object, so the <code>access_account</code> method can return the <code>SavingsAccount</code> object from the list.</p>\n\n<p>Back to possible uses of inheritance: Perhaps if you decided to extend the program in future, there might be different variations on the <code>SavingsAccount</code> which the bank could own - e.g. maybe you would create a <code>PensionAccount</code> class which disallows someone from withdrawing any money since it's a deposit-only account -- in that case, it could indeed make sense to treat the <code>SavingsAccount</code> as a base class and inherit the <code>PensionAccount</code> from it then override the <code>withdraw</code> method. </p>\n\n<p>The menu code further down which handles Account-specific concerns such as letting the user display/deposit/withdraw are only concerned with a <code>SavingsAccount</code> object, which leads onto the next item:</p>\n\n<h3>Menu</h3>\n\n<ul>\n<li>There's a lot of duplication involving <code>previous_page()</code>, <code>break</code>, and <code>continue</code> which could be eliminated by re-structuring the logic slightly. </li>\n<li>There's no need for separate <code>userchoice1</code> and <code>userchoice2</code> variables - one variable is enough.</li>\n<li>The names of the <code>user_choice1()</code> and <code>user_choice2()</code> functions aren't very descriptive - try to use verbs with function names. The functions are for menu options related to either the Bank or the Account, so something like <code>do_bank_menu()</code> and <code>do_account_menu()</code> would be more insightful for someone reading the code. </li>\n<li><p>The account portion of the menu, now only concerned with accounts and not banks, would need a <code>SavingsAccount</code> object, which it can get from the <code>Bank</code> object:</p>\n\n<pre><code>elif user_choice == \"2\":\n account = bank.access_account()\n while True:\n user_choice = do_account_menu()\n if user_choice == \"1\":\n account.display_balance()\n elif user_choice == \"2\":\n account.withdraw_money()\n elif user_choice == \"3\":\n account.deposit_money()\n elif user_choice == \"4\":\n break\n else:\n continue\n\n if not previous_page():\n break\n</code></pre></li>\n</ul>\n\n<h3>Menu as a class</h3>\n\n<p>Classes aren't just for combining methods and data - classes are often good tools for grouping methods together without any data - all of the menu functions could be grouped together inside a <code>Menu</code> class. This allows the menu itself to be treated as a self-contained unit, and helps create further logical separation between different areas of your program. </p>\n\n<h3>Main</h3>\n\n<p>It's generally recommended to use a <code>main()</code> function in Python for some of the reasons explained here: <a href=\"https://stackoverflow.com/questions/4041238/why-use-def-main\">https://stackoverflow.com/questions/4041238/why-use-def-main</a></p>\n\n<h3>Putting it Together</h3>\n\n<p>Here's a code listing with those structural changes - <a href=\"https://repl.it/repls/FlawedJuniorShareware\" rel=\"noreferrer\">https://repl.it/repls/FlawedJuniorShareware</a></p>\n\n<pre><code>from typing import Dict\nfrom random import randint\n\n\ndef read_int(prompt_msg, error_msg):\n while True:\n try:\n return int(input(prompt_msg))\n except ValueError:\n print(error_msg)\n\n\nclass SavingsAccount:\n def __init__(self, balance):\n self.account_no = ''.join([\"{}\".format(randint(0, 9)) for num in range(0, 5)])\n self.balance = balance\n\n def print_account_no(self):\n print(\"Your account number is {}.\".format(self.account_no))\n\n def display_balance (self):\n print(\"You currently have £{} in your account.\".format(self.balance))\n\n def read_withdraw_amount(self):\n while True:\n withdraw = read_int(\"How much money would you like to withdraw?\", \"This value must be an integer.\")\n if withdraw &gt; self.balance:\n print(\"Sorry, you do not have enough money in your account.\")\n else:\n return withdraw\n\n def withdraw_money(self):\n withdraw = self.read_withdraw_amount()\n print(\"You have successfully withdrawn £{}.\".format(withdraw))\n self.balance -= withdraw\n self.display_balance()\n\n def deposit_money (self):\n deposit = read_int(\"How much money would you like to deposit?\", \"This value must be an integer.\")\n print(\"You have successfully deposited £{}.\".format(deposit))\n self.balance += deposit\n self.display_balance()\n\n\nclass Bank:\n def __init__ (self):\n self.savingsAccount: Dict[str, SavingsAccount] = {}\n\n def create_account(self):\n name = input(\"Please input your full name: \")\n deposit = read_int(\"Please input the amount of your initial deposit: \", \"Please input a valid integer amount. \")\n print(\"You have deposited £{}\".format(deposit))\n account = SavingsAccount(deposit)\n self.savingsAccount[name] = account\n account.print_account_no()\n\n def access_account(self):\n while True:\n name = input(\"Please input your full name: \")\n if name in self.savingsAccount.keys():\n account = self.savingsAccount[name]\n while True:\n account_no = input(\"Please enter your account number: \")\n if account.account_no == account_no:\n break\n else:\n print(\"There is no such account number associated with this name.\")\n break\n else:\n print(\"We cannot find this name in our system.\")\n return account\n\n\nclass BankMenu:\n def __init__(self, bank: Bank):\n self.bank = bank\n\n def do_bank_menu(self):\n while True:\n choice = input(\"Enter 1 to create an account.\\n\"\n \"Enter 2 to access an existing account.\\n\"\n \"Enter 3 to exit.\\n\")\n if choice not in [\"1\", \"2\", \"3\"]:\n print (\"Please enter 1, 2 or 3..\")\n else:\n return choice\n\n def do_account_menu(self):\n while True:\n choice = input(\"Enter 1 to display balance.\\n\"\n \"Enter 2 to withdraw money.\\n\"\n \"Enter 3 to deposit money.\\n\"\n \"Enter 4 to return to the main menu.\\n\")\n if choice not in [\"1\", \"2\", \"3\", \"4\"]:\n print (\"Please enter 1, 2, 3 or 4.\")\n else:\n break\n return choice\n\n def previous_page(self):\n while True:\n return input(\"Would you like to return to the previous page? Enter yes or no:\")[0].lower() == 'y'\n\n def run(self):\n print(\"Welcome to the bank!\")\n while True:\n user_choice = self.do_bank_menu()\n if user_choice == \"1\":\n self.bank.create_account()\n if not self.previous_page():\n break\n elif user_choice == \"2\":\n account = self.bank.access_account()\n while True:\n user_choice = self.do_account_menu()\n if user_choice == \"1\":\n account.display_balance()\n elif user_choice == \"2\":\n account.withdraw_money()\n elif user_choice == \"3\":\n account.deposit_money()\n elif user_choice == \"4\":\n break\n else:\n continue\n\n if not self.previous_page():\n break\n else:\n break\n\n\ndef main():\n print(\"Welcome to the bank!\")\n bank = Bank()\n bank_menu = BankMenu(bank)\n bank_menu.run()\n print(\"Thankyou for using the bank!\")\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-04T15:17:27.180", "Id": "456249", "Score": "1", "body": "Thanks so much for this detailed and informative answer - highly appreciated!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T12:58:10.503", "Id": "233191", "ParentId": "233176", "Score": "5" } } ]
{ "AcceptedAnswerId": "233191", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:18:46.793", "Id": "233176", "Score": "6", "Tags": [ "python", "object-oriented" ], "Title": "Looking for general feedback on Python OOP banking project" }
233176
<p><strong>UPDATE:</strong> Current best state of a solution incorporating feedback and further development is in <a href="https://codereview.stackexchange.com/a/233292/212940">this answer</a>. </p> <p>Review on this Design#2 please: </p> <p>Simple wrapper class template for <code>std::map</code> for the purpose of "retaining insertion order". This is quite a frequently asked question, <a href="https://stackoverflow.com/questions/2266179/c-stl-map-i-dont-want-it-to-sort/2267198">here</a> and <a href="https://stackoverflow.com/questions/35053544/keep-the-order-of-unordered-map-as-we-insert-a-new-key/59100306#59100306">here</a>.</p> <p>This is the follow on 2nd Design of a solution for <a href="https://codereview.stackexchange.com/questions/233157/wrapper-class-template-for-stdmap-stdlist-to-provide-a-sequencedmap-which">this original question</a>.</p> <p>Code is still a bit rough, but it implements the new strategy:</p> <ol> <li>Basically a <code>std::map&lt;KeyT,ValueT&gt;</code></li> <li>But the <code>ValueT</code> is wrapped in a struct which hold prev/next pointers to make a doubly linked list</li> <li>These pointers are maintained on insertion and deletion</li> <li>Thus rudimentary iteration in original insertion order is possible (to be improved -- input wanted on best way to do that)</li> </ol> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;list&gt; #include &lt;map&gt; #include &lt;random&gt; #include &lt;string&gt; #include &lt;vector&gt; template &lt;class KeyT, class ValueT&gt; struct SequencedMapValue; template &lt;class KeyT, class ValueT&gt; class SequencedMap { using MapT = std::map&lt;KeyT, SequencedMapValue&lt;KeyT, ValueT&gt;&gt;; using MapItT = typename MapT::iterator; using MapValT = typename MapT::value_type; public: template &lt;class K, class V&gt; std::pair&lt;MapItT, bool&gt; insert_or_assign(const K&amp; key, V&amp;&amp; value) { const auto map_it = map.find(key); if (map_it != map.end()) { map_it-&gt;second.v = value; return {map_it, false}; } SequencedMapValue&lt;KeyT, ValueT&gt; s(std::forward&lt;V&gt;(value)); MapValT pair = std::make_pair(std::move(key), std::move(s)); const auto ins_res = map.insert(std::move(pair)); auto [elem_it, was_new] = ins_res; if (tail) { tail-&gt;second.next = &amp;*elem_it; elem_it-&gt;second.prev = tail; tail = &amp;*elem_it; } else { tail = &amp;*elem_it; head = tail; } return ins_res; } MapItT find(const KeyT&amp; key) const { return map.find(key); } ValueT&amp; operator[](const KeyT&amp; key) { const auto map_it = map.find(key); if (map_it == map.end()) throw std::logic_error( "Warning! You are trying to create a SequencedMap entry using [] operator. Use " "insert_or_assign for safety!"); return map_it-&gt;second.v; } MapItT erase(const KeyT&amp; key) { const auto map_it = map.find(key); if (map_it != map.end()) { // close gap in ptrs if (!map_it-&gt;second.next) { // last one tail = map_it-&gt;second.prev; map_it-&gt;second.prev-&gt;second.next = nullptr; } else if (!map_it-&gt;second.prev) { // this is head head = map_it-&gt;second.next; map_it-&gt;second.next-&gt;second.prev = nullptr; } else { // somewhere in the middle map_it-&gt;second.prev-&gt;second.next = map_it-&gt;second.next; map_it-&gt;second.next-&gt;second.prev = map_it-&gt;second.prev; } } return map.erase(map_it); } const MapT&amp; getMap() const { return map; } MapValT* const ibegin() const { return head; } const MapValT* const cibegin() const { return head; } private: MapT map; MapValT* tail = nullptr; MapValT* head = nullptr; }; template &lt;class KeyT, class ValueT&gt; struct SequencedMapValue { using MapT = std::map&lt;KeyT, SequencedMapValue&lt;KeyT, ValueT&gt;&gt;; using MapValT = typename MapT::value_type; template &lt;class V&gt; SequencedMapValue(V&amp;&amp; v_) : v{std::forward&lt;V&gt;(v_)} {} ValueT v; MapValT* next = nullptr; MapValT* prev = nullptr; }; // EOF class: Rest is demo usage code template &lt;class KeyT, class ValueT&gt; void print_in_insertion_order(const SequencedMap&lt;KeyT, ValueT&gt;&amp; smap) { auto curr = smap.ibegin(); while (curr) { std::cout &lt;&lt; curr-&gt;first &lt;&lt; " -&gt; " &lt;&lt; curr-&gt;second.v &lt;&lt; "\n"; curr = curr-&gt;second.next; } } template &lt;class KeyT, class ValueT&gt; void print_in_map_order(const SequencedMap&lt;KeyT, ValueT&gt;&amp; smap) { for (auto&amp; pair: smap.getMap()) { std::cout &lt;&lt; pair.first &lt;&lt; " -&gt; " &lt;&lt; pair.second.v &lt;&lt; "\n"; } } int main() { using Key = std::string; using Value = int; SequencedMap&lt;Key, Value&gt; smap; // arbitrary ad-hoc temporary structure for the data (for demo purposes only) std::cout &lt;&lt; "insert data...\n"; for (auto p: std::vector&lt;std::pair&lt;Key, Value&gt;&gt;{ {"Mary", 10}, {"Alex", 20}, {"Johnny", 30}, {"Roman", 40}, {"Johnny", 50}}) { smap.insert_or_assign(p.first, p.second); } print_in_insertion_order(smap); std::cout &lt;&lt; "\nsorted by key\n"; print_in_map_order(smap); std::cout &lt;&lt; "\nretrieve by known key\n"; auto key = "Alex"; std::cout &lt;&lt; key &lt;&lt; " -&gt; " &lt;&lt; smap["Alex"] &lt;&lt; "\n"; std::cout &lt;&lt; "\nchange value by known key: Johnny++\n"; ++smap["Johnny"]; print_in_insertion_order(smap); std::cout &lt;&lt; "\ndelete by known key: Johnny\n"; smap.erase("Johnny"); print_in_insertion_order(smap); } </code></pre> <p>I struggle in <code>insert_or_assign()</code> with all the "universal references" and different template params apparently doing "the same thing". I sprinkled some <code>std::move</code> and <code>std::forward</code>, and made it compile and work, but I am sure it's not right.</p> <p>I also struggled breaking the recursive template Type params and Type aliases between <code>SequencedMap</code> and <code>SequencedMapValue</code>. It works without <code>static_cast</code>ing from <code>void*</code> now, but there is probably a better way. I need help on how to do the iterators cleanly.</p> <p>--</p> <p>The benchmark (separate code) has been filled out more as well, and it looks good compared to the original design. No more slow deletes. Really on average about the same as <code>std::map</code> (except, insertion ~35% slower). Compiled on clang-8 -std=C++17 -O3.</p> <pre class="lang-none prettyprint-override"><code>SequencedMap: insert 100,000=81.4451ms SequencedMap: iterate in insertion order=0.844402ms SequencedMap: Check sum=4990318 SequencedMap: modify 100,000 in insertion order=0.871902ms SequencedMap: iterate in insertion order=0.792979ms SequencedMap: Check sum=5090318 SequencedMap: delete 10,000=6.52532ms SequencedMap: iterate in insertion order=0.83679ms SequencedMap: Check sum=4581601 Map: insert 100,000=59.9917ms Map: iterate in map order=3.19841ms Map: Check sum=4990318 Map: modify 100,000 in map order=18.3977ms Map: iterate in map order=3.66884ms Map: Check sum=5090318 Map: delete 10,000=4.3003ms Map: iterate in map order=2.59503ms Map: Check sum=4581601 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T17:17:59.110", "Id": "455753", "Score": "1", "body": "What is MKII, it is not clear what the code does from the description?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T18:47:14.957", "Id": "455756", "Score": "0", "body": "@pacmaninbw Sorry, I mean \"Design Version #2\" I have edited the text to make that clearer. Basic challenge is to have an associative C++ container (eg `std::map` or `std::unordered_map`) which retains the order in which pairs were inserted; ie you can iterate it in the original insertion order -- this is not normally the case for std::(unordered)_map.." } ]
[ { "body": "<p>OK, in the interest of not inventing wheels, I tried boost::multi_index. Took half an hour to get over their approach, type syntax and their API. </p>\n\n<p>But it's actually really good. Very flexible, very performant. And not that verbose for reasonable real world cases. It all seems a bit C++03, but that doesn't actually get in the way. In fact if you use modern features \"like <code>auto</code> you can avoid some of the very verbose <code>typename .... ::value_type</code> type syntax, see below</p>\n\n<p>Code does something similar to my code above (ie simple map with an additional \"linked-list\" sequence index) but using boost::multi_index:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;boost/multi_index/member.hpp&gt;\n#include &lt;boost/multi_index/ordered_index.hpp&gt;\n#include &lt;boost/multi_index/sequenced_index.hpp&gt;\n#include &lt;boost/multi_index_container.hpp&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;string&gt;\n\nusing boost::multi_index_container;\nusing namespace boost::multi_index;\n\nstruct Pair {\n std::string key;\n int value;\n\n Pair(std::string key_, int value_) : key(key_), value(value_) {}\n\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Pair&amp; p) {\n os &lt;&lt; p.key &lt;&lt; \" -&gt; \" &lt;&lt; p.value &lt;&lt; \"\\n\";\n return os;\n }\n};\n\nstruct key {};\n\ntypedef multi_index_container&lt;\n Pair, indexed_by&lt;sequenced&lt;&gt;, ordered_unique&lt;tag&lt;key&gt;, member&lt;Pair, std::string, &amp;Pair::key&gt;&gt;&gt;&gt;\n PairContainer;\n\ntemplate &lt;typename Tag, typename MIC&gt; void print_out_by(const MIC&amp; mic) {\n auto&amp; i = get&lt;Tag&gt;(mic);\n std::copy(i.begin(), i.end(), std::ostream_iterator&lt;typename MIC::value_type&gt;(std::cout));\n}\n\nint main() {\n\n PairContainer ps;\n ps.push_back(Pair(\"Johnny\", 10));\n ps.push_back(Pair(\"Alex\", 20));\n ps.push_back(Pair(\"Barty\", 30));\n ps.push_back(Pair(\"Zoe\", 40));\n ps.push_back(Pair(\"Vaughan\", 50));\n\n int sum = 0;\n for (auto it = ps.begin(); it != ps.end(); ++it) {\n sum += it-&gt;value;\n }\n std::cout &lt;&lt; sum &lt;&lt; \"\\n\";\n {\n const auto&amp; i = get&lt;key&gt;(ps);\n for (auto it = i.begin(); it != i.end(); ++it) {\n std::cout &lt;&lt; *it;\n }\n }\n std::cout &lt;&lt; sum &lt;&lt; \"\\n\";\n {\n for (auto it = ps.begin(); it != ps.end(); ++it) {\n std::cout &lt;&lt; *it;\n }\n }\n return 0;\n}\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T10:07:57.923", "Id": "233185", "ParentId": "233177", "Score": "4" } }, { "body": "<p>Never call <code>map.erase(map.end())</code>. Doing so is undefined.</p>\n\n<p>There are some simple tricks for linked lists to avoid special-cases:</p>\n\n<p>Define your own type for the links (prev and next), instead of letting loose pointers rattle around everywhere.</p>\n\n<p>Also, arrange for a special value which on assignment does nothing:</p>\n\n<pre><code>struct links {\n links() = default;\n constexpr links(char) noexcept {}\n constexpr links&amp; operator=(char) noexcept { return *this; }\n links *prev = this;\n links *next = this;\n};\n\nstd::map&lt;KeyT, std::pair&lt;links, ValueT&gt;&gt; map;\nlinks order;\n\nvoid linkit(links&amp; x) noexcept {\n x.next = order;\n order.prev-&gt;next = &amp;x;\n x.prev = order.prev;\n order.prev = &amp;x;\n}\n\nvoid unlinkit(links&amp; x) noexcept {\n x.prev-&gt;next = x.next;\n x.next-&gt;prev = x.prev;\n}\n\ndecltype(*map.begin())&amp; fromlink(links&amp; x) noexcept {\n auto&amp; y = *map.begin();\n const auto offset = (char*)&amp;y-&gt;second.first - (char*)y;\n return (decltype(y)&amp;)((char*)&amp;x - offset);\n}\n\ntemplate &lt;class K, class V&gt;\nstd::pair&lt;MapItT, bool&gt; insert_or_assign(const K&amp; key, V&amp;&amp; value) {\n auto r = map.insert_or_assign(key, std::pair&lt;char, V&amp;&amp;&gt;(\n '\\0', std::forward&lt;V&gt;(value)));\n if (r.second)\n linkit(r.first-&gt;second.first);\n return r;\n}\n\nValueT&amp; operator[](const KeyT&amp; key) {\n auto&amp; x = map[key];\n if (!x.first.prev)\n linkit(x.first);\n return x.second;\n}\n\nsize_type erase(const KeyT&amp; key) {\n const auto p = map.find(key);\n if (p == map.end())\n return 0;\n unlinkit(p-&gt;second.first);\n map.erase(p);\n return 1;\n}\n</code></pre>\n\n<p>Beware: All code is untested.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T02:26:58.137", "Id": "455761", "Score": "0", "body": "Thx. Need to look at your code more and try to run it. Good call on map.erase: that was a clear UB bug. \n\nTrying to get it to compile and understand it now. Currentl getting a wall of errors on insert_or_assign which make no sense to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T15:44:31.913", "Id": "455905", "Score": "0", "body": "I dropped a ctor, added that. Also added mapping from links to whole element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T16:55:41.570", "Id": "455918", "Score": "0", "body": "Ok. That's funny. That looks much like \"workaround\" i made up. But better. ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T20:27:10.653", "Id": "455957", "Score": "0", "body": "Complete working code below: https://codereview.stackexchange.com/a/233292/212940\nBetter?!\nInsertion order iteration API still bad. Suggestions welcome." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T20:37:22.233", "Id": "455958", "Score": "0", "body": "Sure. Provide a function returning a view on the list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T21:29:31.637", "Id": "455962", "Score": "0", "body": "Hah. Might go with a couple of iterators first! Map order and insertion order! BTW i didn't use `decltype(*map.begin())` as you did a couple of times. I used using/typedefs. I presume it would be safe to do it your way because the type is resolved at compile time and we are not de-referencing a .end() iterator (in case of empty map)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T07:34:44.947", "Id": "455992", "Score": "0", "body": "While reviewing I decided I am not so keen on std::pair. The whole .first .second is highly unsemantic. So I think I might merge ideas and use a map -> valueStruct -> linksStruct. Then add iterators Will update below." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T22:41:21.820", "Id": "233210", "ParentId": "233177", "Score": "3" } }, { "body": "<p>Integrating all the pieces. Quite nice now? Faster insert than my version at top (less branches I think!). </p>\n\n<p>See below for state and history:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;map&gt;\n#include &lt;string&gt;\n#include &lt;type_traits&gt;\n#include &lt;vector&gt;\n\ntemplate &lt;class KeyT, class ValueT&gt;\nclass SequencedMap {\n // needed by std::map::operator[]\n static_assert(std::is_default_constructible_v&lt;ValueT&gt;, \"ValueT must be DefaultConstructible\");\n static_assert(std::is_default_constructible_v&lt;KeyT&gt;, \"KeyT must be CopyConstructible\");\n\n struct Links;\n struct Value;\n\npublic:\n using MapT = std::map&lt;KeyT, Value&gt;;\n using MapItT = typename MapT::iterator;\n using MapValT = typename MapT::value_type;\n\n template &lt;class K, class V&gt; // re-template to allow perfect forwarding\n std::pair&lt;MapItT, bool&gt; insert_or_assign(const K&amp; key, V&amp;&amp; value) {\n auto insert_result = map.insert_or_assign(key, Value(std::forward&lt;V&gt;(value)));\n auto&amp; [elem_ptr, was_new] = insert_result;\n if (was_new) linkit(elem_ptr-&gt;second.links);\n return insert_result;\n }\n\n ValueT&amp; operator[](const KeyT&amp; key) {\n auto&amp; e = map[key];\n if (e.links.prev == e.links.next &amp;&amp; e.links.next != &amp;ends) linkit(e.links);\n return e.value;\n }\n\n std::size_t erase(const KeyT&amp; key) {\n const auto p = map.find(key);\n if (p == map.end()) return 0;\n unlinkit(p-&gt;second.links);\n map.erase(p);\n return 1;\n }\n\n // TODO: this shouldn't be public!\n const MapT&amp; getMap() const { return map; }\n\n // is this portable? How dodgy to reinterpret_cast from a pair to this?\n struct MapExtValT {\n KeyT first;\n ValueT second;\n // Links _dummy_;\n };\n\n class Iterator {\n public:\n using value_type = MapExtValT;\n using difference_type = std::ptrdiff_t;\n using pointer = MapExtValT*;\n using reference = MapExtValT&amp;;\n using iterator_category = std::bidirectional_iterator_tag;\n\n Iterator(SequencedMap&lt;KeyT, ValueT&gt;* m_, Links* curr_) : map(m_), curr(curr_) {}\n\n reference operator*() { return map-&gt;fromlink(*curr); }\n pointer operator-&gt;() { return &amp;(map-&gt;fromlink(*curr)); }\n\n // clang-format off\n Iterator&amp; operator++() { curr = curr-&gt;next; return *this; }\n Iterator&amp; operator--() { curr = curr-&gt;prev; return *this; }\n // clang-format on\n\n bool operator!=(const Iterator&amp; o) const { return curr != o.curr; }\n bool operator==(const Iterator&amp; o) const { return curr == o.curr; }\n\n private:\n SequencedMap&lt;KeyT, ValueT&gt;* map;\n Links* curr;\n };\n\n Iterator begin() { return Iterator(this, head); }\n Iterator end() { return Iterator(this, &amp;ends); }\n\nprivate:\n MapT map;\n\n Links ends;\n Links*&amp; head = ends.next;\n Links*&amp; tail = ends.prev;\n\n struct Links {\n Links* prev = this;\n Links* next = this;\n\n Links() = default;\n Links(const Links&amp;) = default;\n Links(Links&amp;&amp;) = default;\n\n // NOP copy/move asignment because it would break ptrs\n Links&amp; operator=(Links&amp;) noexcept { return *this; }\n Links&amp; operator=(Links&amp;&amp;) noexcept { return *this; }\n };\n\n struct Value { // Could be just a std::pair. This is cleaner\n // default cstr needed for std::map::operator[]\n Value() = default;\n\n Value(ValueT&amp; v) : value{v} {}\n\n ValueT value;\n Links links;\n };\n\n MapExtValT&amp; fromlink(Links&amp; x) const noexcept {\n // MSVC 2019 balks at this assert Clang 8 passes it, but MSVC apparently runs fine anyway\n static_assert(std::is_standard_layout_v&lt;MapValT&gt;, \"MapValT must have StandardLayout\");\n return *reinterpret_cast&lt;MapExtValT*&gt;(reinterpret_cast&lt;std::byte*&gt;(&amp;x) -\n offsetof(MapValT, second.links));\n }\n\n void linkit(Links&amp; x) noexcept {\n x.next = &amp;ends;\n tail-&gt;next = &amp;x;\n x.prev = tail;\n tail = &amp;x;\n }\n\n void unlinkit(Links&amp; x) noexcept {\n x.prev-&gt;next = x.next;\n x.next-&gt;prev = x.prev;\n }\n\n};\n\n// EOF class: Rest is demo usage code\n\ntemplate &lt;class KeyT, class ValueT&gt;\nvoid print_in_insertion_order(SequencedMap&lt;KeyT, ValueT&gt;&amp; smap) {\n for (auto&amp; pair: smap) {\n std::cout &lt;&lt; pair.first &lt;&lt; \" -&gt; \" &lt;&lt; pair.second &lt;&lt; \"\\n\";\n }\n}\n\ntemplate &lt;class KeyT, class ValueT&gt;\nvoid print_in_map_order(const SequencedMap&lt;KeyT, ValueT&gt;&amp; smap) {\n for (auto&amp; pair: smap.getMap()) {\n std::cout &lt;&lt; pair.first &lt;&lt; \" -&gt; \" &lt;&lt; pair.second.value &lt;&lt; \"\\n\";\n }\n}\n\nint main() {\n using Key = std::string;\n using Value = int;\n SequencedMap&lt;Key, Value&gt; smap;\n\n // arbitrary ad-hoc temporary structure for the data (for demo purposes only)\n\n for (auto p: std::vector&lt;std::pair&lt;Key, Value&gt;&gt;{\n {\"Mary\", 10},\n {\"Alex\", 20},\n {\"Johnny\", 40},\n {\"Roman\", 40},\n {\"Johnny\", 50},\n }) {\n smap.insert_or_assign(p.first, p.second);\n }\n std::cout &lt;&lt; \"\\nsorted by map\\n\";\n print_in_map_order(smap);\n\n std::cout &lt;&lt; \"\\nsorted by insert\\n\";\n print_in_insertion_order(smap);\n\n std::cout &lt;&lt; \"\\nretrieve by known key\\n\";\n auto key = \"Alex\";\n smap[key];\n ++smap[key];\n print_in_insertion_order(smap);\n\n std::cout &lt;&lt; \"\\nchange value by known key: Johnny++\\n\";\n ++smap[\"Johnny\"];\n print_in_insertion_order(smap);\n\n std::cout &lt;&lt; \"\\nchange value for new key: NewGuy++\\n\";\n ++smap[\"NewGuy\"];\n print_in_insertion_order(smap);\n\n std::cout &lt;&lt; \"\\ndelete by known key: Johnny\\n\";\n smap.erase(\"Johnny\");\n print_in_insertion_order(smap);\n\n}\n</code></pre>\n\n<p><strong>EDIT</strong> (4th Dec 2019): </p>\n\n<ol>\n<li>Refactored code above.</li>\n<li>Helper classes for \"inner Value\" and \"links\" now inner classes. Reducing public interface.</li>\n<li>No longer using char('0') \"hack/trick\" to prevent change of Links ptrs upon assignment to existing map-key (was deemed too confusing). Using proper \"no-op\" move/copy assignment operators on <code>Links</code> now. </li>\n<li>static_asserts for type restrictions</li>\n<li>better \"tests\"</li>\n</ol>\n\n<p><strong>EDIT</strong> (4th Dec 2019 #2): </p>\n\n<ol start=\"6\">\n<li><p>Added Iterator for the \"insertion order\". works well with external ranged for loop. </p></li>\n<li><p>There is an interesting \"reinterpret_cast\" to <code>MapExtvalIt</code> which hides the <code>Links</code> member and gives the external user something that looks like a normal map <code>std::pair</code>. Neat. Good perf. But how portable is that?</p></li>\n<li><p>Not clear how to present the other iterator (ie the normal sorted map order). mbeing() and mend() ? that won't work with \"ranged for\"? </p></li>\n</ol>\n\n<p>Benchmark:</p>\n\n\n\n<pre class=\"lang-none prettyprint-override\"><code>SequencedMap: insert 100,000=99.8293ms\nSequencedMap: iterate in insertion order=0.849751ms\nSequencedMap: Check sum=4990318\nSequencedMap: modify 100,000 in insertion order=0.964927ms\nSequencedMap: iterate in insertion order=0.914365ms\nSequencedMap: Check sum=5090318\nSequencedMap: delete 10,000=7.02706ms\nSequencedMap: iterate in insertion order=0.821281ms\nSequencedMap: Check sum=4581601\nMap: insert 100,000=83.5828ms\nMap: iterate in map order=6.86609ms\nMap: Check sum=4990318\nMap: modify 100,000 in map order=28.0204ms\nMap: iterate in map order=7.2687ms\nMap: Check sum=5090318\nMap: delete 10,000=7.07613ms\nMap: iterate in map order=5.52114ms\nMap: Check sum=4581601\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T20:25:03.327", "Id": "233292", "ParentId": "233177", "Score": "1" } } ]
{ "AcceptedAnswerId": "233210", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-29T20:26:11.173", "Id": "233177", "Score": "4", "Tags": [ "c++", "template-meta-programming", "stl" ], "Title": "SequencedMap which retains insertion order - Design#2" }
233177
<p>I've started learning Rust recently using the Rust book.</p> <p>In one of the chapters, the authors encourage the reader to experiment with closures, and try to create a <a href="https://doc.rust-lang.org/book/ch13-01-closures.html#limitations-of-the-cacher-implementation" rel="noreferrer">generic cache implementation</a>.</p> <p>I've managed to get it working as below. However, it irks me that I need to add Clone trait on the input argument in the get() method. I was wondering if there was a better way of doing this?</p> <p>Any other comments are also welcome (apart from the main() method which is a sample driver).</p> <pre><code>use std::collections::HashMap; use std::thread; use std::time::Duration; use std::hash::Hash; use std::clone::Clone; struct Cache&lt;T, U, W&gt; where T: Fn(U) -&gt; W, U: Eq + Hash + Clone { calculator: T, values: HashMap&lt;U, W&gt;, } impl&lt;T, U, W&gt; Cache&lt;T, U, W&gt; where T: Fn(U) -&gt; W, U: Eq + Hash + Clone { fn new(calculator: T) -&gt; Cache&lt;T, U, W&gt; { Cache { calculator, values: HashMap::new(), } } /* * The ugliest part in this function is the constraint that we have to clone the input. * HashMap::entry() moves the key, which renders it unusable for subsequent calculations. * So we can either * - always perform the expensive computation * (OR) * - clone the input so that it can be re-used later * * Another problem is that defining a closure in or_insert_with borrows the Cache::calculator, and that creates a problem * when we attempt to borrow it again by invoking self.calculator. This is why the following line won't work: * self.values.entry(input.clone()).or_insert_with(|| { (self.calculator)(input) }) */ fn get(&amp;mut self, input: U) -&gt; &amp;W { let calc = &amp;self.calculator; self.values.entry(input.clone()).or_insert_with(|| { (calc)(input) }) } } fn main() { println!("Hello, world!"); let mut c = Cache::new(|x: &amp;str| { println!("performing an expensive calculation with input: {}", x); thread::sleep(Duration::from_secs(2)); format!("Original input: {}", x) }); let x = c.get("10"); println!("x: {}, cacher after getting {}", x, 10); let x = c.get("10"); println!("x: {}, cacher after getting {}", x, 10); let x = c.get("20"); println!("x: {}, cacher after getting {}", x, 20); let x = c.get("10"); println!("x: {}, cacher after getting {}", x, 10); let x = c.get("10"); println!("x: {}, cacher after getting {}", x, 10); let x = c.get("20"); println!("x: {}, cacher after getting {}", x, 20); } </code></pre>
[]
[ { "body": "<p>You don't need to have the <code>where</code> clause on your struct. General, rust coders prefer to only restrict the <code>impl</code> blocks and not the structs.</p>\n\n<p>You can avoid Clone, by unpacking the Entry enum, like so:</p>\n\n<pre><code>fn get(&amp;mut self, input: U) -&gt; &amp;W {\n use std::collections::hash_map::Entry;\n match self.values.entry(input) {\n Entry::Occupied(entry) =&gt; entry.into_mut(),\n Entry::Vacant(entry) =&gt; {\n let value = (self.calculator)(entry.key());\n entry.insert(value)\n }\n }\n} \n</code></pre>\n\n<p>This is, in fact, close to how <code>or_insert_with</code> is implemented. </p>\n\n<p>Note that this calls the function with <code>&amp;U</code> not <code>U</code>. Your calculator cannot take ownership of the key if you also plan to put into the hashmap. This is awkward for your code because it is using &amp;str as the keys. Hence the type passed to the calculator is &amp;&amp;str. We can resolve this by using the borrow trait. The Borrow traits knows that it can convert &amp;&amp;str to &amp;str, so we could implement it as follows.</p>\n\n<pre><code>// Leave the struct unconstrained\nstruct Cache&lt;T, U, W&gt; {\n calculator: T,\n values: HashMap&lt;U, W&gt;,\n}\n\n// The impl block only constrains for Eq + Hash of the keys.\nimpl&lt;T, U, W&gt; Cache&lt;T, U, W&gt;\n where \n U: Eq + Hash\n {\n\n fn new(calculator: T) -&gt; Cache&lt;T, U, W&gt; {\n Cache {\n calculator,\n values: HashMap::new(),\n }\n }\n\n // We take a new type parameter, Y.\n // The calculation function takes &amp;Y as a parameter\n // It does not need to be sized because we only use references to it. \n fn get&lt;Y:?Sized&gt;(&amp;mut self, input: U) -&gt; &amp;W \n where \n // Our calculator must take a reference to Y.\n T: Fn(&amp;Y) -&gt; W,\n // The borrow trait will let us convert a &amp;U to a &amp;Y\n U: std::borrow::Borrow&lt;Y&gt; {\n use std::collections::hash_map::Entry;\n match self.values.entry(input) {\n Entry::Occupied(entry) =&gt; entry.into_mut(),\n Entry::Vacant(entry) =&gt; {\n let value = (self.calculator)(entry.key().borrow());\n entry.insert(value)\n }\n }\n } \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T20:04:03.383", "Id": "455809", "Score": "0", "body": "Do we need the Borrow trait though? It appears the program works even if we constrain the T: Fn(&U) -> W, and just pass in entry.key() as a reference to self.calculator? I'm trying to understand if introducing the Borrow trait is somehow better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T00:51:21.723", "Id": "455834", "Score": "0", "body": "@skittish, if you do that, you'll find that closure passed to `Cache::new` in your main function has to take a `&&str` parameter rather than the more natural `&str`. `Borrow` just gives the trait a bit more flexibility in what parameter it takes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T23:14:35.777", "Id": "455966", "Score": "0", "body": "Ah! Sorry, I think I misunderstood your comment in the answer about the Borrow trait. Thank you for the answer and the clarification." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T15:56:45.187", "Id": "233199", "ParentId": "233181", "Score": "6" } } ]
{ "AcceptedAnswerId": "233199", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T00:46:37.270", "Id": "233181", "Score": "6", "Tags": [ "rust" ], "Title": "Cache implementation in Rust" }
233181
<p>I have written a matrix class using python, allowing me to perform a variety of operations on matrices. I'm pretty happy with how it performs, and everything works fine. However, I feel like the way I've handled the initialiser could be much improved.</p> <p>I wasn't sure how to handle different possible cases for the arguments passed to the <code>__init__</code> method, due to the lack of multiple constructors. I want to at least support the creation of a matrix from a list of lists, or the number of rows and columns. What I ended up going with was using <code>isinstance()</code> to check if the arguments are of a certain type, and handle each case that way.</p> <p>Would it be better to use different class methods for each case, or is an approach similar to my own using <code>isinstance()</code> considered appropriate?</p> <p>I would also appreciate a general overview of the class, to see what aspects of it could be improved.</p> <pre><code>from copy import deepcopy class MatrixError(Exception): """An exception class for Matrix""" pass class Matrix: matrix = [] def __init__(self, *args): if len(args) == 1: if isinstance(args[0], Matrix): self.matrix = deepcopy(args[0].matrix) self.rows = len(self.matrix) self.cols = len(self.matrix[0]) elif isinstance(args[0], list): self.rows = len(args[0]) self.cols = len(args[0][0]) if all(map(lambda x: len(x) == self.cols, args[0])): self.matrix = deepcopy(args[0]) else: raise MatrixError("Uneven columns") else: raise MatrixError("Expected Matrix, list, or int * int") elif len(args) == 2): if isinstance(args[0], int) and isinstance(args[1], int): self.rows = args[0] self.cols = args[1] self.matrix = [[0] * args[1] for row in range(args[0])] else: raise MatrixError("Expected Matrix, list, or int * int") else: raise MatrixError("Expected Matrix, list, or int * int") @classmethod def identity(cls, size): new_matrix = cls(size, size) for i in range(size): new_matrix[i][i] = 1 return new_matrix def __str__(self): return str(self.matrix) def __getitem__(self, key): return self.matrix[key] def __eq__(self, other): if isinstance(other, Matrix): if self.rows != other.rows: return False # They don't have the same dimensions, they can't be equal # Test if all rows are equal return all(map(lambda rows: rows[0] == rows[1], zip(self.matrix, other.matrix))) else: return False def __ne__(self, other): return not self.__eq__(other) # Check for equality and reverse the result def __pos__(self): return self def __neg__(self): return -1 * self def __add__(self, other): new_matrix = Matrix(self.rows, self.cols) if isinstance(other, Matrix): if (self.rows == other.rows) and (self.cols == other.cols): for row in range(self.rows): for column in range(self.cols): new_matrix[row][column] = self[row][column] + other[row][column] else: raise MatrixError("Can't add or subtract %d x %d matrix with %d x %d matrix" % (self.rows, self.cols, other.rows, other.cols)) else: return NotImplemented return new_matrix def __sub__(self, other): return self + (other * -1) def __mul__(self, other): if isinstance(other, (int, float, complex)): new_matrix = Matrix(self.rows, self.cols) for row in range(self.rows): for col in range(self.cols): new_matrix[row][col] = self[row][col] * other elif isinstance(other, Matrix): if self.cols == other.rows: new_matrix = Matrix(self.rows, other.cols) for row in range(self.rows): for col in range(other.transpose().rows): value = 0 for i in range(self.cols): value += self[row][i] * other[i][col] new_matrix[row][col] = value else: raise MatrixError("Can't multiply (%d, %d) matrix with (%d, %d) matrix" % (self.rows, self.cols, other.rows, other.cols)) else: return NotImplemented return new_matrix def __rmul__(self, other): return self.__mul__(other) def transpose(self): new_matrix = Matrix(self.cols, self.rows) for row in range(self.rows): for col in range(self.cols): new_matrix[col][row] = self[row][col] return new_matrix def is_square(self): return self.rows == self.cols def minor_matrix(self, remove_row, remove_col): new_matrix_array = [row[:remove_col] + row[remove_col + 1:] for row in (self[:remove_row] + self[remove_row + 1:])] return Matrix(new_matrix_array) def determinant(self): if self.is_square(): # base case for 2x2 matrix if self.rows == 2: return self[0][0] * self[1][1] - self[0][1] * self[1][0] determinant = 0 for col in range(self.cols): determinant += ((-1) ** col) * self[0][col] * self.minor_matrix(0, col).determinant() return determinant else: raise MatrixError("Determinant only defined for square matrices") def inverse(self): if self.is_square(): determinant = self.determinant() if determinant == 0: raise MatrixError("Matrix is singular") # special case for 2x2 matrix: if self.rows == 2: return [[self[1][1] / determinant, -1 * self[0][1] / determinant], [-1 * self[1][0] / determinant, self[0][0] / determinant]] # find matrix of minors minors = Matrix(self.rows, self.cols) for row in range(self.rows): for col in range(self.cols): minor = self.minor_matrix(row, col) minors[row][col] = ((-1) ** (row + col)) * minor.determinant() t_minors = minors.transpose() for row in range(t_minors.rows): for col in range(t_minors.cols): t_minors[row][col] /= determinant return t_minors else: raise MatrixError("Inverse only defined for square matrices") </code></pre>
[]
[ { "body": "<p>Just a quick reminder before we get started: In case you want to do anything serious with matrices in Python, consider using the <a href=\"https://numpy.org/\" rel=\"nofollow noreferrer\">NumPy</a> library instead of roling your own matrix class. NumPy is the de-facto standard when it comes to numeric operations in Python and is in the general case (very likely much) faster than anything you write yourself. It's always the loops that get you in the end ;-)</p>\n\n<hr>\n\n<h1>Overall feedback</h1>\n\n<p>Your code looks quite good from an overall point of you regarding style and layout. The <code>Matrix</code> class would profit from further documentation using <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>, such as the one you have started to use on <code>MatrixError</code>. This is especially important when you have methods/constructors that accept <code>*args</code>. Without proper documentation, everything that remains for someone else but you would be to read the code or get it working by trial and error.</p>\n\n<h1>Class interface</h1>\n\n<p>I would consider declaring <code>self.matrix</code> as \"private\"/internal by prefixing it with an <code>_</code> to discourage user to directly interact with the inner data representation of your class. To allow changing the data, consider also implementing <code>__setitem__</code> for your class. Having classmethods to construct special matrices is quite a common approach, e.g. used by the C++ libraries Eigen (e.g. <code>MatrixXf::Identity</code>) and OpenCV (e.g. <code>Mat::eye</code>). NumPy on the other hand has them as top-level module functions (e.g <code>np.identity</code>). You'll have to decide what's your preferred way to go.</p>\n\n<h1>The constructor</h1>\n\n<p>The \"copy\" constructor looks a little bit odd to me. Why would you bother using <code>self.rows = len(self.matrix)</code> and <code>self.cols = len(self.matrix[0])</code> when the other matrix should have the attributes properly set? Dont't you trust your own implementation? ;-)</p>\n\n<p>The same error message is repeated three times in the constructor. Under the assumption you wouldn't want to have a zero-sized matrix (no rows, no cols, no data), removing them and checking</p>\n\n<pre><code>if not self.matrix:\n raise MatrixError(\"Expected Matrix, list, or int * int\")\n</code></pre>\n\n<p>at the end will help you to reduce the duplication here. Maybe also use <code>None</code> instead of <code>[]</code> as default value of <code>self.matrix</code> and then check for <code>if self.matrix is None:</code>.</p>\n\n<p>I'm also not entirely sure <code>\"int * int\"</code> gets the message across to possible users, so that they really understand what they are supposed to provide to the constructor.</p>\n\n<h1>Reduce nesting</h1>\n\n<p>Some of your methods like <code>__eq__</code>, <code>__add__</code>, <code>determinant</code>, <code>inverse</code> perform input validation and raise an exception if the input is not valid. You can reduce the level of nesting in that case if you return early. So instead of </p>\n\n<pre><code>def determinant(self):\n if self.is_square():\n ... # do the actual work\n else:\n raise MatrixError(\"Determinant only defined for square matrices\")\n</code></pre>\n\n<p>do</p>\n\n<pre><code>def determinant(self):\n if self.is_square():\n raise MatrixError(\"Determinant only defined for square matrices\")\n ... # do the actual work\n</code></pre>\n\n<p>This helps to reduce the needed level of indentation and makes it clearer what happens when the condition is violated.</p>\n\n<h1>String formatting</h1>\n\n<p>A more modern approach to generate the error message in <code>__add__</code> and <code>__mul__</code> would either be to use <code>.format(...)</code> (Python 2, Python 3) or f-strings (Python 3.6+):</p>\n\n<pre><code># .format(...)\nMatrixError(\n \"Can't multiply ({}, {}) matrix with ({}, {}) matrix\".format(\n self.rows, self.cols, other.rows, other.cols\n )\n)\n\n# f-string\nMatrixError(\n f\"Can't add or subtract {self.rows} x {self.cols} matrix \"\n f\"with {other.rows} x {other.cols} matrix\"\n)\n</code></pre>\n\n<h1>Performance</h1>\n\n<p>The implementation of <code>__sub__</code> is computationally wasteful, since you have to iterate over all the rows and columns twice. Although it does not get rid of that problem, you can also implement this using your <code>__neg__</code> as <code>-other + self</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T10:09:56.090", "Id": "233186", "ParentId": "233182", "Score": "2" } }, { "body": "<h1>A typo</h1>\n\n<p><code>elif len(args) == 2):</code> closes an unopened parenthesis.</p>\n\n<h1>An unnecessary transpose</h1>\n\n<p>In <code>__mul__</code>, this seems strange:</p>\n\n<blockquote>\n <p><code>for col in range(other.transpose().rows):</code></p>\n</blockquote>\n\n<p>This would transpose the <code>other</code> matrix lots of times, just to access the row count of the transposes. Why not:</p>\n\n<pre><code>for col in range(other.cols):\n</code></pre>\n\n<h1>Slow inverse and determinant</h1>\n\n<p>The cofactor expansion algorithm works well for small matrixes, but suffers <em>severe</em> performance degradation as the matrix grows. The time complexity of cofactor expansion is O(n!), that really limits the ability to work with matrixes beyond \"tiny\", the biggest I could go without running out of patience was 8x8. Both the determinant and the inverse (if it exists) can be found in O(n³) time by LU-factoring the matrix.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:09:39.147", "Id": "233190", "ParentId": "233182", "Score": "3" } } ]
{ "AcceptedAnswerId": "233186", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T00:48:37.917", "Id": "233182", "Score": "6", "Tags": [ "python", "python-3.x", "matrix" ], "Title": "General matrix class" }
233182
<p>This fasm x64 (Linux) code seems very crude and repetitive, but it gets the job done. How could I perform this task in a more idiomatic manner?</p> <pre><code>format ELF64 executable 3 segment readable executable entry $ prompt_user: mov edx,prompt_len lea rsi,[prompt] ;&lt;------ String mov edi,1 ; STDOUT mov eax,1 ; sys_write syscall get_user_input: mov rax, 0 ; sys_read mov rdi, 0 ; STDIN lea rsi, [bit_string] ; &lt;----- defined memory location mov rdx, 2 ; &lt;---- # of chars to read syscall ;DEBUG CODE: ;lea rax, [bit_string] ;mov [rax], byte 'A' ;mov [rax+1], byte 'B' lea rax, [bit_string] cmp [rax], byte '0' je load_0 cmp [rax], byte '1' je load_1 cmp [rax], byte '2' je load_2 cmp [rax], byte '3' je load_3 cmp [rax], byte '4' je load_4 cmp [rax], byte '5' je load_5 cmp [rax], byte '6' je load_6 cmp [rax], byte '7' je load_7 cmp [rax], byte '8' je load_8 cmp [rax], byte '9' je load_9 cmp [rax], byte 'A' je load_A cmp [rax], byte 'B' je load_B cmp [rax], byte 'C' je load_C cmp [rax], byte 'D' je load_D cmp [rax], byte 'E' je load_E cmp [rax], byte 'F' je load_F load_0: lea rsi, [n0] jmp print_nibble load_1: lea rsi, [n1] jmp print_nibble load_2: lea rsi, [n2] jmp print_nibble load_3: lea rsi, [n3] jmp print_nibble load_4: lea rsi, [n4] jmp print_nibble load_5: lea rsi, [n5] jmp print_nibble load_6: lea rsi, [n6] jmp print_nibble load_7: lea rsi, [n7] jmp print_nibble load_8: lea rsi, [n8] jmp print_nibble load_9: lea rsi, [n9] jmp print_nibble load_A: lea rsi, [nA] jmp print_nibble load_B: lea rsi, [nB] jmp print_nibble load_C: lea rsi, [nC] jmp print_nibble load_D: lea rsi, [nD] jmp print_nibble load_E: lea rsi, [nE] jmp print_nibble load_F: lea rsi, [nF] jmp print_nibble nibble_two: lea rax, [bit_string] cmp [rax+1], byte '0' je load_0 cmp [rax+1], byte '1' je load_1 cmp [rax+1], byte '2' je load_2 cmp [rax+1], byte '3' je load_3 cmp [rax+1], byte '4' je load_4 cmp [rax+1], byte '5' je load_5 cmp [rax+1], byte '6' je load_6 cmp [rax+1], byte '7' je load_7 cmp [rax+1], byte '8' je load_8 cmp [rax+1], byte '9' je load_9 cmp [rax+1], byte 'A' je load_A cmp [rax+1], byte 'B' je load_B cmp [rax+1], byte 'C' je load_C cmp [rax+1], byte 'D' je load_D cmp [rax+1], byte 'E' je load_E cmp [rax+1], byte 'F' je load_F print_intro: mov edx,intro_len lea rsi,[intro] mov edi,1 ; STDOUT mov eax,1 ; sys_write syscall ret print_nibble: cmp [position], 0 ; If were on first iter, then print intro jne skip_intro push rsi call print_intro pop rsi skip_intro: mov rax, 1 cmp al, [position] jl go_out mov edx, 4 mov edi,1 ; STDOUT mov eax,1 ; sys_write syscall add [position], 1 jmp nibble_two go_out: mov edx,1 lea rsi,[nl] mov edi,1 ; STDOUT mov eax,1 ; sys_write syscall xor edi,edi ; exit code 0 mov eax,60 ; sys_exit syscall segment readable writeable prompt db 'Enter a byte in the format: F6', 0xA prompt_len = $ - prompt nl db 0xA intro db 'In binary: ', 0 intro_len = $ - intro bit_string rb 2 position db 0 n0 db '0000', 0 n1 db '0001', 0 n2 db '0010', 0 n3 db '0011', 0 n4 db '0100', 0 n5 db '0101', 0 n6 db '0110', 0 n7 db '0111', 0 n8 db '1000', 0 n9 db '1001', 0 nA db '1010', 0 nB db '1011', 0 nC db '1100', 0 nD db '1101', 0 nE db '1110', 0 nF db '1111', 0 </code></pre>
[]
[ { "body": "<p>In a high-level language, I would write it as:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def put_nibble(buf: array[byte], n: int):\n buf[0] = '0' + ((n shr 3) bitand 1)\n buf[1] = '0' + ((n shr 2) bitand 1)\n buf[2] = '0' + ((n shr 1) bitand 1)\n buf[3] = '0' + ((n shr 0) bitand 1)\n\ndef char_to_nibble(ch: byte) -&gt; int:\n if '0' &lt;= ch &lt;= '9': return ch\n ch = ch bitor 0x20 # convert to lowercase\n if 'a' &lt;= ch &lt;= 'z': return ch - 'a' + 10\n error\n\ndef byte_to_binary(b: str):\n buf = byte[8] # reserve memory on the stack\n hi = char_to_nibble(b[0])\n put_nibble(buf, hi)\n lo = char_to_nibble(b[1])\n put_nibble(but + 4, lo)\n sys_write(1, buf, 8)\n</code></pre>\n\n<p>This way you avoid comparing each possible digit on its own.</p>\n\n<p>The above code also reduces memory access to the memory on the stack, since it doesn't need any external strings for the bit patterns.</p>\n\n<p>Sure, the <code>put_nibble</code> code looks a bit repetitive, but you can merge all the <code>'0' + …</code> together into a single addition:</p>\n\n<pre><code>add dword [buf], 0x30303030 ; 0x30 == '0'\n</code></pre>\n\n<p>You could also compute the buffer for a whole nibble in a register and then write it to memory in a single instruction:</p>\n\n<pre><code>; input: al = the nibble to print\n; output: ebx = 4 bytes ASCII buffer containing the 4 binary digits\nxor ebx, ebx\n\nrcr al, 1\nadc ebx, '0'\nrol ebx, 8\n\nrcr al, 1\nadc ebx, '0'\nrol ebx, 8\n\nrcr al, 1\nadc ebx, '0'\nrol ebx, 8\n\nrcr al, 1\nadc ebx, '0'\nrol ebx, 8\n\nmov [buf], ebx\n</code></pre>\n\n<p>Once you have translated the above high-level code into assembler, you probably want to optimize the code a bit. Or just use a compiler to do the heavy work for you. Write your code in C or in Go, assemble it into machine code and look at the result. Some keywords for searching:</p>\n\n<ul>\n<li>go tool objdump</li>\n<li>gcc -S binary.c -O2</li>\n</ul>\n\n<p>By the way, you should not place the string literals for the prompt and the bit patterns in a <code>writeable</code> segment since they are not intended to be overwritten by any part of your program.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:00:25.927", "Id": "233189", "ParentId": "233183", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T04:56:49.437", "Id": "233183", "Score": "4", "Tags": [ "strings", "converting", "assembly", "unit-conversion" ], "Title": "fasm convert hex byte to binary string" }
233183
<p>I have two buttons </p> <p>1) Chat button <br> 2) Annotation Button </p> <p>On tap each view comes from bottom and when tap outside view hidden back (Please refer the screen shot)</p> <p><a href="https://i.stack.imgur.com/OaJvd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OaJvd.png" alt="enter image description here"></a></p> <p>On tap On annotation </p> <p><a href="https://i.stack.imgur.com/DDpJm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DDpJm.png" alt="enter image description here"></a></p> <p>On tap on Chat </p> <p><a href="https://i.stack.imgur.com/Y92Hm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y92Hm.png" alt="enter image description here"></a></p> <p>To Handle This I have created following classes </p> <p>//Annotaion Card</p> <pre><code>struct CardInfo { enum CardState { case expanded case collpased } enum CardType { case annotaion case chat } var cardType:CardType var caardHandleHeight:CGFloat var cardState:CardState = .collpased var nextState : CardState { return cardState == .expanded ? .collpased : .expanded } mutating func updateToNextState() { cardState = nextState } } class CardHandler { var cardInfo:CardInfo private(set) unowned var viewController : UIViewController var cardHeight:CGFloat { switch self.cardInfo.cardType { case .annotaion: return UIDevice().userInterfaceIdiom == .pad ? UIScreen.main.bounds.height * 0.4 : 300 case .chat: return UIDevice().userInterfaceIdiom == .pad ? UIScreen.main.bounds.height * 0.4 : 400 } } var isExpanded:Bool { return cardInfo.cardState == .expanded } init (viewController:UIViewController,info:CardInfo) { self.viewController = viewController self.cardInfo = info } } </code></pre> <p>In My Main View Controller I have created two properties </p> <pre><code>lazy var annotationCard = CardHandler(viewController: AnnotaionListViewController.viewController(), info: CardInfo(cardType: .annotaion, caardHandleHeight: 0)) lazy var chatCard = CardHandler(viewController: ChatViewController.viewController(), info: CardInfo(cardType: .chat, caardHandleHeight: 0)) </code></pre> <p>And Add as Child View Controller </p> <pre><code>func setupCardView() { visualEffectView = UIVisualEffectView(frame: self.view.bounds) visualEffectView.effect = UIBlurEffect() visualEffectView.isUserInteractionEnabled = false self.view.addSubview(visualEffectView) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissCardView)) visualEffectView.addGestureRecognizer(tapGesture) // Add Annotaion View to current class let annotationVC = self.annotationCard.viewController as! AnnotaionListViewController annotationVC.closeAction = { self.createAnimation(card:self.annotationCard, duration: 0.45) } annotationVC.annotaionSelected = { annotaion in self.btnAnnotaion.setImage(annotaion.image, for: .normal) self.selfSession.selectedAnnotaionType = annotaion self.createAnimation(card:self.annotationCard, duration: 0.45) } self.addChild(annotationVC) self.view.addSubview(annotationVC.view) annotationVC.view.frame = CGRect(x:0,y:self.view.frame.height - self.annotationCard.cardInfo.caardHandleHeight,width:self.view.frame.width,height:self.annotationCard.cardHeight) annotationVC.view.clipsToBounds = true // Add Chat View to current class let chatVC = self.chatCard.viewController as! ChatViewController self.addChild(chatVC) self.view.addSubview(chatVC.view) chatVC.view.frame = CGRect(x:0,y:self.view.frame.height - self.chatCard.cardInfo.caardHandleHeight,width:self.view.frame.width,height:self.chatCard.cardHeight) chatVC.view.clipsToBounds = true } // called when tap gesture on Visual effect view @objc func dismissCardView() { self.view.endEditing(true) if self.chatCard.isExpanded { self.createAnimation(card: self.chatCard, duration: 0.45) } else if self.annotationCard.isExpanded { self.createAnimation(card: self.annotationCard, duration: 0.45) } } </code></pre> <p>Now On On tap on button action </p> <pre><code>@IBAction func btnAnnotationTapped(_ sender: Any) { self.createAnimation(card:self.annotationCard, duration: 0.45) } @IBAction func btnChatTapped(_ sender: Any) { self.createAnimation(card:self.chatCard, duration: 0.45) } </code></pre> <p>Here is method to animate </p> <pre><code>var animations:[UIViewPropertyAnimator] = [] func createAnimation(card:CardHandler,duration:TimeInterval) { guard animations.isEmpty else { print("Animation not empty") return } let viewController = card.viewController print("array count",self.animations.count) let cardMoveUpAnimation = UIViewPropertyAnimator.init(duration: duration, dampingRatio: 1.0) { [weak self] in guard let `self` = self else {return} switch card.cardInfo.nextState { case .collpased: viewController.view.frame.origin.y = self.view.frame.height - card.cardInfo.caardHandleHeight case .expanded: viewController.view.frame.origin.y = self.view.frame.height - card.cardHeight } } cardMoveUpAnimation.addCompletion { [weak self] _ in self?.animations.removeAll() if card.cardInfo.nextState == .expanded { self?.view.gestureRecognizers?.map{$0.isEnabled = false} self?.isDrawingEnable = false self?.visualEffectView.isUserInteractionEnabled = true } else { self?.view.gestureRecognizers?.map{$0.isEnabled = true} self?.visualEffectView.isUserInteractionEnabled = false self?.isDrawingEnable = true } card.cardInfo.updateToNextState() } cardMoveUpAnimation.startAnimation() animations.append(cardMoveUpAnimation) let cornerRadiusAnimation = UIViewPropertyAnimator(duration: duration, curve: .linear) { [weak self] in switch card.cardInfo.nextState { case .expanded: viewController.view.layer.cornerRadius = 12 case .collpased: viewController.view.layer.cornerRadius = 0 } } cornerRadiusAnimation.startAnimation() animations.append(cornerRadiusAnimation) let visualEffectAnimation = UIViewPropertyAnimator.init(duration: duration, curve: .linear) { [weak self ] in switch card.cardInfo.nextState { case .expanded: let blurEffect = UIBlurEffect(style: .dark) self?.visualEffectView.effect = blurEffect case .collpased: self?.visualEffectView.effect = nil } } visualEffectAnimation.startAnimation() animations.append(visualEffectAnimation) } </code></pre> <p>I can see there are many issues in code handling &amp; scalability How Can I improve this coding </p> <p>Please provide suggestions and correction you are seeing in the code</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:53:57.850", "Id": "455732", "Score": "0", "body": "_\"I can see there are many issues how I have handle this\"_ Can you [edit] your question please and name these _issues_ specifically." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:55:54.963", "Id": "455733", "Score": "0", "body": "@πάνταῥε What should I name it ? **I can see there are many issues how I have handle this** ? isn't this too long ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T11:57:25.827", "Id": "455735", "Score": "0", "body": "@πάνταῥεῖ No My code is working fine !! , I want best solution to handle this" } ]
[ { "body": "<p>A few big picture observations: </p>\n\n<ul>\n<li><p>You really shouldn’t have this much animation code in your view controller.</p>\n\n<p>For example, rather than using view controller containment, I might do a “modal” presentation with a <code>modalPresentationStyle</code> of <code>.overCurrentContext</code>. That gets you out the child view controller containment code. And you can move your animation code into an animator object (see WWDC 2013 video <a href=\"https://developer.apple.com/videos/play/wwdc2013/218/\" rel=\"nofollow noreferrer\">Custom Transitions Using View Controllers</a>). You’ll end up with a radically simplified view controller.</p>\n\n<p>When you first do this, it’s going to seem complicated because you’ll be dealing with all sorts of objects with which you are likely unfamiliar, but when you’re done, you’ll end up with an implementation that abstracts the details of how the presentation is performed out of this parent view controller. All of this will be incorporated into specific, animation-related objects and is in keeping with the single responsibility principle.</p>\n\n<p>Anyway, when you’re done, the parent view controller will just be presenting and dismissing the view controllers associated with these two popup views.</p></li>\n<li><p>The annotation view feels a bit like a keyboard. So it begs the question of whether a proper keyboard might be more appropriate implementation. See <a href=\"https://stackoverflow.com/a/57244936/1271826\">https://stackoverflow.com/a/57244936/1271826</a>. Then you get the standard keyboard appearance and disappearance UI for free.</p>\n\n<p>It’s a bit hard to say in this scenario, because we’re not seeing what is shown in the parent view controller and the interaction between these popup views and the main scene, but it’s something to consider.</p></li>\n</ul>\n\n<p>And now, a bunch of tactical observations:</p>\n\n<ol>\n<li><p>I’d rename:</p>\n\n<ul>\n<li><code>CardState.collpased</code> to be <code>.collapsed</code>.</li>\n<li><code>CardType.annotaion</code> to <code>.annotation</code>.</li>\n<li><code>annotationVC.annotaionSelected</code> to <code>.annotationSelected</code></li>\n<li><code>caardHandleHeight</code> to <code>cardHandleHeight</code></li>\n<li><code>selectedAnnotaionType</code> to <code>selectedAnnotationType</code></li>\n<li><code>AnnotaionListViewController</code> to <code>AnnotationListViewController</code></li>\n</ul></li>\n<li><p>You have a lot of unnecessary <code>self</code> references. I’d personally remove all of them except where they’re absolutely needed (e.g. closures and <code>init</code> methods). This eliminates cruft from your code. It also has the virtue of bringing the <code>self</code> references into stark relief. This prompts us to then more clearly reason about whether you really want strong references or <code>weak</code>/<code>unowned</code> references (see next point). But if you have unnecessary <code>self</code> references all over the place, these sorts of issues don’t jump out at you like they might otherwise.</p></li>\n<li><p>In your closures, use <code>weak</code> or <code>unowned</code> references (such as in <code>annotationVC.closeAction</code> or <code>annotationVC.annotationSelected</code>) because you are likely introducing strong reference cycles. A child object should not have any strong references to the parent.</p></li>\n<li><p>You don’t need the quotes in:</p>\n\n<pre><code>guard let self = self else { return }\n</code></pre></li>\n<li><p>Consider:</p>\n\n<pre><code>self?.view.gestureRecognizers?.map { $0.isEnabled = false }\n</code></pre>\n\n<p>You really should use <code>forEach</code>. We use <code>map</code> for transforming a sequence of objects into other objects, whereas <code>forEach</code> is for performing a block of code for each. Clearly we’re not performing any transformation here, so <code>forEach</code> is appropriate.</p></li>\n<li><p>If this view containment survives your rewrite, make sure to call <a href=\"https://developer.apple.com/documentation/uikit/uiviewcontroller/1621405-didmove\" rel=\"nofollow noreferrer\"><code>didMove(toParent:)</code></a> when you’re done adding the subview:</p>\n\n<pre><code>addChild(chatVC)\nview.addSubview(chatVC.view)\nchatVC.view.frame = ...\nchatVC.view.clipsToBounds = true\nchatVC.didMove(toParent: self) // add this line\n</code></pre>\n\n<p>As the <a href=\"https://developer.apple.com/documentation/uikit/uiviewcontroller/1621405-didmove\" rel=\"nofollow noreferrer\">documentation</a> says:</p>\n\n<blockquote>\n <p>If you are implementing your own container view controller, it must call the <code>didMove(toParent:)</code> method of the child view controller after the transition to the new controller is complete ...</p>\n</blockquote></li>\n<li><p>Make sure you’re in the right coordinate system. When adding a subview, you set its <code>frame</code> relative to its superview’s <code>bounds</code> (not the superview’s <code>frame</code>). Often you won’t see problems because a view’s <code>frame</code> and <code>bounds</code> might be the the same or similar enough in most scenarios, but (a) in certain cases it can cause problems; and (b) it suggests a conceptual misunderstanding of coordinate systems.</p></li>\n<li><p>You have a line that says:</p>\n\n<pre><code>return UIDevice().userInterfaceIdiom == .pad ? UIScreen.main.bounds.height * 0.4 : 300\n</code></pre>\n\n<p>A couple of problems here:</p>\n\n<ul>\n<li><p>I think you mean <code>UIDevice.current</code> not <code>UIDevice()</code>.</p></li>\n<li><p>You shouldn’t rely on <code>UIScreen.main</code> as you have no assurance that the current view is taking up the whole height of the screen.<br />&nbsp;</p></li>\n</ul>\n\n<p>Bottom line, you should do you calculations based upon the view height and you should respond to size changes (e.g. in <code>layoutSubviews</code> of <code>UIView</code> subclass or in <code>viewDidLayoutSubviews</code> in view controller). Or, better, use constraints instead of manipulating frame settings manually.</p></li>\n<li><p>I personally wouldn’t round the bottom corners of your presented views (with the black background showing through in the lower corners). Sure, on the top it’s fine, but on the bottom it sort of breaks the sliding-from-the-bottom visual metaphor.</p></li>\n<li><p>Very minor observation, but I’m not sure why <code>AnnotationListViewController</code> and <code>ChatViewController</code> have static <code>viewController</code> method, rather than just using <code>init</code> (e.g. <code>ChatViewController()</code>). It’s not a big deal, but seems curious. </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T18:13:04.653", "Id": "455799", "Score": "0", "body": "**For example, rather than using view controller containment, I might do a “modal” presentation with a modalPresentationStyle of .overCurrentContext.** --> I am using ARKit (black background in screenshot). So I have paused the session on view will disappear and resume on appears , and annotations are more frequently used so I don't want to use present view controller" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T18:15:03.460", "Id": "455800", "Score": "0", "body": "**When you first do this, it’s going to seem complicated because you’ll be dealing with all sorts of objects with which you are likely unfamiliar...** I am sorry I didn't get this point , Could you please explain this ? Do i need to update structure ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T18:18:01.953", "Id": "455801", "Score": "0", "body": "**Very minor observation, but I’m not sure why AnnotationListViewController and ChatViewController have static viewController method, rather than just using init (e.g. ChatViewController()). It’s not a big deal, but seems curious** --> This will return particular view controller instantiate from stroyboard" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T18:21:18.640", "Id": "455802", "Score": "0", "body": "“I am using ARKit (black background in screenshot). So I have paused the session on view will disappear and resume on appears , and annotations are more frequently used so I don't want to use present view controller” ... I don’t understand: When you present over the current context and don’t cover the whole context, the effect is identical to what you have here (you still see the view behind where your new view doesn’t cover it)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T18:23:48.780", "Id": "455803", "Score": "0", "body": "“Could you please explain this [custom modal transitions]?” ... See [that video](https://developer.apple.com/videos/play/wwdc2013/218/) that I reference. It walks you through the issues. Or see https://stackoverflow.com/a/42213998/1271826 or many other S.O. answers about “UIViewController custom transition”." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T17:45:23.110", "Id": "233233", "ParentId": "233187", "Score": "2" } }, { "body": "<p>I would move more logic to an Enum CardInfo</p>\n\n<pre><code>struct CardInfo {\n\n enum CardState {\n case expanded\n case collapased\n\n var nextState : CardState {\n return isExpanded ? .collapased : .expanded\n }\n\n var isExpanded: Bool { self == .expanded }\n }\n\n enum CardType {\n case annotaion\n case chat\n }\n\n var cardType: CardType\n\n var cardHandleHeight: CGFloat\n var cardState: CardState = .collapased\n\n mutating func updateToNextState() {\n cardState = cardState.nextState\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-10T14:31:42.913", "Id": "233789", "ParentId": "233187", "Score": "1" } } ]
{ "AcceptedAnswerId": "233233", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T10:55:52.440", "Id": "233187", "Score": "2", "Tags": [ "swift", "ios", "animation" ], "Title": "Handling view state for cardview" }
233187
<p>I'm trying to make a dice game with three dice and with rules.</p> <ol> <li>It costs 10 credits to roll the dice.</li> <li>If you get 6 6 6 you win 90 credits.</li> <li>If you get 5 5 5, 4 4 4, 3 3 3, 2 2 2, 1 1 1, you win 40 credits.</li> <li>If two of the dice have the same number you win 0 credits (because it costs 10 to roll).</li> </ol> <p>Here's what I've done so far:</p> <pre><code>#include &lt;iostream&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; int main(void) { srand((int)time(NULL)); int diceRoll1, diceRoll2, diceRoll3; char yn; do { printf("\nDo you want to play? (y/n): "); scanf_s("%c", &amp;yn); getchar(); if (yn == 'n') { printf("Coward!"); getchar(); return 0; } diceRoll1 = (rand() % 6) + 1; diceRoll2 = (rand() % 6) + 1; diceRoll3 = (rand() % 6) + 1; printf("Your dices are %d %d %d \n", diceRoll1, diceRoll2, diceRoll3); if (diceRoll1 == 6 &amp;&amp; diceRoll2 == 6 &amp;&amp; diceRoll3 == 6) { printf("Congratulations! You won 90 credits.\n"); } if (diceRoll1 == 5 &amp;&amp; diceRoll2 == 5 &amp;&amp; diceRoll3 == 5) { printf("Congratulations! You won 40 credits.\n"); } if (diceRoll1 == 4 &amp;&amp; diceRoll2 == 4 &amp;&amp; diceRoll3 == 4) { printf("Congratulations! You won 40 credits.\n"); } if (diceRoll1 == 3 &amp;&amp; diceRoll2 == 3 &amp;&amp; diceRoll3 == 3) { printf("Congratulations! You won 40 credits.\n"); } if (diceRoll1 == 2 &amp;&amp; diceRoll2 == 2 &amp;&amp; diceRoll3 == 2) { printf("Congratulations! You won 40 credits.\n"); } if (diceRoll1 == 1 &amp;&amp; diceRoll2 == 1 &amp;&amp; diceRoll3 == 1) { printf("Congratulations! You won 40 credits.\n"); } } while (yn != 'n'); getchar(); return 0; } </code></pre> <p>I have not implemented all of the rules and the ones I have done can probably be done in a better way. I don't have much experience, so I wonder what the best way is to have all the rules in the game and so the code looks good.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T13:58:48.750", "Id": "455741", "Score": "2", "body": "I'm a bit unsure about the exact wording of the task. The \"you win 0\" sounds to me as if I still had to pay the 10 credits to actually throw the dice. And what does \"win 90\" mean? When I start with 1000 and roll a 666, do I then have 1080 or 1090 credit?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T18:06:31.927", "Id": "455755", "Score": "2", "body": "Clarifying your understanding of the rules and also specifying which ones you have implemented would greatly improve this question." } ]
[ { "body": "<p>You could condense the code using <em>or-eing</em> conditions that match the same credit gain:</p>\n\n<pre><code> if (diceRoll1 == 6 &amp;&amp; diceRoll2 == 6 &amp;&amp; diceRoll3 == 6) {\n printf(\"Congratulations! You won 90 credits.\\n\");\n }\n\n if ((diceRoll1 == 5 &amp;&amp; diceRoll2 == 5 &amp;&amp; diceRoll3 == 5) || \n (diceRoll1 == 4 &amp;&amp; diceRoll2 == 4 &amp;&amp; diceRoll3 == 4) || \n (diceRoll1 == 3 &amp;&amp; diceRoll2 == 3 &amp;&amp; diceRoll3 == 3) ||\n (diceRoll1 == 2 &amp;&amp; diceRoll2 == 2 &amp;&amp; diceRoll3 == 2) ||\n (diceRoll1 == 1 &amp;&amp; diceRoll2 == 1 &amp;&amp; diceRoll3 == 1)) {\n printf(\"Congratulations! You won 40 credits.\\n\");\n }\n</code></pre>\n\n<blockquote>\n <p>I have not implemented all of the rules and the ones I have done can probably be done in a better way?</p>\n</blockquote>\n\n<p>You could also make this code more flexible and extendible using function pointers and an array of these:</p>\n\n<pre><code>typedef int (*fn_gamerule(int,int,int));\n\nint gamerule1(int,int,int);\nint gamerule2(int,int,int);\n\n// ...\n\nfn_gamerule gamerules[] = { gamerule1, gamerule2, NULL };\n\n// ...\nint credits = 0;\nfor(fn_gamerule rule = gamerules; rule != NULL; ++rule) {\n credits = rule(diceRoll1m,diceRoll2,diceRoll3);\n if(credits &gt; 0) {\n printf(\"Congratulations! You won %d credits.\\n\",credits);\n }\n}\n\n// ...\n\nint gamerule1(int dr1,int dr2,int dr3) {\n if(dr1 == 6 &amp;&amp; dr2 == 6 &amp;&amp; dr3 == 6) {\n return 90;\n }\n return 0;\n}\n\nint gamerule2(int dr1,int dr2,int dr3) {\n if ((dr1 == dr2 &amp;&amp; dr2 == dr3) &amp;&amp;\n (dr1 &gt;= 1 &amp;&amp; dr1 &lt; 6)) {\n return 40;\n }\n return 0;\n}\n</code></pre>\n\n<p>Designing your code in that way will also help you to keep track of the <em>credits</em> in repeated iterations of the dice roll.</p>\n\n<pre><code>int rolldice_rule(int,int,int);\nint allsame_rule(int,int,int);\n\n// ...\n\nfn_gamerule gamerules[] = { rolldice_rule, allsame_rule, NULL };\n\nint total_credits = 0;\ndo {\n printf(\"\\nDo you want to play? (y/n): \");\n scanf_s(\"%c\", &amp;yn);\n // getchar(); &lt;= confusing user ecperience, not necessary\n\n if (yn == 'n') {\n printf(\"Coward!\");\n // getchar(); &lt;= confusing user ecperience, not necessary\n return 0;\n }\n\n diceRoll1 = (rand() % 6) + 1;\n diceRoll2 = (rand() % 6) + 1;\n diceRoll3 = (rand() % 6) + 1;\n\n printf(\"Your dices are %d %d %d \\n\", diceRoll1, diceRoll2, diceRoll3);\n\n int credits = 0;\n for(fn_gamerule rule = gamerules; rule != NULL; ++rule) {\n credits = rule(diceRoll1m,diceRoll2,diceRoll3);\n if(credits &gt; 0) {\n printf(\"Congratulations! You won %d credits.\\n\",credits);\n } \n total_credits += credits;\n }\n} while (yn != 'n');\n\n// ...\n\nint rolldice_rule(int dr1,int dr2,int dr3) {\n return -10;\n}\n\nint allsame_rule(int,int,int) {\n if (diceRoll1 == diceRoll2 == diceRoll3) {\n switch(diceRoll1) {\n case 6:\n return 90;\n default:\n return 40;\n }\n }\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T13:47:18.570", "Id": "233195", "ParentId": "233194", "Score": "3" } }, { "body": "<p>Reducing the amount of code in any program is good because that reduces the possible errors or bugs in the code. Providing general functions that can be reused is a good habit to get into.</p>\n\n<h2>DRY Code</h2>\n\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n\n<p>As shown in another answer all the if statements of the form </p>\n\n<pre><code> if (diceRoll1 == **x** &amp;&amp; diceRoll2 == diceRoll1 &amp;&amp; diceRoll3 == diceRoll1) {\n printf(\"Congratulations! You won **YY** credits.\\n\");\n }\n</code></pre>\n\n<p>Can be reduced to a simple function that can be reused.</p>\n\n<p>This code can also be simplified, although it is not absolutely necessary</p>\n\n<pre><code> diceRoll1 = (rand() % 6) + 1;\n diceRoll2 = (rand() % 6) + 1;\n diceRoll3 = (rand() % 6) + 1;\n</code></pre>\n\n<p>Can be </p>\n\n<pre><code>static constexpr int dieFaces = 6; // Allows the number of faces of the dice to be changed in one place\n // if this is used in a board game such as D &amp; D\n\nint rollOneDie()\n{\n return (rand() % dieFaces) + 1;\n}\n\nvoid rollTheDice(int &amp;die1, int &amp;die2, int &amp;die3)\n{\n die1 = rollOneDie();\n die2 = rollOneDie();\n die3 = rollOneDie();\n}\n</code></pre>\n\n<p>Any time I see variables with the names <code>var1</code>, <code>var2</code> and <code>var3</code> I see the potential for using an array instead of separate variables. The entire program might be simplified if instead of 3 separate variables <code>diceRoll1</code>, <code>diceRoll2</code> and <code>diceRoll3</code> there was one array of dice. This would also allow the program to be easily changed so that more or less dice are used.</p>\n\n<pre><code>static constexpr int diceCount = 3;\nstatic constexpr int highScore = 90;\nstatic constexpr int normalScore = 40;\nstatic constexpr int lowScore = 10;\nstatic constexpr int noScore = 0;\n\nvoid rollTheDice2(int dice[])\n{\n for (int i = 0; i &lt; diceCount; i++)\n {\n dice[i] = rollOneDie();\n }\n}\n\nbool allTheDiceEqualThisNumber(int dice[],int faceValue)\n{\n for (int i = 0; i &lt; diceCount; i++)\n {\n if (dice[i] != faceValue)\n {\n return false;\n }\n }\n return true;\n}\n\nint earnCredit(int dice[])\n{\n if (allTheDiceEqualThisNumber(dice, dieFaces))\n {\n return highScore;\n }\n else if (allTheDiceEqualThisNumber(dice, 1))\n {\n return lowScore;\n }\n else\n {\n for (int i = 2; i &lt; dieFaces - 1; i++) {\n if (allTheDiceEqualThisNumber(dice, i)) {\n return normalScore;\n }\n }\n }\n return noScore;\n}\n\nvoid showDice(int dice[])\n{\n printf(\"Your dices are \");\n for (int i = 0; i &lt; diceCount; i++)\n {\n printf(\"%d \", dice[i]);\n }\n printf(\"\\n\");\n}\n\nvoid playGame()\n{\n int diceRolls[diceCount];\n\n rollTheDice2(diceRolls);\n\n showDice(diceRolls);\n\n int newCredits = earnCredit(diceRolls);\n if (newCredits &gt; 0)\n {\n printf(\"Congratulations! You won 90 credits.\\n\");\n }\n}\n</code></pre>\n\n<h2>Complexity</h2>\n\n<p>The 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\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\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\n<pre><code>int main(void)\n{\n srand((int)time(NULL));\n\n char yn;\n\n do {\n printf(\"\\nDo you want to play? (y/n): \");\n scanf_s(\"%c\", &amp;yn);\n getchar();\n\n if (yn == 'n') {\n printf(\"Coward!\");\n getchar();\n return 0;\n }\n\n playGame();\n\n } while (yn != 'n');\n\n\n getchar();\n return 0;\n}\n</code></pre>\n\n<h2>Magic Numbers</h2>\n\n<p>There are Magic Numbers in the <code>main()</code> function (6, 90, 40, 10), it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</p>\n\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n\n<p>The possible symbolic constants are show in the examples for <strong>DRY Code</strong></p>\n\n<h2>C versus C++</h2>\n\n<p>This question was originally tagged with <strong>C</strong> rather than <strong>C++</strong>. The strict version of <code>C</code> can't compile <code>#include &lt;iostream&gt;</code>, it uses <code>#include &lt;stdio.h&gt;</code> instead. Also input in <code>C++</code> generally prefers</p>\n\n<pre><code>std::cin &gt;&gt; variableName;\n</code></pre>\n\n<p>over <code>scanf</code>, <code>scanf_s</code> or <code>getchar()</code> and </p>\n\n<pre><code>std::cout &lt;&lt; \"Your score was \" &lt;&lt; variableName &lt;&lt; \"\\n\";\n</code></pre>\n\n<p>over printf().</p>\n\n<p>C++ also has a newer random number generator with better distribution using <code>#include &lt;random&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T11:48:42.320", "Id": "461884", "Score": "1", "body": "\"`variableName << std::cin;`\" Is that C++42 new syntax? I [can't compile](https://wandbox.org/permlink/SP3DHHqBrEyGletd) it even with gcc HEAD 10.0.1 20200 and `-std=gnu++2a`. Did you mean `std::cin >> variableName`? :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T12:50:13.943", "Id": "461888", "Score": "0", "body": "Better? I think I corrected it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-20T12:51:54.100", "Id": "461890", "Score": "0", "body": "Great. Now it compiles ;)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T17:06:23.397", "Id": "233202", "ParentId": "233194", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T13:41:53.293", "Id": "233194", "Score": "5", "Tags": [ "c++", "game", "dice" ], "Title": "Dice game with rules and three dice" }
233194
<p>I have a HashMap and I want to convert data in it to a Response object. Is it possible to achieve this code that parses the string in a better and optimized and cleaner way, maybe by using streams?</p> <pre><code>class Converter{ public static void main(String[] args) { Map&lt;String, Long&gt; map = new HashMap&lt;String, Long&gt;(); map.put("111", 80) // first map.put("1A9-ppp", 190) // second map.put("98U-6765", 900) // third map.put("999-aa-local", 95) // fourth List&lt;FinalProduct&gt; products = new ArrayList&lt;&gt;(); for(String key : map.keySet()){ FinalProduct response = new FinalProduct(); String[] str = key.split("\\-"); response.id = str[0] //id is always present in key i.e 111, 1A9, 98U,999 if(str.length == 2) { if(str.matches("-?\\d+(\\.\\d+)?")){ // check if is numeric response.code = str[1]; // 6765 } else{ response.city = str[1]; //ppp } } if(str.length == 3){ response.client = str[1]; //aa response.type = str[2]; // local } response.qty = map.get[key]; products.add(response); } } } class FinalProduct{ String id; String city; Long code; String client; String type; Long qty; // getters and setters } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T17:15:14.603", "Id": "455752", "Score": "3", "body": "It might be better if the contents of the class FinalProduct was properly indented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T22:41:19.737", "Id": "455758", "Score": "0", "body": "@pacmaninbw And the code of the Converter class as well. That too looks ugly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T01:41:41.883", "Id": "455760", "Score": "1", "body": "What's the purpose of this? For example, where does \"1A9-ppp\" come from? If you have control over it, it's best not to hack a String for properties." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T12:34:55.653", "Id": "455778", "Score": "0", "body": "If the code works and you want to get reviews for optimization, better post to http://codereview.stackexchange.com" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T03:25:34.850", "Id": "455835", "Score": "0", "body": "`if(str.matches(\"-?\\\\d+(\\\\.\\\\d+)?\");){` this code does not compile." } ]
[ { "body": "<p>The only thing you need is a saparate method doing the parsing. </p>\n\n<p>This <code>parse</code> method can either be in a specific converter class that is used in a specific case when you're taking the strings and ammounts from a certain place. </p>\n\n<pre><code>public static FinalProduct parse(String key, Long quantity) {\n //transform into FinalProduct here\n}\n</code></pre>\n\n<p>Or if you'll always start from those business specific Strings you could just provide a constructor for <code>FinalProduct</code> that takes those as input params:</p>\n\n<pre><code>public class FinalProduct{\n\n private String id;\n private String city;\n private Long code;\n private String client;\n private String type;\n private Long qty;\n\n public FinalProduct(String codedProduct, Long qty) {\n this.qty = qty;\n //parse coded input string here\n } \n\n // only getters here, no setters\n}\n</code></pre>\n\n<p>Since the variables are probably not going to change after initializing the class you can make them final and not provide setters. Immutable objects are generaly easier to get right in a production code base (less edge cases when using multi threading for example).</p>\n\n<p>Using streams isn't going to make much of a difference really. The parsing itself isn't going to change and the loop is already as simple as it's going to get. I personally prefer the loop version over the stream version when going through a map:</p>\n\n<p>for loop:</p>\n\n<pre><code>List&lt;FinalProduct&gt; products = new ArrayList&lt;&gt;();\nfor (Map.Entry&lt;String, Long&gt; entry : map.entrySet()) {\n products.add(new FinalProduct(entry.getKey(), entry.getValue()));\n}\n</code></pre>\n\n<p>stream:</p>\n\n<pre><code>map.entrySet().stream()\n .map(entry -&gt; new FinalProduct(entry.getKey(), entry.getValue()))\n .collect(Collectors.toList());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T13:02:09.053", "Id": "233269", "ParentId": "233200", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T16:01:59.457", "Id": "233200", "Score": "2", "Tags": [ "java", "regex", "stream" ], "Title": "Converting HashMap data to a Response object" }
233200
<p><a href="https://github.com/dmitrynogin/dynoproxy" rel="noreferrer">GitHub</a> and <a href="https://www.nuget.org/packages/Dynoproxy" rel="noreferrer">NuGet</a></p> <p>I would like to use DynamicObject derived types to execute REST API/NodeJS module calls. It would also help to capture API shape in a strictly typed manner, so here comes an interface proxy which hides low level machinery allowing to do tricks like this:</p> <pre><code>[TestMethod] public void Call() { dynamic c = new ExpandoObject(); c.Add = (Func&lt;int, int, int&gt;)((a, b) =&gt; a + b); ICalculator proxy = Proxy.Create&lt;ICalculator&gt;(c); Assert.AreEqual(3, proxy.Add(1, 2)); } public interface ICalculator { int Add(int a, int b); } </code></pre> <p>Library code is:</p> <pre><code>using Castle.DynamicProxy; using Dynamitey; using System; namespace Dynoproxy { public static class Proxy { public static T Create&lt;T&gt;(this object source) where T : class { var proxyGenerator = new ProxyGenerator(); return proxyGenerator.CreateInterfaceProxyWithoutTarget&lt;T&gt;( ProxyGenerationOptions.Default, new Interceptor(source)); } class Interceptor : IInterceptor { public Interceptor(object target) =&gt; Target = target; object Target { get; } public void Intercept(IInvocation invocation) =&gt; invocation.ReturnValue = Dynamic.InvokeMember( Target, invocation.Method.Name, invocation.Arguments); } } } </code></pre>
[]
[ { "body": "<p>It would be very useful to see the associated <code>MethodInfo</code> instance while implementing source in the situation like this:</p>\n\n<pre><code>interface IMyWebApi\n{\n [Description(\"GET orders/{0}\")]\n Order GetOrder(int id); \n}\n\nIWebApi api = Proxy.Create&lt;IMyWebApi&gt;(new RestApi(\"http://example.com/api\"));\nOrder order = api.GetOrder(33);\n</code></pre>\n\n<p>So I made the proxy injecting it when <code>DescriptionAttribute</code> is provided:</p>\n\n<pre><code>[TestMethod]\npublic void Call()\n{\n dynamic c = new ExpandoObject();\n c.Add = (Func&lt;int, int, int&gt;)((a, b) =&gt; a + b);\n c.Divide = (Func&lt;MethodInfo, int, int, int&gt;)((mi, a, b) =&gt; a / b);\n\n ICalculator proxy = Proxy.Create&lt;ICalculator&gt;(c);\n Assert.AreEqual(3, proxy.Add(1, 2));\n Assert.AreEqual(2, proxy.Divide(4, 2));\n}\n\npublic interface ICalculator\n{\n int Add(int a, int b);\n\n [Description]\n int Divide(int a, int b);\n}\n</code></pre>\n\n<p>It should provide access to all interface method attributes and return types.</p>\n\n<p>Updated <code>Interceptor</code> looks like this now:</p>\n\n<pre><code>class Interceptor : IInterceptor\n{\n public Interceptor(object target) =&gt; Target = target;\n object Target { get; }\n public void Intercept(IInvocation invocation) =&gt;\n invocation.ReturnValue = Dynamic.InvokeMember(\n Target,\n invocation.Method.Name,\n invocation.Method.IsDefined(typeof(DescriptionAttribute)) \n ? invocation.Arguments.Prepend(invocation.Method).ToArray()\n : invocation.Arguments);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T22:57:45.013", "Id": "233212", "ParentId": "233203", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T17:09:07.207", "Id": "233203", "Score": "5", "Tags": [ "c#", "proxy" ], "Title": "Strictly typed dynamic proxy to call dynamic object" }
233203
<p>For my python project, I wanted to make a crossword game GUI with sql connectivity to display high scores so I tried to learn tkinter the only difficulty was that I cannot use classes or objects as they are not taught at my school yet. Still I managed to make a highly inefficient and ugly looking code ( I am a newbie btw). Please suggest me to improve my code quality and writing style.</p> <p>Heres my code:</p> <pre><code># -*- coding: utf-8 -*- import tkinter as tk from PIL import ImageTk, Image import mysql.connector import requests from io import BytesIO #requesting password to access sql database passwd = str(input("enter the password for sql database")) #connecting to mysql connection = mysql.connector.connect(host='localhost', user='root', password=passwd) #creating database myschool cursor = connection.cursor() cursor.execute('''CREATE DATABASE IF NOT EXISTS myschool''') cursor.execute('''USE myschool''') #function to insert player score into database def updatevalues(val1,val2,val3): cursor = connection.cursor() sql = "INSERT INTO crossword (User, timetaken, correctvalues) VALUES (%s, %s, %s)" val = (val1,val2,val3) cursor.execute(sql, val) connection.commit() #function to create table if crossword table doesnt not exist def createtable(): cursor = connection.cursor() cursor.execute('''CREATE TABLE crossword (User varchar(255),timetaken varchar(255),correctvalues int);''') #defining delete and entry functions def delete(entry): entry.delete(0,'end') return None def entry_get(entry): value1 = entry.get() return value1 #defining a function to get the entered username username = '' def check(): global username if entry_get(nameentry) : username = str(entry_get(nameentry)) delete(nameentry) new_window.destroy() #making a login window new_window = tk.Tk() tk.Label(new_window,text='Enter username:',font=('Times New Roman',25)).place(x=80,y=100) tk.Label(new_window,text='Welcome to My Game',font=('Algerian',35,'underline')).place(x=60,y=10) tk.Label(new_window,text='Note: The Game will start as soon as you press enter',font=('Times New Roman',15)).place(x=70,y=230) nameentry = tk.Entry(new_window) nameentry.place(x=320,y=110,height=30,width=200) sub1 = tk.Button(new_window,text="Enter", command = check) sub1.place(x=250,y=160,height=40,width=150) new_window.geometry('600x350') new_window.mainloop() #making the main crossword window window = tk.Tk() window.title("My GUI") lab = tk.Label(window,text='Crossword#1') #making a 30 min timer def update_timeText(): if (state): global timer timer[2] += 1 if (timer[2] &gt;= 100): timer[2] = 0 timer[1] += 1 if (timer[1] &gt;= 60): timer[0] += 1 timer[1] = 0 timeString = pattern.format(timer[0], timer[1], timer[2]) timeText.configure(text=timeString) if timer == [30,0,0]: timeText.configure(text="30:00:00") else: window.after(10, update_timeText) def start(): global state state = True def stop(): global state state = False state = False timer = [0, 0, 0] pattern = '{0:02d}:{1:02d}:{2:02d}' timeText = tk.Label(window, text="00:00:00", font=("Helvetica", 30)) timeText.place(x=100,y=30) update_timeText() window.after(1,start) #creating a canvas and making a crossword structure cwidth=450 cheight=450 W = tk.Canvas(window,width=cwidth,height=cheight,highlightbackground='black') W.place(x=100,y=100) for i in range(0,450,50): W.create_line(0,i,450,i) W.create_line(i,0,i,450) #marking numbers on grid W.create_text(10,10,text=1) W.create_text(110,10,text=2) W.create_text(260,10,text=3) W.create_text(310,10,text=4) W.create_text(410,10,text=5) W.create_text(10,110,text=6) W.create_text(60,110,text=7) W.create_text(160,110,text=8) W.create_text(260,110,text=9) W.create_text(360,110,text=10) W.create_text(160,160,text=11) W.create_text(10,210,text=12) W.create_text(260,210,text=13) W.create_text(160,260,text=14) W.create_text(10,310,text=15) W.create_text(110,310,text=16) W.create_text(260,310,text=17) W.create_text(310,310,text=18) W.create_text(410,310,text=19) W.create_text(10,410,text=20) W.create_text(260,410,text=21) #making black squares W.create_rectangle(200,0,250,150,fill='black') W.create_rectangle(150,50,300,100,fill='black') W.create_rectangle(50,50,100,100,fill='black') W.create_rectangle(350,50,400,100,fill='black') W.create_rectangle(0,150,50,200,fill='black') W.create_rectangle(100,150,150,200,fill='black') W.create_rectangle(300,150,350,200,fill='black') W.create_rectangle(400,150,451,200,fill='black') W.create_rectangle(200,200,250,250,fill='black') W.create_rectangle(0,250,50,300,fill='black') W.create_rectangle(100,250,150,300,fill='black') W.create_rectangle(300,250,350,300,fill='black') W.create_rectangle(400,250,451,300,fill='black') W.create_rectangle(200,300,250,451,fill='black') W.create_rectangle(50,350,100,400,fill='black') W.create_rectangle(150,350,300,400,fill='black') W.create_rectangle(350,350,400,400,fill='black') #creating section for clues X = tk.Canvas(window,height=600,width=700,highlightbackground='black') X.pack(padx=40,side='right') #Across secion X.create_text(130,50,font=('Arial',40),text='Across') X.create_text(115,105,font=('Arial',20),text='1. Locale') X.create_text(176,145,font=('Arial',20),text='3. Soup Containers') X.create_text(180,185,font=('Arial',20),text='6. Nectar Gatherers') X.create_text(150,225,font=('Arial',20),text='9. Fries or Slaw') X.create_text(159,265,font=('Arial',20),text='11. Household pest') X.create_text(167,305,font=('Arial',20),text='12. Belonging to Eda') X.create_text(120,345,font=('Arial',20),text='13. __ of Evil') X.create_text(150,385,font=('Arial',20),text='14. Morning Riser') X.create_text(100,425,font=('Arial',20),text='15. Lazily') X.create_text(138,465,font=('Arial',20),text='17. Buck or doe') X.create_text(167,505,font=('Arial',20),text='20. Sunrise direction') X.create_text(195,545,font=('Arial',19),text='21. you do this with a book') #Down section X.create_text(530,50,font=('Arial',40),text='Down') X.create_text(520,105,font=('Arial',20),text='1. Long Sandwhich') X.create_text(487,145,font=('Arial',20),text='2. Casual top') X.create_text(471,185,font=('Arial',20),text='4. __ Baba') X.create_text(471,225,font=('Arial',20),text='5. Observe') X.create_text(484,265,font=('Arial',20),text='7. Concluded') X.create_text(465,305,font=('Arial',20),text='8. Cheeky') X.create_text(465,345,font=('Arial',20),text='9. Dont sit') X.create_text(457,385,font=('Arial',20),text='10. Tee off') X.create_text(516,425,font=('Arial',20),text='15. If__I said it once') X.create_text(480,465,font=('Arial',20),text='16. __Angeles') X.create_text(498,505,font=('Arial',20),text='18. New Years__') X.create_text(530,545,font=('Arial',20),text='19. Scarlett or Maroon') #linking tick image when answer is correct img_url = "https://i.ibb.co/2PKKZrj/iconfinder-tick-16-22643.png" response = requests.get(img_url) img_data = response.content img = ImageTk.PhotoImage(Image.open(BytesIO(img_data))) def tickimg(x_co,y_co): panel = tk.Label(window, image=img) panel.place(x=x_co,y=y_co) lis = [['1','A','site'],['1','D','sub'],['2','D','tee'],['3','A','cans'],['4','D','ali'], ['5','D','see'],['6','A','bees'],['7','D','ended'],['8','D','sassy'], ['9','A','side'],['9','D','stand'],['10','D','drive'],['11','A','ant'],['12','A','idas'], ['13','A','axis'],['14','A','sun'],['15','A','idly'],['15','D','ive'], ['16','D','los'],['17','A','deer'],['18','D','eve'], ['19','D','red'],['20','A','east'],['21','A','read']] def listchange(): stop() global timer timestring = '' minutes = timer[0] if minutes &lt; 10: timestring += '0'+str(timer[0])+':' else: timestring += str(timer[0])+':' seconds = timer[1] if seconds &lt; 10: timestring += '0'+str(timer[1])+':' else: timestring += str(timer[1])+':' milliseconds = timer[2] if milliseconds &lt; 10: timestring += '0'+str(timer[2]) else: timestring += str(timer[2]) return timestring def button_fun(): global correct global username new_timer = listchange() cursor = connection.cursor() cursor.execute("""show tables;""") if ('crossword',) in cursor: updatevalues(username,new_timer,len(correct)) else: createtable() updatevalues(username,new_timer,len(correct)) def endscreen1(): root = tk.Tk() def des(): root.destroy() root.geometry('700x450') tk.Label(root,text='THANK YOU',font=('Algerian',60)).place(x = 140,y = 30) tk.Label(root,text='FOR',font=('Algerian',60)).place(x = 270, y = 120) tk.Label(root,text='PLAYING',font=('Algerian',60)).place(x = 190, y= 210) viewscore = tk.Button(root,text='VIEW HIGHSCORE',command=des) viewscore.place(x=270,y=340,height=40,width=150) root.mainloop() def highscore(): newroot = tk.Tk() newroot.geometry('800x700') tk.Label(newroot,text='HIGH SCORES',font=('Algerian',50,'underline')).pack(side='top',pady=20) Y = tk.Canvas(newroot,height=700,width=600,highlightbackground='black') Y.pack(side='top',pady=30) Y.create_line(200,0,200,700) Y.create_line(400,0,400,700) Y.create_text(100,30,text='Name',font=('Times New Roman',30)) Y.create_text(300,30,text='Time Taken',font=('Times New Roman',30)) Y.create_text(500,30,text='Correct',font=('Times New Roman',30)) Y.create_text(500,60,text='Answers',font=('Times New Roman',30)) Y.create_line(0,80,600,80) cursor = connection.cursor() cursor.execute('''select * from crossword order by correctvalues desc,timetaken ;''') names = [] times = [] correct = [] for i in cursor: names.append(i[0]) times.append(i[1]) correct.append(i[2]) x1_co = 100 x2_co = 300 x3_co = 500 y_co = 60 if len(names) &gt; 8: names = names[0:8] for i in range(0,len(names)): y_co += 50 Y.create_text(x1_co,y_co,text=names[i],font=('Times New Roman',20)) Y.create_text(x2_co,y_co,text=times[i],font=('Times New Roman',20)) Y.create_text(x3_co,y_co,text=correct[i],font=('Times New Roman',20)) newroot.mainloop() correct = [] def check_func(myvav = False): global correct global isclicked for i in range(len(lis)): if entry_get(entry1) == lis[i][0] and entry_get(entry2) == lis[i][1] and entry_get(entry3) == lis[i][2]: correct.append('1') if i == 0: tickimg(640,160) W.create_text(25,25,font=('Times New Roman',25),text='S') W.create_text(75,25,font=('Times New Roman',25),text='I') W.create_text(125,25,font=('Times New Roman',25),text='T') W.create_text(175,25,font=('Times New Roman',25),text='E') if i == 1: tickimg(980,160) W.create_text(25,25,font=('Times New Roman',25),text='S') W.create_text(25,75,font=('Times New Roman',25),text='U') W.create_text(25,125,font=('Times New Roman',25),text='B') if i == 2: tickimg(980,200) W.create_text(125,25,font=('Times New Roman',25),text='T') W.create_text(125,75,font=('Times New Roman',25),text='E') W.create_text(125,125,font=('Times New Roman',25),text='E') if i == 3: tickimg(640,200) W.create_text(275,25,font=('Times New Roman',25),text='C') W.create_text(325,25,font=('Times New Roman',25),text='A') W.create_text(375,25,font=('Times New Roman',25),text='N') W.create_text(425,25,font=('Times New Roman',25),text='S') if i == 4: tickimg(980,240) W.create_text(325,25,font=('Times New Roman',25),text='A') W.create_text(325,75,font=('Times New Roman',25),text='L') W.create_text(325,125,font=('Times New Roman',25),text='I') if i == 5: tickimg(980,280) W.create_text(425,25,font=('Times New Roman',25),text='S') W.create_text(425,75,font=('Times New Roman',25),text='E') W.create_text(425,125,font=('Times New Roman',25),text='E') if i == 6: tickimg(640,240) W.create_text(25,125,font=('Times New Roman',25),text='B') W.create_text(75,125,font=('Times New Roman',25),text='E') W.create_text(125,125,font=('Times New Roman',25),text='E') W.create_text(175,125,font=('Times New Roman',25),text='S') if i == 7: tickimg(980,320) W.create_text(75,125,font=('Times New Roman',25),text='E') W.create_text(75,175,font=('Times New Roman',25),text='N') W.create_text(75,225,font=('Times New Roman',25),text='D') W.create_text(75,275,font=('Times New Roman',25),text='E') W.create_text(75,325,font=('Times New Roman',25),text='D') if i == 8: tickimg(980,360) W.create_text(175,125,font=('Times New Roman',25),text='S') W.create_text(175,175,font=('Times New Roman',25),text='A') W.create_text(175,225,font=('Times New Roman',25),text='S') W.create_text(175,275,font=('Times New Roman',25),text='S') W.create_text(175,325,font=('Times New Roman',25),text='Y') if i == 9: tickimg(640,280) W.create_text(275,125,font=('Times New Roman',25),text='S') W.create_text(325,125,font=('Times New Roman',25),text='I') W.create_text(375,125,font=('Times New Roman',25),text='D') W.create_text(425,125,font=('Times New Roman',25),text='E') if i == 10: tickimg(980,400) W.create_text(275,125,font=('Times New Roman',25),text='S') W.create_text(275,175,font=('Times New Roman',25),text='T') W.create_text(275,225,font=('Times New Roman',25),text='A') W.create_text(275,275,font=('Times New Roman',25),text='N') W.create_text(275,325,font=('Times New Roman',25),text='D') if i == 11: tickimg(980,440) W.create_text(275,325,font=('Times New Roman',25),text='D') W.create_text(375,175,font=('Times New Roman',25),text='R') W.create_text(375,225,font=('Times New Roman',25),text='I') W.create_text(375,275,font=('Times New Roman',25),text='V') W.create_text(375,325,font=('Times New Roman',25),text='E') if i == 12: tickimg(625,320) W.create_text(175,175,font=('Times New Roman',25),text='A') W.create_text(225,175,font=('Times New Roman',25),text='N') W.create_text(275,175,font=('Times New Roman',25),text='T') if i == 13: tickimg(627,360) W.create_text(25,225,font=('Times New Roman',25),text='I') W.create_text(75,225,font=('Times New Roman',25),text='D') W.create_text(125,225,font=('Times New Roman',25),text='A') W.create_text(175,225,font=('Times New Roman',25),text='S') if i == 14: tickimg(627,400) W.create_text(275,225,font=('Times New Roman',25),text='A') W.create_text(325,225,font=('Times New Roman',25),text='X') W.create_text(375,225,font=('Times New Roman',25),text='I') W.create_text(425,225,font=('Times New Roman',25),text='S') if i == 15: tickimg(627,440) W.create_text(175,275,font=('Times New Roman',25),text='S') W.create_text(225,275,font=('Times New Roman',25),text='U') W.create_text(275,275,font=('Times New Roman',25),text='N') if i == 16: tickimg(627,480) W.create_text(25,325,font=('Times New Roman',25),text='I') W.create_text(75,325,font=('Times New Roman',25),text='D') W.create_text(125,325,font=('Times New Roman',25),text='L') W.create_text(175,325,font=('Times New Roman',25),text='Y') if i == 17: tickimg(980,480) W.create_text(25,325,font=('Times New Roman',25),text='I') W.create_text(25,375,font=('Times New Roman',25),text='V') W.create_text(25,425,font=('Times New Roman',25),text='E') if i == 18: tickimg(980,520) W.create_text(125,325,font=('Times New Roman',25),text='L') W.create_text(125,375,font=('Times New Roman',25),text='O') W.create_text(125,425,font=('Times New Roman',25),text='S') if i == 19: tickimg(627,520) W.create_text(275,325,font=('Times New Roman',25),text='D') W.create_text(325,325,font=('Times New Roman',25),text='E') W.create_text(375,325,font=('Times New Roman',25),text='E') W.create_text(425,325,font=('Times New Roman',25),text='R') if i == 20: tickimg(980,560) W.create_text(325,325,font=('Times New Roman',25),text='E') W.create_text(325,375,font=('Times New Roman',25),text='V') W.create_text(325,425,font=('Times New Roman',25),text='E') if i == 21: tickimg(980,600) W.create_text(425,325,font=('Times New Roman',25),text='R') W.create_text(425,375,font=('Times New Roman',25),text='E') W.create_text(425,425,font=('Times New Roman',25),text='D') if i == 22: tickimg(627,560) W.create_text(25,425,font=('Times New Roman',25),text='E') W.create_text(75,425,font=('Times New Roman',25),text='A') W.create_text(125,425,font=('Times New Roman',25),text='S') W.create_text(175,425,font=('Times New Roman',25),text='T') if i == 23: tickimg(627,600) W.create_text(275,425,font=('Times New Roman',25),text='R') W.create_text(325,425,font=('Times New Roman',25),text='E') W.create_text(375,425,font=('Times New Roman',25),text='A') W.create_text(425,425,font=('Times New Roman',25),text='D') delete(entry1) delete(entry2) delete(entry3) if myvav == True: submitbutton.bind('&lt;Button-1&gt;',button_fun()) window.destroy() endscreen1() highscore() if len(correct) == 24: button_fun() window.destroy() endscreen1() highscore() #Entry windows ,check button and submit button tk.Label(window,text='Number:',font=('Arial',15)).place(x=21,y=580) entry1 = tk.Entry(window) entry1.place(x=100,y=580,height=30,width=100) tk.Label(window,text='A or D:',font=('Arial',15)).place(x=230,y=580) entry2 = tk.Entry(window) entry2.place(x=300,y=580,height=30,width=100) tk.Label(window,text='Word:',font=('Arial',15)).place(x=437,y=580) entry3 = tk.Entry(window) entry3.place(x=500,y=580,height=30,width=100) check_button = tk.Button(window, text="Check",command=check_func) check_button.place(x=270,y=630,height=30,width=100) submitbutton = tk.Button(window,text="Submit",command=lambda: check_func(myvav=True)) submitbutton.place(x=500,y=630,height=30,width=100) window.geometry("1366x768") window.mainloop() </code></pre> <p>One more thing I want to add data file handling in this but I am not quite sure how that works so any suggestions would be helpful.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T22:36:54.070", "Id": "455757", "Score": "0", "body": "Yep, you're right, the code looks ugly. Since you already know how to define functions with parameters, why didn't you use them for the repetitive `W.create_text` blocks? For example you could define `add_across(627, 560, 25, 425, \"EAST\")` or `add_down(980, 600, 425, 325, \"RED\")`. As long as there are no answers, you may still improve your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T10:28:54.003", "Id": "455768", "Score": "0", "body": "@RolandIllig Thanks for the advice. I will definitely implement this on my code." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T18:31:17.277", "Id": "233206", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "mysql", "tkinter" ], "Title": "crossword using tkinter without classes and objects" }
233206
<p>I have written many variations of the <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow noreferrer">Sieve of Eratosthenses</a>, which is the fastest way to generate a large collection of primes. (@slepic asked for clarification, which I provide in an answer below. My intended statement is that a sieve in general is much faster than naive methods at generating lots of primes; not that the Sieve of Eratosthenses is the fastest ever.)</p> <p>If you later want to query the gathered primes by count or at a specific index, the performance of the sieve is lacking compared to a list. So I thought, why not make a prime table that uses a high performance sieve to generate the primes, but later move those primes into a list (memory permitting).</p> <p>I originally wrote this as an answer to someone else's <a href="https://codereview.stackexchange.com/questions/232198/a-prime-numbers-enumeration-optimized-for-speed">post</a>, but much of my goals, objectives, code, and features differed so much that I am posting for my own review.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; using System.Collections; namespace Prime_Table_Core { // What's in a name? Variable/parameter names for any Int32 were chosen to denote context. // // number: any Int32 on the "number line" to be evaluated as prime, composite, or neither. // prime : a subset of number where the Int32 is a prime. // index : an Int32 used as the positional index into _knownPrimes list. // value : no specific context or restriction on this Int32. public static class PrimeTable { private static readonly List&lt;int&gt; _knownPrimes = new List&lt;int&gt;() { 2 }; public static bool IsInitialized { get; private set; } = false; public static TimeSpan LastDuration { get; private set; } = TimeSpan.Zero; // If you want to work directly with just the known primes, no need for streaming // since the table is already in memory. public static IReadOnlyList&lt;int&gt; KnownPrimes =&gt; _knownPrimes; public static int KnownPrimeCount =&gt; _knownPrimes.Count; public static int LastKnownPrime =&gt; _knownPrimes.Last(); public static int LastKnownIndex =&gt; _knownPrimes.Count - 1; // Track the very last number checked using GetNextUnknownPrime() or Initialize(). // This number could be greater than LastKnownPrime. private static int _lastNumberChecked = 2; private static Func&lt;int, bool&gt; HasMoreNumbers = number =&gt; (int.MaxValue - number) &gt; 2; private static Func&lt;int, int&gt; DoubleIt = value =&gt; value &lt;&lt; 1; private static Func&lt;int, int&gt; HalveIt = value =&gt; value &gt;&gt; 1; private static Func&lt;int, bool&gt; IsEven = value =&gt; value % 2 == 0; public static int GetIndexAtOrBefore(int number) { if (number &lt; 2) { return -1; } InitializeIfNeeded(); if (number &gt;= LastKnownPrime) { return LastKnownIndex; } var upperIndex = LastKnownIndex; var lowerIndex = 0; var midIndex = HalveIt(upperIndex + lowerIndex); // Instead of a while(true), let's completely avoid an infinite loop. // The for loop won't use it's index variable other than to prevent // the loop from being infinite. But as a debugging bonus, you can use // "iteration" to see how many iterations were needed for a lookup. for (var iteration = 1; iteration &lt; _knownPrimes.Count; iteration++) { if (number == _knownPrimes[midIndex]) { return midIndex; } if ((upperIndex - lowerIndex) &lt;= 1) { return (number &gt; _knownPrimes[upperIndex]) ? upperIndex : lowerIndex; } if (number &gt; _knownPrimes[midIndex]) { lowerIndex = midIndex; } else { upperIndex = midIndex; } midIndex = HalveIt(upperIndex + lowerIndex); } return -1; // for safety's sake, but really is unreachable. } public static int GetIndexBefore(int number) =&gt; (number &lt;= 2) ? -1 : GetIndexAtOrBefore(number - 1); public static int GetIndexAfter(int number) =&gt; (number == int.MaxValue) ? -1 : GetIndexAtOrAfter(number + 1); public static int GetIndexAtOrAfter(int number) { var index = GetIndexAtOrBefore(number); if (index == -1) { return 0; } if (_knownPrimes[index] == number) { return index; } return ++index &lt; KnownPrimeCount ? index : -1; } public static bool IsPrime(this int number) { // First, dispense with easy cases. if (number &lt; 2) { return false; } if (IsEven(number)) { return number == 2; } InitializeIfNeeded(); var index = 0; // Second, quickly check against _knownPrimes and _lastNumberChecked. if (number &lt;= LastKnownPrime) { index = GetIndexAtOrBefore(number); return _knownPrimes[index] == number; } if (number &lt;= _lastNumberChecked) { return false; } // Third, perform naive primality test using known primes. var sqrt = (int)Math.Sqrt(number); for (index = 0; index &lt; _knownPrimes.Count; index++) { if (number % _knownPrimes[index] == 0) { return false; } if (_knownPrimes[index] &gt; sqrt) { return true; } } // Fourth, perform naive primality test on Odds beyond LargestKnownPrime for (var possibleDivisor = _lastNumberChecked + 2; possibleDivisor &lt;= sqrt; possibleDivisor += 2) { if (number % possibleDivisor == 0) { return false; } } // Finally, it must be prime. return true; } // This method will stream the known primes first, followed by the unknown ones. public static IEnumerable&lt;int&gt; GetPrimes() { InitializeIfNeeded(); foreach (var prime in _knownPrimes) { yield return prime; } for (; ; ) { var next = GetNextUnknownPrime(); if (next.HasValue) { yield return next.Value; } else { yield break; } } } // This method bypasses the known primes and starts streaming the unknown ones, if any. public static IEnumerable&lt;int&gt; GetUnknownPrimes() { InitializeIfNeeded(); for (; ; ) { var next = GetNextUnknownPrime(); if (next.HasValue) { yield return next.Value; } else { yield break; } } } public static int? GetNextUnknownPrime() { if (!HasMoreNumbers(_lastNumberChecked)) { LastDuration = TimeSpan.Zero; return null; } int result = -1; InitializeIfNeeded(); var sw = Stopwatch.StartNew(); for (var candidate = _lastNumberChecked + 2; ; candidate += 2) { if (IsPrime(candidate)) { _lastNumberChecked = candidate; result = candidate; break; } _lastNumberChecked = candidate; if (!HasMoreNumbers(candidate)) { // Do this here instead of inside for condition so that // we do not overflow past Int.MaxValue, or worse, // wrap around to Int.MinValue. break; } } if (result &gt; 1) { _knownPrimes.Add(result); } sw.Stop(); LastDuration = sw.Elapsed; return result; } // This will only initialize _knownPrimes once. public static void InitializeIfNeeded() { const int DefaultUpperLimit = 1_500_001; // produces 114_155 primes in 0.01 seconds if (!IsInitialized) { Initialize(DefaultUpperLimit); } } // You may Initialize and re-Initialize to your heart's content. // Depending upon upperLimit, this may take a split second or half a minute or longer based // upon your CPU and RAM. public static void Initialize(int upperLimit) { const int MinimumUpperLimit = 1000; if (upperLimit &lt; MinimumUpperLimit) { throw new ArgumentException($"{nameof(upperLimit)} must be {MinimumUpperLimit} or greater."); } var sw = Stopwatch.StartNew(); GenerateSieve(upperLimit); sw.Stop(); LastDuration = sw.Elapsed; IsInitialized = true; } // The intent is to start off with a small, very fast sieve to build the _knownPrimes up to a point. // While a BitArray uses less memory, it is also slower than bool[]. // Once this method completes, the array is set to null and memory can be GC'd. // If responsiveness is your goal, then a "reasonable" upperLimit is one that executes // in less than 0.25 seconds on your hardware. private static void GenerateSieve(int upperLimit) { lock (_knownPrimes) { _knownPrimes.Clear(); _knownPrimes.Add(2); // Evens all done. Now check only odd numbers for primality if (IsEven(upperLimit)) { upperLimit++; } const int offset = 1; Func&lt;int, int&gt; ToNumber = index =&gt; DoubleIt(index) + offset; Func&lt;int, int&gt; ToIndex = number =&gt; HalveIt(number - offset); // initial flags are false var flags = new BitArray(ToIndex(upperLimit) + 1, true); flags[0] = false; var upperSqrtIndex = ToIndex((int)Math.Sqrt(upperLimit)); for (var i = 1; i &lt;= upperSqrtIndex; i++) { // If this bit has already been turned off, then its associated number is composite. if (!flags[i]) { continue; } var number = ToNumber(i); _knownPrimes.Add(number); // Any multiples of number are composite and their respective flags should be turned off. for (var j = ToIndex(number * number); j &lt; flags.Length; j += number) { flags[j] = false; } } // Output remaining primes once flags array is fully resolved: for (var i = upperSqrtIndex + 1; i &lt; flags.Length; i++) { if (flags[i]) { _knownPrimes.Add(ToNumber(i)); } } _lastNumberChecked = upperLimit; } } } } </code></pre> <p>This was written in .NET Core 3.0, but also ported to full Framework 4.8. The full Framework is about 50% slower on the same hardware.</p> <p>Once the prime table is generated, you may query against the list of what I call known primes. But you may also continue to discover unknown primes, if any, that once discovered are then added to the known primes.</p> <p>You may quickly initialize a larger number of known primes using the <code>Initialize(upperLimit)</code> method. If speedy responsiveness is your main objective, then a good <code>upperlimit</code> should be something that returns in 0.25 seconds or less on your particular hardware. If you want to max out all of Int32, you can do that too but it may take quite a while to generate all 105+ million primes.</p> <p>An example of it in use:</p> <pre><code>PrimeTable.Initialize using assorted upper limits: Upper Limit = 1000001, PrimeCount = 78498, LastPrime = 999983, Duration: 00:00:00.0064373 (includes JIT time) Upper Limit = 1500001, PrimeCount = 114155, LastPrime = 1499977, Duration: 00:00:00.0043673 Upper Limit = 2000001, PrimeCount = 148933, LastPrime = 1999993, Duration: 00:00:00.0072214 Upper Limit = 5000001, PrimeCount = 348513, LastPrime = 4999999, Duration: 00:00:00.0180426 Upper Limit = 10000001, PrimeCount = 664579, LastPrime = 9999991, Duration: 00:00:00.0330480 Upper Limit = 17000001, PrimeCount = 1091314, LastPrime = 16999999, Duration: 00:00:00.0573246 Upper Limit = 20000001, PrimeCount = 1270607, LastPrime = 19999999, Duration: 00:00:00.0648279 Upper Limit = 50000001, PrimeCount = 3001134, LastPrime = 49999991, Duration: 00:00:00.1564291 Demo of index usage to KnownPrimes: GetIndexAtOrBefore(55551) = 5636, KnownPrimes[5636] = 55547 GetIndexAtOrAfter (55551) = 5637, KnownPrimes[5637] = 55579 Demo fetching next 10 unknown primes: PrimeCount = 3001135, LastPrime = 50000017, Duration: 00:00:00.0004588 (includes JIT time) PrimeCount = 3001136, LastPrime = 50000021, Duration: 00:00:00.0000044 PrimeCount = 3001137, LastPrime = 50000047, Duration: 00:00:00.0000188 PrimeCount = 3001138, LastPrime = 50000059, Duration: 00:00:00.0000065 PrimeCount = 3001139, LastPrime = 50000063, Duration: 00:00:00.0000180 PrimeCount = 3001140, LastPrime = 50000101, Duration: 00:00:00.0000048 PrimeCount = 3001141, LastPrime = 50000131, Duration: 00:00:00.0000071 PrimeCount = 3001142, LastPrime = 50000141, Duration: 00:00:00.0000193 PrimeCount = 3001143, LastPrime = 50000161, Duration: 00:00:00.0000097 PrimeCount = 3001144, LastPrime = 50000201, Duration: 00:00:00.0000148 PrimeTable.Initialize(int.MaxValue): Upper Limit = 2147483647, PrimeCount = 105097565, LastPrime = 2147483647, Duration: 00:00:12.8353907 GetIndexAtOrBefore(55551) = 5636, KnownPrimes[5636] = 55547 GetIndexAtOrAfter (55551) = 5637, KnownPrimes[5637] = 55579 GetIndexAtOrAfter (2147483647) = 105097564, KnownPrimes[105097564] = 2147483647 GetIndexAfter (2147483647) = -1 GetNextUnknownPrime() = &lt;null&gt; Press ENTER key to close </code></pre> <p>There are 3 ways to enumerate over a large collection of primes:</p> <ol> <li>Use the KnownPrimes table, a read-only list.</li> <li>GetUnknownPrimes() skips over the known primes and streams the unknown to you.</li> <li>GetPrimes() will first stream the known primes to you, followed by the unknown.</li> </ol> <p>Other features:</p> <p>Since performance is a curiosity, there is a <code>LastDuration</code> property to inform you how long the sieve took to generate, or how long the last GetNextUnknownPrime took.</p> <p>Anything using the known prime's index does not discover any unknown primes. This includes the <code>IsPrime</code> method, which is a tad long as it tries to first check against the known primes before resorting to a naive implementation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T08:10:16.463", "Id": "455764", "Score": "2", "body": "\"which is the fastest way to generate a large collection of primes\". That deserves some reference..." } ]
[ { "body": "<p>I am providing an answer to my post in order to address a comment by @slepic regarding the first sentence in the OP. @slepic asked for clarification to this statement:</p>\n\n<blockquote>\n <p>I have written many variations of the Sieve of Eratosthenses, which is\n the fastest way to generate a large collection of primes.</p>\n</blockquote>\n\n<p>First of all, what I meant was that in order to generate a lot of primes that a sieve is faster than using naive methods. There may be sieves faster than Eratosthenses, but a sieve will be much faster than not using a sieve. That was my intended statement and hopefully addresses the clarification that was requested.</p>\n\n<p>My PrimeTable can be easily modified to demonstrate this. First, I changed this line in <code>PrimeTable.cs</code>:</p>\n\n<pre><code>public static bool IsInitialized { get; private set; } = true;\n</code></pre>\n\n<p>But hit a quirk because the only prime I have to start with is 2, and my later logic assumes the last known prime is odd. I could change that logic but I chose instead to change this line:</p>\n\n<pre><code>private static readonly List&lt;int&gt; _knownPrimes = new List&lt;int&gt;() { 2, 3 };\n</code></pre>\n\n<p>Which also required me to change a field, which was upgraded with softer coding:</p>\n\n<pre><code>private static int _lastNumberChecked = LastKnownPrime;\n</code></pre>\n\n<p>With those few changes, I then wrote a method to generate primes:</p>\n\n<pre><code>private static void SlowerGrowth()\n{\n Console.WriteLine(\"Display 'slower' growth without sieve.\");\n // Account for JIT\n var prime = PrimeTable.GetNextUnknownPrime(); \n var preCount = PrimeTable.KnownPrimeCount; \n\n var step = TimeSpan.FromMilliseconds(10);\n var limit = TimeSpan.FromSeconds(1);\n var progressMark = step;\n\n var total = TimeSpan.Zero;\n var count = 0;\n\n while (total &lt; limit)\n {\n prime = PrimeTable.GetNextUnknownPrime();\n var elapsed = PrimeTable.LastDuration;\n total += elapsed;\n\n if (total &gt;= progressMark || total &gt;= limit)\n {\n count++;\n Console.WriteLine($\" Count = {(PrimeTable.KnownPrimeCount - preCount)}, Largest = {PrimeTable.LastKnownPrime}, Elapsed = {total}\"); //, Step = {step}, Mark = {progressMark}\");\n if (count == 5 || total &gt;= limit)\n {\n step = 10 * step;\n progressMark = step;\n count = 0;\n }\n else\n {\n progressMark += step;\n }\n }\n }\n}\n</code></pre>\n\n<p>Which produced this output:</p>\n\n<p><strong>WITHOUT A SIEVE (NAIVE CHECKS)</strong></p>\n\n<pre><code>Display 'slower' growth without sieve.\n Count = 16427, Largest = 181211, Elapsed = 00:00:00.0100004\n Count = 29658, Largest = 346079, Elapsed = 00:00:00.0200006\n Count = 41234, Largest = 496007, Elapsed = 00:00:00.0300001\n Count = 52233, Largest = 642197, Elapsed = 00:00:00.0400015\n Count = 62740, Largest = 783707, Elapsed = 00:00:00.0500005\n Count = 104720, Largest = 1366609, Elapsed = 00:00:00.1000005\n Count = 178155, Largest = 2427463, Elapsed = 00:00:00.2000005\n Count = 243973, Largest = 3406421, Elapsed = 00:00:00.3000012\n Count = 306982, Largest = 4363897, Elapsed = 00:00:00.4000024\n Count = 365978, Largest = 5270231, Elapsed = 00:00:00.5000013\n Count = 619977, Largest = 9280757, Elapsed = 00:00:01.0000003\n</code></pre>\n\n<p>I followed up by running a few different size sieves, to get these results:</p>\n\n<p><strong>WITH A SIEVE</strong></p>\n\n<pre><code>PrimeTable.Initialize using assorted upper limits:\n Upper Limit = 10000001, PrimeCount = 664579, LastPrime = 9999991, Duration: 00:00:00.0340529 (includes JIT time)\n Upper Limit = 20000001, PrimeCount = 1270607, LastPrime = 19999999, Duration: 00:00:00.0618941\n Upper Limit = 200000001, PrimeCount = 11078937, LastPrime = 199999991, Duration: 00:00:00.9063038\n</code></pre>\n\n<p>Using ballpark numbers, it took the naive methods almost 1 second to generate around 620K primes with the largest near 9.3 million. Using a sieve, it took only 0.035 seconds to find the same (plus 40K more). For 1 seconds using a sieve, I could find over 11 million primes which is over 17X more than using naive methods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-07T13:42:32.857", "Id": "233590", "ParentId": "233209", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-30T22:08:49.847", "Id": "233209", "Score": "4", "Tags": [ "c#", "primes", "sieve-of-eratosthenes", ".net-core" ], "Title": "Prime Number Table, i.e. List<int>" }
233209
<p>This is my second script in my first language so I'm trying to get oriented and better foundations. I noticed in the <code>while</code> loop I got really messy but I couldn't google my way to a better solution that I could understand. With that, I'd appreciate any feedback that makes my code more "pythonic" or clean. </p> <pre class="lang-py prettyprint-override"><code>import random def card_deck(): card_faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] card_suits = ['♠', '♦', '♥', '♣'] deck = [] for i in card_suits: for j in card_faces: deck.append(j + ' ' + i) return deck def card_draw(deck): random.shuffle(deck) deck = deck.pop() return deck def card_value(card): card = str(card) if card[0] == 'J': return 10 elif card[0] == 'Q': return 12 elif card[0] == 'K': return 13 elif card[0] == 'A': return 14 else: card = int(card[0:2]) return card correct_guesses = 0 deck = card_deck() card = card_draw(deck) while True: card_points = card_value(card) if not deck: print("You've done it! You've won with", correct_guesses, "correct guesses!") break next_card = card_draw(deck) next_card_points = card_value(next_card) print("\nYou're card is: ", card) user_guess = input('\n(H)igher, (L)ower, or (S)ame?:\t') user_guess = user_guess.lower() if user_guess not in ('h', 'l', 's'): break if card_points &lt; next_card_points and user_guess == 'h': print("Correct!") correct_guesses += 1 card = next_card continue elif card_points &gt; next_card_points and user_guess == 'l': print("Correct!") correct_guesses += 1 card = next_card continue elif card_points == next_card_points and user_guess == 's': print("Correct!") correct_guesses += 1 card = next_card continue else: print('You lose the next card was ', next_card) print('You had', correct_guesses, 'correct guesses.') break <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>I may have went overboard on the Python-ification, but this is a refactoring of the current solution.</p>\n\n<p>What I did was create a <code>Card</code> class which contained the suit and value of the card. To get the value, I added all items to an array and then got the index of the card's value from the array's offset, which allowed <code>card_value</code> to be removed.</p>\n\n<p>There was lots of duplication when displaying that the user got the correct answer. I made this a function and was able to minimize the method's body by using an iterator which contained the current card and the previous card (thus avoiding having to set the previous card to the current card and then get the next card.)</p>\n\n<p>Here is a rewritten version: (comments to follow)</p>\n\n<pre><code>import random\nimport itertools\n\ncard_faces = [\n '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King',\n 'Ace'\n]\n\n\nclass Card:\n \"\"\"\n Defines a Card with a suit and face, and allows retrieving the points of the card\n \"\"\"\n\n def __init__(self, face_suit):\n self.face = face_suit[0]\n self.suit = face_suit[1]\n\n def getPoints(self):\n return card_faces.index(self.face) + 2\n\n def __str__(self):\n return self.face + ' ' + self.suit\n\n def __gt__(self, other):\n return self.getPoints() &gt; other.getPoints()\n\n def __lt__(self, other):\n return self.getPoints() &lt; other.getPoints()\n\n def __eq__(self, other):\n return self.getPoints() == other.getPoints()\n\n\ndef generate_card_deck():\n \"\"\"\n Creates a shuffled list of cards as [(c0, c1), (c1, c2), ...]\n \"\"\"\n card_suits = ['♠', '♦', '♥', '♣']\n deck = list(map(Card, itertools.product(card_faces, card_suits)))\n random.shuffle(deck)\n return deck\n\n\ndef user_guessed_correctly():\n \"\"\"\n Congratulates the user if they have a correct guess, and increments\n the counter\n \"\"\"\n print(\"Correct!\")\n global correct_guesses\n correct_guesses += 1\n\n\ndef pairwise(iterable):\n \"s -&gt; (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\ncorrect_guesses = 0\ndeck = pairwise(generate_card_deck())\n\nwhile True:\n card, next_card = next(deck, (None, None))\n if not card:\n print(\"You've done it! You've won with\", correct_guesses,\n \"correct guesses!\")\n break\n\n print(\"Your card is: \", card)\n user_guess = input('(H)igher, (L)ower, or (S)ame?:\\t').lower()\n if user_guess not in ('h', 'l', 's'):\n break\n\n if (card &lt; next_card and user_guess == 'h') or (\n card &gt; next_card and user_guess == 'l') or (card == next_card\n and user_guess == 's'):\n user_guessed_correctly()\n else:\n print('You lose: the next card was ', next_card)\n print('You had', correct_guesses, 'correct guesses.')\n break\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T16:36:43.107", "Id": "455794", "Score": "0", "body": "Really well done. Thank you for the feedback, I'm going to refer back to your example as I press on. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T03:37:25.530", "Id": "233215", "ParentId": "233213", "Score": "3" } } ]
{ "AcceptedAnswerId": "233215", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T01:56:11.077", "Id": "233213", "Score": "7", "Tags": [ "python", "beginner", "game" ], "Title": "Lower, Higher, or Same Card Game" }
233213
<p>I am trying to build an OOP design for an election system.</p> <p>A citizen can nominate themselves to be a contender. So all contenders are citizens. I was thinking of keeping the relation ship IS-A by having contender extend citizen, but I am not able to understand how i will have a citizen nominate themselves then.</p> <p>Citizen can become followers of contenders and receive a mail about any idea they post. Further more if they receive a mail and were also a contender they would send mail to their followers. Contenders can post at most 3 ideas in their manifesto and low quality contenders are dropped from the election (ie if they have at least 1 idea which has rating &lt;5 from more than 3 people). Also if a person gives a rating > 5 to an idea, they are auto added as followers of the contender</p> <p>Also if a contender is removed their rating of an idea still counts as they were a citizen also when they made it.</p> <p>eg.</p> <pre><code>class Citizen { public: bool Citizen::nominate(Eboard* b) { return b-&gt;addContender(Contender(this)); } } class Contender: public Citizen { Citizen* c; public: Contender(Citizen* c); } </code></pre> <p>(1) I first thought it is fine to not have an ISA relationship. But with the mail constraint, i need to maintain a list of base class objects, as followers can be citizen or contenders.</p> <p>(2) When system is required to maintain some constraints, take additional actions upon things like candidate giving rating- should the system be passed by reference from the main or should this be directly able to get the system singleton and operate on that.</p> <p>Searching what can be done I got this helpful answer <a href="https://softwareengineering.stackexchange.com/questions/317297/inheritance-vs-additional-property-with-null-value?newreg=f39ae86e18e04b2f8136380610c4ffc8">https://softwareengineering.stackexchange.com/questions/317297/inheritance-vs-additional-property-with-null-value?newreg=f39ae86e18e04b2f8136380610c4ffc8</a> which seemed to fit with what i could do</p> <p>Can someone please help me with the best design choice here?</p> <p>I was not able to get this so i did something like this in which i made the property whether a citizen is a contender which forced me to have functions like postIdea for citizens also. </p> <pre><code>#include &lt;iostream&gt; #include &lt;list&gt; #include &lt;vector&gt; #include &lt;unordered_map&gt; using namespace std; class Citizen; class Idea; class Manifesto { public: vector&lt;Idea*&gt; ideas; Citizen* contender; Manifesto(Citizen* contender) { this-&gt;contender = contender; } bool addIdea(Idea* idea) { if (ideas.size() == 3) { return false; } ideas.push_back(idea); } }; //the rating is more than 5, then citizen is added as a follower of the contender. class Idea { public: unordered_map&lt;Citizen*, int&gt; citizenRating; Citizen* contender; Idea(Citizen* contender){ this-&gt;contender = contender; } void setRating(Citizen* citizen, int rating) { citizenRating[citizen] = rating; } bool isRatedLt5ByGt3Voters() { int cnt = 0; for(auto iter = citizenRating.begin(); iter != citizenRating.end();iter++) { if (iter-&gt;second &lt; 5) { cnt++; } } return cnt &gt; 3; } }; class Citizen { public: bool isContender; list&lt;Citizen*&gt; followers; list&lt;Citizen*&gt; following; // for removing Manifesto* manifesto; Citizen() { isContender = false; manifesto = nullptr; } bool nominate() { cout&lt;&lt;"here"; isContender = true; manifesto = new Manifesto(this); } bool setRating(Idea* idea, int rating) { idea-&gt;setRating(this, rating); // Ideally logic below this should be done by election system // not by the citizen, so probably call like Election.setRating(citizen, idea, rating) which will call this // and do below logic if (rating &gt; 5) { makeFollower(manifesto-&gt;contender); } for(auto idea:manifesto-&gt;ideas) { if (idea-&gt;isRatedLt5ByGt3Voters()) { removeAsContender(); break; } } } void makeFollower(Citizen* contender) { contender-&gt;followers.push_back(this); following.push_back(contender); } bool postIdea(Idea* idea) { this-&gt;manifesto-&gt;addIdea(idea); sendMail(); } bool sendMail() { for(auto el: followers) { el-&gt;getMail(); } } bool getMail() { std::cout&lt;&lt;"Got mail"; sendMail(); } bool removeAsContender() { this-&gt;isContender = false; followers.clear(); for (auto iter = following.begin(); iter != following.end(); iter++) { for (auto iter2 = (*iter)-&gt;followers.begin(); iter2 != (*iter)-&gt;followers.end(); iter2++) { if (*iter2 == this) { (*iter)-&gt;followers.erase(iter2); } } } } }; int main() { std::cout &lt;&lt; "Hello, World!" &lt;&lt; std::endl; Citizen c; c.nominate(); c.postIdea(new Idea(&amp;c)); Citizen c2; c2.makeFollower(&amp;c); c.postIdea(new Idea(&amp;c)); return 0; } </code></pre> <p>In the second version of my attempt i try to separate what the election does from what citizen does. So eg. the election should be responsible for sending mail , or adding followers on citizen's actions. Is this design better?</p> <pre><code>#include &lt;iostream&gt; #include &lt;unordered_set&gt; #include &lt;vector&gt; #include &lt;unordered_map&gt; using namespace std; class Citizen; class Idea; class Manifesto { public: vector&lt;Idea *&gt; ideas; Citizen *contender; Manifesto(Citizen *contender) { this-&gt;contender = contender; } bool addIdea(Idea *idea) { if (ideas.size() == 3) { return false; } ideas.push_back(idea); } }; class Idea { public: unordered_map&lt;Citizen *, int&gt; citizenRating; Citizen *contender; Idea(Citizen *contender) { this-&gt;contender = contender; } void setRating(Citizen *citizen, int rating) { citizenRating[citizen] = rating; } bool isRatedLt5ByGt3Voters() { int cnt = 0; for (auto iter = citizenRating.begin(); iter != citizenRating.end(); iter++) { if (iter-&gt;second &lt; 5) { cnt++; } } return cnt &gt; 3; } }; class Election; class Citizen { public: bool isContender; unordered_set&lt;Citizen *&gt; followers; unordered_set&lt;Citizen *&gt; following; // for removing Manifesto *manifesto; Election *election; Citizen(Election *election) { isContender = false; manifesto = nullptr; this-&gt;election = election; } // Citizen should be able to get all contenders. unordered_set&lt;Citizen *&gt; getAllContenders(); // Citizen should be able to nominate self. bool nominate(); // These are defined outside as they need to dereference Election // and Election needs to dereference citizen bool setRating(Idea *idea, int rating) { idea-&gt;setRating(this, rating); } bool postIdea(Idea *idea) { this-&gt;manifesto-&gt;addIdea(idea); } }; class Election { unordered_set&lt;Citizen *&gt; contenders; public: unordered_set&lt;Citizen *&gt; getAllContenders() { return contenders; } void addContender(Citizen *contender) { contenders.insert(contender); } void nominate(Citizen *citizen) { citizen-&gt;nominate(); contenders.insert(citizen); } void makeFollower(Citizen *citizen, Citizen *contender) { contender-&gt;followers.insert(citizen); citizen-&gt;following.insert(contender); } bool removeAsContender(Citizen *contender) { contender-&gt;isContender = false; contenders.erase(contender); contender-&gt;followers.clear(); for (auto iter = contender-&gt;following.begin(); iter != contender-&gt;following.end(); iter++) { (*iter)-&gt;followers.erase(contender); } } public: bool setRating(Citizen *citizen, Citizen *contender, Idea *idea, int rating) { citizen-&gt;setRating(idea, rating); if (rating &gt; 5) { makeFollower(citizen, contender); } for (auto idea:contender-&gt;manifesto-&gt;ideas) { if (idea-&gt;isRatedLt5ByGt3Voters()) { removeAsContender(contender); break; } } }; bool postIdea(Citizen *contender, Idea *idea) { contender-&gt;postIdea(idea); sendMail(contender); } bool sendMail(Citizen *contender) { cout &lt;&lt; "in send " &lt;&lt; contender-&gt;followers.size(); for (auto el: contender-&gt;followers) { cout &lt;&lt; "trying "; getMail(el); } } bool getMail(Citizen *c) { std::cout &lt;&lt; "Got mail"; if (c-&gt;isContender) { sendMail(c); } } }; unordered_set&lt;Citizen *&gt; Citizen::getAllContenders() { return election-&gt;getAllContenders(); } bool Citizen::nominate() { isContender = true; manifesto = new Manifesto(this); election-&gt;addContender(this); } int main() { Election e; std::cout &lt;&lt; "Hello, World!" &lt;&lt; std::endl; Citizen c(&amp;e); c.nominate(); // citizen can self nominate Idea *idea = new Idea(&amp;c); e.postIdea(&amp;c, idea); Citizen c2(&amp;e); e.setRating(&amp;c2, &amp;c, idea, 8); e.postIdea(&amp;c, new Idea(&amp;c)); cout &lt;&lt; "CONT" &lt;&lt; e.getAllContenders().size(); return 0; } </code></pre> <p>I do not like this design as Citizen class should not have anything to do with functions like <code>sendMail</code>, but since the same object can be made a contender anytime, i can only think of composition which fails due to it also requiring to extend citizen.</p>
[]
[ { "body": "<p>Start by writing down the use-cases in plain text. What is it that you are designing and how should it work. \"It is a noun so it must be a class\" is a common mistake. You don't seem to be designing \"citizens\" but rather mail lists. </p>\n\n<p>So the class here should perhaps be <code>MailList</code>, which can contain a list of registered citizens. One instance of the mail list per contender, contender probably doesn't need to be a class, meaning you'll have a <code>MailList</code> array the size of the number of contenders. There's no direct relation between citizen and contender that motivates inheritance or polymorphism.</p>\n\n<p>You can have a citizen class still, but it would be a pretty \"dumb\" one only containing name and e-mail address. Or possibly just the e-mail address, in which case a class isn't needed and it can be a string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T14:22:39.640", "Id": "233272", "ParentId": "233216", "Score": "1" } }, { "body": "<p>Here are some things that may help you improve your code. I'll start with some details and then move on to the larger design issues.</p>\n\n<h2>Make sure all paths return a value</h2>\n\n<p>The <code>Citizen::setRating()</code> and <code>Citizen::postIdea()</code> and many other functions claim to return <code>bool</code> but don't return anything.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Especially in a very simple program like this, there's little reason to use that line. Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. </p>\n\n<h2>Keep internal class details <code>private</code></h2>\n\n<p>It's best to keep the internals of a class private to reduce linkage among objects to only what they need. This simplifies the interface and therefore the maintenance. Right now, for example, one could easily bypass the <code>Manifesto::addIdea()</code> function and add 300 ideas directly to the structure. That's poor encapsulation.</p>\n\n<h2>Avoid using pointers</h2>\n\n<p>Modern C++ doesn't really need pointers very often. It's usually better to either use a smart pointer, such as <a href=\"http://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a> or simply use objects or object references. For this code, which is used depends very much on the class design which is the subject of some suggestions below.</p>\n\n<h2>Avoid <code>new</code> and <code>delete</code></h2>\n\n<p>If you don't use pointers, you have much less reason to use <code>new</code> and <code>delete</code>. But if you do use <code>new</code>, each instance of <code>new</code> must be matched to a corresponding <code>delete</code> or your code will leak memory. Often the best way to make sure no memory is leaked is to put <code>delete</code> in a destructor.</p>\n\n<h2>Rethink your class design</h2>\n\n<p>One way to approach class design is to begin with a written description. Examining the description, <em>nouns</em> suggest objects and <em>verbs</em> suggest methods. You have already identified <code>Citizen</code>, <code>Idea</code>, <code>Manifesto</code> and <code>Election</code> as potential classes and <code>Candidate</code> as a potential class. Each of the suggestions below will discuss a specific way to approach the class design. </p>\n\n<h2>Decide what the code should do</h2>\n\n<p>It seems to me that the first thing to decide is how you want to use this code. Given the title of the question, I would expect that everything should happen in the context of an <code>Election</code> which suggests to me that rather than directly manipulating <code>Idea</code> or <code>Citizen</code> objects, <code>main()</code> should only have a single <code>Election</code> object and do everything within that context. That leads directly to the next suggestion.</p>\n\n<h2>Decide what each object needs to do</h2>\n\n<p>It is odd to me that an <code>Election</code> object doesn't actually seem to include voting but does seem to include sending mail. Perhaps this is only intended to represent a particular phase of the election which involves nominations of candidates and the dissemination of ideas. Because of the particular features of the class, I'm going to infer that it's intended to run a <em>simulation</em> of that particular phase of an election rather than being software that is used for an actual election. This is an important distinction because it suggests a very different pattern of use. I'm going to assume that it's a simulation for all of the suggestions below, but the general approach is applicable either way.</p>\n\n<h2>Decide on sequence and responsibility</h2>\n\n<p>The written description includes sentences like this one:</p>\n\n<blockquote>\n <p>Contenders can post at most 3 ideas in their manifesto and low quality contenders are dropped from the election (ie if they have at least 1 idea which has rating 5 from more than 3 people).</p>\n</blockquote>\n\n<p>We can glean many useful things from this particular sentence. First, only a <strong>contender</strong> can post an <strong>idea</strong> to their own <strong>manifesto</strong>. This seems to imply that the <code>Manifesto</code> should be publicly visible, but only managed by a contender, suggesting a <code>private</code> class with read-only <code>public</code> access. Second it says that a <strong>contender</strong> might be dropped from the <strong>election</strong> based on <strong>idea</strong> ratings. This implies a sequence but fails to spell out what that sequence is. That is, clearly the ideas must be rated before contenders are culled, and that ideas must be posted before they can be rated. We also know from the description that contenders must be nominated before they are changed from <strong>citizens</strong> to <strong>candidates</strong>. This fuzziness about sequence is why this code is not yet well designed. Are there distinct phases such as nomination, manifesto generation, voting, culling? Or can any action be taken at any time? Further what happens to the already rated ideas if a candidate is culled from the election and loses contender status? Also, it is not explicitly stated <em>which entity</em> does the culling of candidates. In general passive verbs are a sign of a vague or incomplete description.</p>\n\n<h2>Start from the public interface</h2>\n\n<p>After the sequence and responsibilities are clarified, it is often useful to start with a public interface for a class. For example, I would say that if we're trying to run a simulation, what do we want from that simulation? What are we trying to learn or see? Do we want to, say, derive an equation that predicts the number of emails sent given the size of the election and number of candidates? Or maybe we just want the detailed chronology to do a more open ended investigation. It's good practice to define the minimally sufficient public interface for the main class or classes before working on the details of implementation.</p>\n\n<h2>Don't let technology drive the solution</h2>\n\n<p>The very first sentence in the description is this:</p>\n\n<blockquote>\n <p>I am trying to build an OOP design for an election system.</p>\n</blockquote>\n\n<p>It seems to me that there are some potential problems with that. First, is the goal to create \"an OOP design\" or actual working code? Second, it's not necessarily true that OOP is the right approach for every problem. It seems to me that the problem definition is still too vague to assume that. Third, \"an election system\" is ambiguous as noted above because it actually seems that perhaps it's a real election, or maybe it's a simulation and that it's apparently only a particular subset of election activities. I'm sure that seems overly picky about one sentence, but I find that the greater clarity one can achieve for a succinct problem statement, the better the subsequent design and code. It's worthwhile trying to clarify before investing a lot of time in design or coding.</p>\n\n<h2>Focus on the user</h2>\n\n<p>Instead of starting with a code-centric approach, think of the <em>user</em> instead. \"Who will be using the software and what will they want from it?\" is much more likely to guide a successful design and implementation than thinking about code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T14:36:26.877", "Id": "233273", "ParentId": "233216", "Score": "3" } } ]
{ "AcceptedAnswerId": "233273", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T04:55:55.180", "Id": "233216", "Score": "6", "Tags": [ "c++", "object-oriented", "comparative-review" ], "Title": "OOP design for election board" }
233216
<p>I'm learning OOPs design principles and design patterns. As an exercise, I came up with this model for multiple user authentication using OOPs. I plan to build this on top of a Flask server, but I've just mocked the behavior for now. </p> <p>Please let me know your thoughts about the implementation design. Thanks in advance. </p> <blockquote> <p>User Model:</p> </blockquote> <pre><code>class User: def __init__(self, name: str = None, ph_no: str = None, username: str = None, password: str = None): self.username = username self.password = Utils.encrypt(password) self.ph_no = ph_no self.name = name Utils.persist_in_db(self) def update_password(self, old_password: str, new_password: str): if Utils.encrypt(old_password) == self.password: self.password = Utils.encrypt(new_password) else: raise PasswordNotCorrectException() def authenticate(self, password) -&gt; bool: return self.password == Utils.encrypt(password) def __repr__(self): return f'&lt;User: {OrderedDict(self.__dict__)}&gt;' </code></pre> <blockquote> <p>Core logic: </p> </blockquote> <pre><code>import threading import time from login_service import LoginService from models.user import User class BMSApp: def __init__(self): self.mock() @staticmethod def mock(): user1 = UserThread(name='Rick', username='ricky', ph_no='xxxxx', password='password1234') user2 = UserThread(name='Morty', username='morty', ph_no='xxxx', password='lifeisawesome') user1.start() user2.start() user1.join() user2.join() class UserThread(threading.Thread): def __init__(self, **kwargs): super().__init__() self.kwargs = kwargs def run(self) -&gt; None: BookingStrategy.execute(**self.kwargs) class BookingStrategy: @staticmethod def execute(**kwargs): login_result = LoginService.login(**kwargs) if login_result[0]: print(f"Login succeeded for user {login_result[1]}") else: print(f"Login failed for user {login_result[1]}") </code></pre> <blockquote> <p>Mock Login service:</p> </blockquote> <pre><code>class LoginService: @staticmethod def login(**kwargs): # TODO: implement proper login functionality user = User(**kwargs) return random.choice([(True, user), (False, user)]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T05:54:22.583", "Id": "455837", "Score": "0", "body": "Independent of whether this is good OOP, your password update function seems to expect that Utils,encrypt() is self-reversible. That would be a **horrible choice for password safety**! All serious password storage mechanisms go to great lengths to ensure passwords can not simply be decrypted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T07:12:16.710", "Id": "455838", "Score": "0", "body": "Sorry, I meant to write `Utils.encrypt(old_password) == self.password`. Fixed it now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T08:11:55.880", "Id": "455842", "Score": "0", "body": "That still does not consider salting. And the name `encrypt()` implies that there is a matching `decrypt()` function, and if there is, you're still not doing it right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T09:38:22.403", "Id": "455858", "Score": "1", "body": "Considering there are answers posted now, please don't edit your code further or it will be considered invalidation of the current answers. The response to such will be a rollback of the edit. Consider posting a follow-up question linking back to this one if you have updated code that you'd like to have reviewed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T09:38:38.277", "Id": "455859", "Score": "0", "body": "@Hans-MartinMosner Please post reviews as an answer instead of a comment, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T10:00:44.290", "Id": "455867", "Score": "1", "body": "Would recommend you to read this book https://github.com/cosmicpython/book" } ]
[ { "body": "<p>First of all, I am not at all sure it is good idea to learn OOP by re-implementing security-sensitive feature for a web-framework, which already has support for such things. Please, at least consider using Flask-Security, Flask-Login, Flask-Principal unless you plan a total rewrite of all those. Also, I see plain text passwords in use - most of the time a security risk.</p>\n\n<p>That said, I can find the following problems:</p>\n\n<ol>\n<li><p>Persistence service is too intrusive and its logic is not clear.\nFor example, you are creating a user just to login: Why do you want to\npersist anything someone tries to enter as a login attempt? Consider\nusing some ORM, where you can control object's persistence, or come\nup with something better than object dealing with its persistence.</p>\n\n<p>Those aspects better be invisible in the model. In Python, it's probably best to use a DTO (data-transfer object, received from the login form, usually a dict) until identity is verified.</p></li>\n<li>I do not really understand why you are using threads. In the Flask environment one can use a session as an abstraction, so dealing at thread level is strange and can make your code too dependent on a specific implementation, preventing porting it to multiprocessing, async/greenlets and the like.</li>\n</ol>\n\n<p>There are some naming problems (what is <code>ph_no</code>?).</p>\n\n<p>In my opinion the best place for OOP in user authentication is (in addition to <code>User</code> class) a possibility to define different authentication strategies (and inject dependencies like <code>Utils.encrypt</code> that way). Then, if a more complex system is in question - role-based authorization, etc, etc. The code you presented above is not geared towards those goals. Instead, it deals with low-level concerns which are already solved in the framework.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T09:11:57.467", "Id": "455851", "Score": "0", "body": "Encrypted, not plaintext. Although it should be hashed. Esp. since OP is treating it as a hash, ie. he is not decrypting the password." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-02T16:32:39.917", "Id": "455914", "Score": "0", "body": "Hmmm... Question was changed after my answer. I believe it was `Utils.decrypt` - so plain text password could be obtained." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T12:27:25.367", "Id": "233224", "ParentId": "233218", "Score": "8" } }, { "body": "<p>In general objects that the parameters of the constructors have dependencies, for example username with password with name, should be readonly in order to avoid changes during the execution, in python basically is make that parameters private and have a decorator that only allows read them. You will avoid issues such has create an object and after that change the username, or even the password.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T16:40:53.477", "Id": "233229", "ParentId": "233218", "Score": "2" } } ]
{ "AcceptedAnswerId": "233224", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-01T08:02:43.230", "Id": "233218", "Score": "14", "Tags": [ "python", "object-oriented" ], "Title": "OOP design for multiple user authentication" }
233218