body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm learning C, and currently I follows <code>C99</code> standard. Here is my implementation of integer-stack, which is just a stack you can do: push, pop, and print the content of the stack.</p> <p>Here are some problems I currently have:</p> <ol> <li>Is that <code>#define STACK_MAX 1000</code> a good idea? Should I consider make it configurable in runtime?</li> <li>It's impossible to make <code>struct int_stack *</code> to <code>int_stack *</code>, like C++, right?</li> </ol> <p>Other than these two problem, I need feedbacks about anything you think important, but I missed out, thank you.</p> <hr /> <p><strong>int_stack.h</strong>:</p> <pre><code>#ifndef INT_STACK_H #define INT_STACK_H #include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; #define STACK_MAX 1000 typedef struct int_stack { int top; int data[STACK_MAX]; bool (*push)(struct int_stack *, int); bool (*pop)(struct int_stack *, int *); int (*size)(struct int_stack *); void (*print_stack)(struct int_stack *); } int_stack; bool push(int_stack *self, int item) { if (self-&gt;top == STACK_MAX) return false; self-&gt;data[self-&gt;top++] = item; return true; } bool pop(int_stack *self, int *out) { if (size(self) == 0) return false; *out = self-&gt;data[--self-&gt;top]; return true; } int size(int_stack *self) { return self-&gt;top; } void print_stack(int_stack *self) { printf(&quot;| top |\n&quot;); for (int i = self-&gt;top-1; i &gt;= 0; i--) printf(&quot;| %3d |\n&quot;, self-&gt;data[i]); } void array_zeros_init(int A[], int size) { for (int i = 0; i &lt; size; i++) A[i] = 0; } void stack_init(struct int_stack *stack) { stack-&gt;top = 0; array_zeros_init(stack-&gt;data, STACK_MAX); stack-&gt;push = &amp;push; stack-&gt;pop = &amp;pop; stack-&gt;size = &amp;size; stack-&gt;print_stack = &amp;print_stack; } #endif // !INT_STACK_H </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T09:12:20.603", "Id": "505540", "Score": "0", "body": "Maybe make your function pointers static ? I don’t know much about c though, more of a c++ guy..." } ]
[ { "body": "<p>We wouldn't normally put the function definitions in the header like that. Just write the <em>declarations</em> that are needed by the calling code, and put the definitions into their own source file.</p>\n<p>It seems odd to have these function pointers:</p>\n<blockquote>\n<pre><code>bool (*push)(struct int_stack *, int);\nbool (*pop)(struct int_stack *, int *);\nint (*size)(struct int_stack *);\nvoid (*print_stack)(struct int_stack *);\n</code></pre>\n</blockquote>\n<p>Nothing needs them, so just omit them.</p>\n<p><code>pop()</code> uses <code>size()</code> before the latter is defined. We could solve this by re-ordering, but separating declarations from definitions will naturally fix this.</p>\n<p><code>size()</code> and <code>print()</code> don't need to modify the stack, so they should accept pointer to const object.</p>\n<p>The function names are all vulnerable to collisions. I'd suggest adding a common prefix to distinguish and group them.</p>\n<p>Writing zeros to the unused elements is a bit pointless, as those elements are not reachable through the public interface.</p>\n<p>Here's my re-write:</p>\n<h3>Header:</h3>\n<pre><code>#ifndef INT_STACK_H\n#define INT_STACK_H\n\n#include &lt;stdbool.h&gt;\n\ntypedef struct int_stack int_stack;\n\nint_stack *stack_create(void);\nvoid stack_free(int_stack *self);\n\nbool stack_push(int_stack *self, int item);\nbool stack_pop(int_stack *self, int *out);\nint stack_size(const int_stack *self);\nvoid stack_print(const int_stack *self);\n\n#endif // !INT_STACK_H\n</code></pre>\n<h3>Implementation</h3>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#define STACK_MAX 1000\n\nstruct int_stack {\n int top;\n int data[STACK_MAX];\n};\n\n\nint_stack *stack_create(void) {\n int_stack *stack = malloc(sizeof *stack);\n if (stack) {\n stack-&gt;top = 0;\n }\n return stack;\n}\n\nvoid stack_free(int_stack *self) {\n free(self);\n}\n\nbool stack_push(int_stack *self, int item) {\n if (self-&gt;top == STACK_MAX) {\n return false;\n }\n self-&gt;data[self-&gt;top++] = item;\n return true;\n}\n\nbool stack_pop(int_stack *self, int *out) {\n if (stack_size(self) == 0) {\n return false;\n }\n *out = self-&gt;data[--self-&gt;top];\n return true;\n}\n\nint stack_size(const int_stack *self) {\n return self-&gt;top;\n}\n\nvoid stack_print(const int_stack *self) {\n printf(&quot;| top |\\n&quot;);\n for (int i = self-&gt;top-1; i &gt;= 0; i--) {\n printf(&quot;| %3d |\\n&quot;, self-&gt;data[i]);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T15:04:07.637", "Id": "256150", "ParentId": "256128", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T08:07:47.653", "Id": "256128", "Score": "1", "Tags": [ "c", "stack" ], "Title": "Stack of integers in C" }
256128
<p>This is my solution for exercise 1-23 from the book &quot;The C programming language&quot;.</p> <p>Exercise 1-23: Write a program that removes all comments from a C program.</p> <p>Key idea:</p> <ul> <li>if the start of a quoted string is detected, then I call a function that prints the entire string. handled '&quot;', '\&quot;'</li> <li>else if a start of a single line comment is detected, I use a second function to skip it.</li> <li>else if a start of a multiple line comment is found, I used a third function to skip it.</li> <li>else just print the char</li> </ul> <p>I made an effort to make the code readable. I'd like your feedback related to all aspects of the solution. Be harsh, but in a constructive way.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; #define DOUBLE_QUOTE_CHAR '&quot;' #define BASK_SLASH '\\' #define NEW_LINE_CHAR '\n' #define FORWARD_SLASH '/' #define ASTERISK '*' #define SINGLE_QUOTE_CHAR '\'' void print_quoted_string(); /* called when a quote char that indicate begining of string is encountered. print the quoated string then stop */ void skip_single_line_comment(); /* called when we see // that indicate start of a single-line comment . skip that comment */ void skip_multiple_line_comment(); int main(void) { char cur_char; bool prev_forward_slash = false; // to handle //, /* bool prev_single_quote = false; // to handle '&quot;' bool prev_back_slash = false; // to handle '\&quot;' while ( (cur_char = getchar()) != EOF) { if (cur_char == DOUBLE_QUOTE_CHAR &amp;&amp; !prev_single_quote &amp;&amp; !prev_back_slash) // to exclude '&quot;' and '\&quot;'. Are there any other casse ? print_quoted_string(); else if (prev_forward_slash &amp;&amp; cur_char == FORWARD_SLASH) { // this // can not be inside a string. because the first if statement guarentee it. skip_single_line_comment(); prev_forward_slash = false; } else if (prev_forward_slash &amp;&amp; cur_char == ASTERISK ) { skip_multiple_line_comment(); prev_forward_slash = false; } else { if (prev_forward_slash) putchar(FORWARD_SLASH); // since we don't print a forward slash until we read the character after it. if (cur_char == FORWARD_SLASH) // we should not print this forward slash now since it may be followed by * prev_forward_slash = true; else if (cur_char == SINGLE_QUOTE_CHAR) { prev_single_quote = true; putchar(cur_char); } else if (cur_char == BASK_SLASH) { prev_back_slash = true; putchar(cur_char); } else { prev_single_quote = prev_forward_slash = prev_back_slash = false; putchar(cur_char); } } } return 0; } void print_quoted_string() { putchar(DOUBLE_QUOTE_CHAR); /* print the start quote of the string */ bool prev_char_is_escape_char = false; /* used to handle the escape sequences issues. for example: &quot;\\&quot; , &quot;\&quot;&quot;, &quot;\\\\\&quot;&quot; */ char cur_char; while (1) { cur_char = getchar(); if (cur_char == DOUBLE_QUOTE_CHAR &amp;&amp; !prev_char_is_escape_char) /* this quote char is the end quote of the string */ break; putchar(cur_char); /* current char is an escape char iff it's a back slash and not proceeded by escape char */ prev_char_is_escape_char = (cur_char == BASK_SLASH &amp;&amp; !prev_char_is_escape_char); } putchar(DOUBLE_QUOTE_CHAR); /* print the end quote of the string */ } void skip_single_line_comment() { while (getchar() != NEW_LINE_CHAR); putchar(NEW_LINE_CHAR); } void skip_multiple_line_comment() { char prev_char = '/'; char cur_char = '*'; while (1) { char cur_char = getchar(); if (prev_char == '*' &amp;&amp; cur_char == '/') { putchar(NEW_LINE_CHAR); return; } prev_char = cur_char; } } </code></pre>
[]
[ { "body": "<p>First a classic bug: <code>char cur_char;</code> ... <code>(cur_char = getchar()) != EOF</code>. The variable must be <code>int</code> not <code>char</code> or you can't compare it with <code>EOF</code>. Yeah it's really stupid that <code>getchar</code> gets an int, not a char, but that's how it is.</p>\n<hr />\n<p>I know this is just a simple program and performance, maintainability etc isn't import. If it was a real production quality program though, it would preferably be written differently. For the sake of learning, lets pretend it is:</p>\n<p>Then overall, you could be checking against a look-up table rather than by using a complex series of if-else if. They are kind of hard to read, you get the various different behavior upon finding certain comment characters scattered over various nested if-else if. Also the compiler is less likely to translate the if-else if to some table look-up, more likely this would generate a bunch of branches which are very bad for loop performance.</p>\n<p>A look-up table followed by a centralized &quot;take action depending on result&quot; code like for example a <code>switch</code> would improve execution speed and readability/maintainability both.</p>\n<p>The simplest form of such a table lookup would be to <code>strchr(&quot;\\&quot;\\\\\\n/*\\'&quot;, input)</code> then take different actions based on if <code>strchr</code> returned NULL or not.</p>\n<p>So rather than defining all comment characters with macros, you'd rather have a <code>typedef enum { DOUBLE_QUOTE_CHAR, BACK_SLASH, ... NO_COMMENT } comment_t;</code> etc corresponding to the index passed to the string literal used by <code>strchr</code>. Then you can do:</p>\n<pre><code> const char comment_characters[] = &quot;\\&quot;\\\\\\n/*\\'&quot;;\n const char* comment_found = strchr(comment_characters, input)\n comment_t comm;\n\n if(comment_found)\n comm = (comment_t) (comment_found - comment_characters); // pointer diff arithmetic\n else // strchr returned NULL\n comm = NO_COMMENT;\n\n switch(comm)\n {\n case DOUBLE_QUOTE_CHAR: /* do double quote stuff */ break;\n case BACK_SLASH: /* do backslash stuff */ break;\n\n default: /* NO_COMMENT etc, do nothing */\n }\n</code></pre>\n<p>You can even take readability/maintainability a bit further almost to extremes by doing this instead:</p>\n<pre><code> const char comment_characters [N] = // where N is some size &quot;large enough&quot;\n {\n [DOUBLE_QUOTE_CHAR] = '\\&quot;',\n [BACK_SLASH] = '\\\\',\n [N-1] = '\\0', // strictly speaking not necessary but being explicit is nice\n };\n</code></pre>\n<p>This guarantees integrity between the string and the enum indices.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T16:18:53.960", "Id": "505589", "Score": "0", "body": "I write this solution based only on what I have learned from chapter 1 of the book. So, I didn't know any of what you said. which makes your reply very useful. thank you so much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T20:29:43.700", "Id": "505611", "Score": "1", "body": "`getchar()` returning an `int` is very much not stupid. If it returned a `char`, the `EOF` value would need to also fit in a `char`, which would mean it would need to have the value of some valid actual character. That would mean that you'd need to have some other way to figure out if the `EOF` return value was an actual end-of-file, or the character. E.g. with `strtol()`, you need to check `errno`. But since it's not modified if there is _no_ error, it means you need to set `errno = 0` before _each call_, if you want to detect errors. That's worse than returning `int`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T07:13:19.180", "Id": "505631", "Score": "0", "body": "@ilkkachu There's no rationale here. Back in the days when all of this was designed at a whim, 7 bit token tables were used, so they could simply have picked any value with MSB set. Such as 0xFF. But no, surely it must be 0xFFFF...! Also god forbid if they designed the function as normally done in professional C, separating data from errors. `char getchar (err_t* result);`, that would have been to logical and readable. But no, getchar must not get a char! This API is just horrible bad, always been, no excuses, no rationales. Like most of stdio.h, likely the worst library ever designed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T09:49:17.927", "Id": "505643", "Score": "0", "body": "@Lundin, I was thinking more like `int getchar (char *c);` where the return value is the ok/error code, and the character read goes through the pointer. That way it would match most other functions. The caller has to use both anyway, so it's not like it would be in any way easier if the return value was the char. But yeah, I'm not too familiar with the history there, so consider that a post-facto rationalization if you want. Regardless, as long as it only returns one value, and all char values are valid characters, the retval has to be bigger than a char, regardless of what size they are." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T11:31:56.260", "Id": "256138", "ParentId": "256133", "Score": "6" } }, { "body": "<p>Few problems:</p>\n<ul>\n<li><p>If a quoted string is not terminated, <code>print_quoted_string</code> becomes an infinite loop. Granted, such input is malformed, but your program shall fail gracefully.</p>\n</li>\n<li><p>Pay attention to a backslash-newlines:</p>\n<pre><code>// This \\\n is a comment.\n\n/\\\n/ This is also a comment\n\n/\\\n* Even this is a comment */\n</code></pre>\n</li>\n</ul>\n<hr />\n<p>I strongly recommend to move the single quote processing into a function. This will greatly reduce the number of state variables. Also, keep in mind that the stray backslash has no meaning. Usually it is a syntax error; in any case it does not escape anything.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T21:04:36.423", "Id": "256158", "ParentId": "256133", "Score": "2" } } ]
{ "AcceptedAnswerId": "256158", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T09:54:51.893", "Id": "256133", "Score": "4", "Tags": [ "c" ], "Title": "Remove all comments from a C program" }
256133
<h2>Use case - motivation &amp; challenge</h2> <p>Hi all! I have been working with Python for the last two years, but never learned proper object-oriented programming and design patterns. I've decided for this year to close this gap by reading some books and applying the knowledge to a real-world problem. I am looking forward to learning a lot from all the suggestions :)</p> <p>To kick off my learning, <strong>I've decided to automate a recurring weekly task of filling some timesheets</strong> located in Microsoft Teams, using a bot to do the heavy lifting for me. The bot should perform the following steps:</p> <ul> <li>Navigate to the login page</li> <li>Fill in username and password</li> <li>Sign in</li> <li>Navigate to the excel page with the timesheet</li> <li>Fill in my weekly hours</li> </ul> <p>Currently, the bot does almost all steps, except the last two, which I haven't implemented yet.</p> <h2>Code breakdown</h2> <p>The code is quite simple. I rely heavily on selenium to perform all actions, so I want to create a chrome instance where the agent will perform its actions.</p> <p>Naturally, I first import the libraries I am going to use:</p> <pre><code>import os import time import random from selenium import webdriver from dataclasses import dataclass from abc import ABC, abstractmethod from webdriver_manager.chrome import ChromeDriverManager </code></pre> <p>Next up, I define <strong>immutable classes whose only purpose is to containerize information that is static</strong>, so that code duplication can be avoided.</p> <pre><code>@dataclass(frozen=True) class XPathsContainer: teams_login_button: str = '//*[@id=&quot;mectrl_main_trigger&quot;]/div/div[1]' teams_login_user_button: str = '//*[@id=&quot;i0116&quot;]' teams_login_next_button: str = '//*[@id=&quot;idSIButton9&quot;]' teams_login_pwd_button: str = '//*[@id=&quot;i0118&quot;]' teams_sign_in_button: str = '//*[@id=&quot;idSIButton9&quot;]' teams_sign_in_keep_logged_in: str = '//*[@id=&quot;KmsiCheckboxField&quot;]' @dataclass(frozen=True) class UrlsContainer: teams_login_page: str = 'https://www.microsoft.com/en-in/microsoft-365/microsoft-teams/group-chat-software' </code></pre> <p>Now, I try to implement a base class which is called <code>Driver</code>. <strong>This class contains the initialization of the chrome object and sets the foundations for other agents to be inherited</strong>. Each <code>Agent</code> child class might have (in the future) different actions but they must have a sleep method (to avoid restrictions in using bots), they must be able to click, write information and navigate to pages.</p> <pre><code>class Driver(ABC): def __init__(self, action, instruction, driver=None): if driver: self.driver = driver else: self.driver = webdriver.Chrome(ChromeDriverManager().install()) self.actions = { 'navigate': self.navigate, 'click': self.click, 'write': self.write } self.parameters = { 'action': None, 'instruction': None } @abstractmethod def sleep(self, current_tick=1): pass @abstractmethod def navigate(self, *args): pass @abstractmethod def click(self, *args): pass @abstractmethod def write(self, **kwargs): pass @abstractmethod def main(self, **kwargs): pass </code></pre> <p>Now I implement a basic <code>Agent</code> <strong>child class, which implements the logic of required functions of the base class</strong> <code>Driver</code>.</p> <pre><code>class Agent(Driver): def __init__(self, action, instruction, driver): super().__init__(action, instruction, driver) self.action = action self.instruction = instruction def sleep(self, current_tick=1): seconds = random.randint(3, 7) timeout = time.time() + seconds while time.time() &lt;= timeout: time.sleep(1) print(f&quot;Sleeping to replicate user.... tick {current_tick}/{seconds}&quot;) current_tick += 1 def navigate(self, url): print(f&quot;Agent navigating to {url}...&quot;) return self.driver.get(url) def click(self, xpath): print(f&quot;Agent clicking in '{xpath}'...&quot;) return self.driver.find_element_by_xpath(xpath).click() def write(self, args): xpath = args[0] phrase = args[1] print(f&quot;Agent writing in '{xpath}' the phrase '{phrase}'...&quot;) return self.driver.find_element_by_xpath(xpath).send_keys(phrase) def main(self, **kwargs): self.action = kwargs.get('action', self.action) self.instruction = kwargs.get('instruction', self.instruction) self.actions[self.action](self.instruction) self.sleep() </code></pre> <p>Finally, I've created a function that updates the parameters of the class whenever there is a set of actions and instructions that need to be executed under the same chrome driver. And I've created a function that takes a script of actions and executes them.</p> <pre><code>def update_driver_parameters(driver, values): params = driver.parameters params['action'] = values[0] params['instruction'] = values[1] return params def run_script(script): for script_line, script_values in SCRIPT.items(): chrome = Agent(None, None, None) for instructions in script_values: params = update_driver_parameters(chrome, instructions) chrome.main(**params) chrome.sleep() USER = os.environ[&quot;USERNAME&quot;] SECRET = os.environ[&quot;SECRET&quot;] SCRIPT = { 'login': [ ('navigate', UrlsContainer.teams_login_page), ('click', XPathsContainer.teams_login_button), ('write', (XPathsContainer.teams_login_user_button, USER)), ('click', XPathsContainer.teams_login_next_button), ('write', (XPathsContainer.teams_login_pwd_button, SECRET)), ('click', XPathsContainer.teams_sign_in_button), ('click', XPathsContainer.teams_sign_in_keep_logged_in), ('click', XPathsContainer.teams_sign_in_button), ] } run_script(SCRIPT) </code></pre> <h2>Concerns</h2> <p>Right now, I think the code has several major concerns, mostly related to being inexperienced in design patterns:</p> <ul> <li>I rely too much on Xpaths to make the bot do something which will result in an enormous data class if there are many steps to do;</li> <li>Also, relying on Xpaths could be bad, because if the page is updated, I will have to retrace steps, but this is probably necessary evil;</li> <li>I am not sure whether the implementation of an immutable class is the correct one. I've used <code>dataclass</code> for this;</li> <li>I have the feeling that the inheritance that I've implemented is quite clunky. I want to be able to share the same driver along with multiple classes. I don't want to create a new driver per action, I always want to fetch the latest context the driver did, but if a new agent is created then a new driver must be assigned to that agent;</li> <li>Maybe <code>kwargs</code> arguments could be implemented differently, I am never sure of the correct way to parse them without using <code>kwargs.get</code>;</li> <li>Inconsistent use of args and kwargs, could this be implemented differently?</li> </ul>
[]
[ { "body": "<p>Bug: on the first line of <code>run_script</code>, <code>SCRIPT.items()</code> should be <code>script.items()</code>. As written, it executes the global SCRIPT and not the argument to the function.</p>\n<p>It doesn't seem like Agent should inherit from Driver</p>\n<p>If you research Selenium best practices, you will find a few that make sense for your use case (most are geared toward testing). Two of them are Page Objects and preferred selector order.</p>\n<p>The idea behind Page Objects is to create a class for each page of the web application (or at least the pages you are using). The class encapsulates the data and methods needed to interact with that page. Your automation script then calls the methods on the Page Objects to automate a task. For example, a class for a login page might have methods for getting the login page, for entering a username, entering a password, clicking a remember me checkbox, and clicking a login button. A login method then calls these methods in the right order to do a login.</p>\n<p>This lets you isolate page specifics in one place. For example, the current design seems to suggest that if you automate another task, you would need to duplicate the <code>login</code> portion of <code>SCRIPT</code>. Then, if the login process changes every script needs to by updated. Using a Page Object, only the login page class needs to be changed.</p>\n<p>In practice the most reliable and robust way to select an element is by ID, then by name, css selector, and lastly Xpath is the least robust. It looks like most of your targets have IDs, so use that.</p>\n<p>Structure the project something like this:</p>\n<pre><code>project\n pages\n __init__.py # can be empty\n base.py # one for each page \n home.py\n login.py\n time.py\n ...etc... # add whatever other pages you use\n\n entertime.py # the script\n</code></pre>\n<p>Then</p>\nbase.py\n<pre><code>class BasePage:\n URL = None\n\n def __init__(self, driver=None):\n if driver is None:\n driver = webdriver.Chrome(ChromeDriverManager().install())\n \n self.driver = driver\n \n def click(self, locator, mu=1.5, sigma=0.3):\n &quot;&quot;&quot;simulate human speed and click a page element.&quot;&quot;&quot;\n self.dally(mu, sigma)\n self.driver.find_element(*locator).click()\n return self\n\n def dally(self, mu=1, sigma=0.2):\n pause = random.gauss(mu, sigma)\n while pause &gt; 0:\n delta = min(1, pause)\n pause -= delta\n time.spleep(delta)\n return self\n\n def navigate(self):\n if self.URL:\n self.driver.get(self.URL)\n return self\n \n raise ValueError(&quot;No where to go. No URL&quot;)\n \n def send_keys(self, locator, keys):\n self.driver.find_element(*locator).send_keys(keys)\n return self\n</code></pre>\nlogin.py\n<pre><code>from selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nfrom .base import BasePage\n \nclass LoginPage(BasePage):\n URL = 'https://www.microsoft.com/en-in/microsoft-365/microsoft-teams/group-chat-software'\n \n #locators for elements of the page\n LOGIN_BUTTON = (By.XPATH, '//*[@id=&quot;mectrl_main_trigger&quot;]/div/div[1]')\n USERNAME_FIELD = (By.ID, &quot;i0116&quot;)\n NEXT_BUTTON = (By.ID, &quot;idSIButton9&quot;)\n PASSWORD_FIELD = (By.ID, &quot;i0118&quot;)\n STAY_LOGGED_IN = (By.ID, &quot;KmsiCheckboxField&quot;)\n \n def click_next(self):\n self.click(*self.NEXT_BUTTON)\n return self\n \n def start_login(self):\n self.click(*self.LOGIN_BUTTON)\n return self\n\n def enter_username(self, username):\n self.send_keys(*self.USERNAME_FIELD, username)\n self.click_next()\n return self\n \n def enter_password(self, password):\n self.send_keys(*self.PASSWORD_FIELD, password)\n self.click_next()\n return self\n \n def toggle_stay_logged_in(self):\n self.driver.find_element(*self.STAY_LOGGED_IN).click()\n return self\n \n def login(self, username, password):\n self.navigate()\n self.start_login()\n self.enter_username(username)\n self.enter_password(password)\n self.toggle_stay_logged_in()\n self.click_next()\n \n return HomePage(driver) # or whatever page comes after a login\n</code></pre>\nentertime.py\n<pre><code>import os\n\nfrom pages import LoginPage, HomePage # what ever pages you need for the script\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nUSER = os.environ[&quot;USERNAME&quot;]\nSECRET = os.environ[&quot;SECRET&quot;]\n\nhomepage = LoginPage().login(USER, SECRET)\n\ntimepage = homepage.navigate_to_time_entry() # &lt;== whatever method you define\ntimepage.entertime() # &lt;== whatever method you define\n</code></pre>\n<p>I don't have MS teams to test this on, so this hasn't been tested. It is merely as suggestion on how to structure you project to make it easier to update, expand, etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T02:15:33.480", "Id": "506100", "Score": "1", "body": "Nice answer. The import pattern `entertime.py` is a pattern I used to use, I found it good until I was more comfortable with correctly setting up a `__main__.py`. I'd personally rename `entertime.py`to `pages/__main__.py` (with some import changes, `from . import LoginPage, ...`) and run the package with `python -m pages` rather than `python entertime.py`. Note using a `__main__.py` can be quite finicky at times so you (anyone) may prefer this much easier approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T03:59:02.260", "Id": "506103", "Score": "1", "body": "@Peilonrayz, I'm presuming that there will be multiple scripts like `entertime.py` to do different tasks. So a `__main__.py` wouldn't work, unless it took arguments to tell it what to do, e.g., something like `python -m teams entertime` would cause `__main__.py` to execute `entertime.py`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T04:30:01.057", "Id": "506105", "Score": "0", "body": "Oh good point. Yeah using `.py`s would be simpler in that regard, hadn't thought of that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T00:00:32.247", "Id": "256356", "ParentId": "256135", "Score": "3" } } ]
{ "AcceptedAnswerId": "256356", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T10:55:16.357", "Id": "256135", "Score": "2", "Tags": [ "python", "python-3.x", "object-oriented", "design-patterns" ], "Title": "Python - Inheritance: sharing objects across instances" }
256135
<p>I'm new to C++ and am following up on: <a href="https://codereview.stackexchange.com/questions/238234/a-simple-multithreaded-filelogger-in-c">A simple multithreaded FileLogger in C++</a></p> <p>I am curious to know if I implemented his ideas correctly, if there are further improvements to the code and whether it's (still) correct.</p> <p><strong>FileLoggerThread.h</strong></p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;mutex&gt; #include &lt;deque&gt; #include &lt;condition_variable&gt; #include &lt;filesystem&gt; class FileLoggerThread { public: explicit FileLoggerThread(std::filesystem::path filePath); ~FileLoggerThread(); // makes code more easily unit testable (unit tests can otherwise be in an infinite loop) void log(const std::string &amp;msg); FileLoggerThread(const FileLoggerThread&amp;) = delete; FileLoggerThread&amp; operator=(const FileLoggerThread&amp;) = delete; private: void writeToFile(); std::deque&lt;std::string&gt; mMessages; // accessed by log (any thread) and writeToFile (the writer thread) std::ofstream mOutputFile; // only accessible by writeToFile // thread internal resources std::mutex mMessagesMutex; // lock/unlock this each time messages is pushed or popped std::condition_variable mThreadScheduler; // log needs to wake up writeToFile bool mIsRunning; // if set to false then the writer thread stops }; </code></pre> <p><strong>FileLoggerThread.cpp</strong></p> <pre><code>#include &quot;FileLoggerThread.h&quot; #include &lt;thread&gt; FileLoggerThread::FileLoggerThread(std::filesystem::path filePath) : mOutputFile {filePath}, mIsRunning {true} { std::thread t(&amp;FileLoggerThread::writeToFile, this); t.detach(); } void FileLoggerThread::writeToFile() { while (mIsRunning) { std::deque&lt;std::string&gt; localMessages; std::unique_lock&lt;std::mutex&gt; writerLock {mMessagesMutex}; mThreadScheduler.wait(writerLock, [&amp;]{ return !mMessages.empty() || !mIsRunning;}); localMessages.swap(mMessages); writerLock.unlock(); for (const auto&amp; message : localMessages) { mOutputFile &lt;&lt; message &lt;&lt; std::endl; } } } void FileLoggerThread::log(const std::string &amp;msg) { std::unique_lock loggerLock(mMessagesMutex); mMessages.emplace_back(msg); loggerLock.unlock(); mThreadScheduler.notify_one(); // done for performance reasons, see: https://youtu.be/F6Ipn7gCOsY?t=2205 } FileLoggerThread::~FileLoggerThread() { mIsRunning = false; mThreadScheduler.notify_one(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T16:57:32.023", "Id": "505594", "Score": "0", "body": "\"and whether its (still) correct\" Did you test it? Does it appear to be correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T08:26:07.563", "Id": "505636", "Score": "0", "body": "Yes, I tested it, it appears to be correct. I should've made that explicit, perhaps, I somehow thought that my own personal testing was implied." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T11:45:16.977", "Id": "505649", "Score": "0", "body": "You'd hope so, but experience tells us that isn't always the case. Thank you for clarifying." } ]
[ { "body": "<ul>\n<li><p>It is not a good idea to have a completely detached thread. When one detaches thread, they usually use some sort of notification system like future/promise to ensure that the thread finished using resources. Here you file logger might have finished working and got destroyed while the detached thread still accesses <code>this</code> leading to UB. Instead you should keep thread as a part of the logger and trigger <code>join</code> in the destructor.</p>\n</li>\n<li><p>You shouldn't use <code>std::endl;</code> for every message - the flushing is a slow operation. You surely don't have a good reason to trigger it more often than more than once a second . Just make sure that you do trigger it once a second or so. <code>std::condition_variable::wait_for/wait_until</code> could be used to ensure that.</p>\n</li>\n<li><p>Another bug in destructor is that you modify <code>mIsRunning</code> without locking the mutex. Technically, it is a UB. In practice, this bug results in some very rare cases with the <code>wait</code> missing the notification and lasting eternity.</p>\n</li>\n<li><p>With the scheme that you are running I don't see why you use a <code>std::deque</code> for holding messages. Why not just <code>std::vector</code>? It is more efficient and also you shouldn't create new <code>localMessages</code> each time - just keep one constantly existing and clear it after each use. It saves some unnecessary memory allocations.</p>\n</li>\n<li><p>Also, once <code>mIsRunning</code> is <code>false</code> you need to ensure that all messages were written instead of quitting. Moreover, you shouldn't access <code>mIsRunning</code> in the while-loop condition as it should be guarded by the mutex.</p>\n</li>\n<li><p>The log function <code>void log(const std::string &amp;msg);</code> accepts a string and copies it into the queue. It is a waste. You'd better have two other overloads: <code>void log(std::string&amp;&amp; msg);</code> and <code>void log(std::string_view msg);</code> with the former moving the string and it's content for printing instead of unnecessarily copying it, while latter is just a more general form of <code>const std::string&amp;</code>.</p>\n</li>\n<li><p>In general, logger should support features like verbosity filterting and identification (e.g., info, warning, error), timestamping, and similar stuff that should be inherent part of a logger. Here you just accept arbitrary messages.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T10:09:05.537", "Id": "505645", "Score": "0", "body": "Is it standard practice to join the thread in the destructor? If so, then the mIsRunning bool is not needed is it? You can just create an infinite loop and join the thread in the destructor. Or is that an unsafe design?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T11:46:25.580", "Id": "505651", "Score": "0", "body": "@Melvin infinite loops are only used when programming microcontrollers. In all other cases you want an exit condition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T11:52:19.247", "Id": "505653", "Score": "0", "body": "Fair enough @Mast, fair enough :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T15:13:39.070", "Id": "505677", "Score": "1", "body": "@MelvinRoest `join` simply waits till the thread exists. You need some other scheme that ensures thread's exit. So use `mIsRunning` or something similar is needed." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T03:53:59.670", "Id": "256171", "ParentId": "256137", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T11:28:04.937", "Id": "256137", "Score": "1", "Tags": [ "c++", "multithreading" ], "Title": "Simple multithreaded FileLogger in C++" }
256137
<p>The exercise i am working on requires me to read a binary sequence stored in a text file. The objective is to find the occurrences of all subsequences of length between a and b (their values are given in the function parameters) and put them in a list of tuples.</p> <p>For example: If the following binary sequence is given as input and the length of each subsequence should be between 2 and 4:</p> <pre><code>a = 2 b = 4 01010010010001000111101100001010011001111000010010011110010000000 </code></pre> <p>I should write a program to generate the following output:</p> <pre><code>[(1, [&quot;1011&quot;, &quot;1101&quot;]), (2, [&quot;0101&quot;, &quot;0110&quot;, &quot;1010&quot;]), (3, [&quot;0111&quot;, &quot;101&quot;, &quot;1110&quot;, &quot;1111&quot;]), (4, [&quot;0001&quot;, &quot;0011&quot;, &quot;1100&quot;]), (5, [&quot;011&quot;, &quot;1000&quot;, &quot;110&quot;]), (6, [&quot;0000&quot;, &quot;111&quot;]), (7, [&quot;0010&quot;, &quot;1001&quot;]), (8, [&quot;0100&quot;]), (10, [&quot;010&quot;]), (11, [&quot;000&quot;, &quot;001&quot;, &quot;11&quot;]), (12, [&quot;100&quot;]), (15, [&quot;01&quot;, &quot;10&quot;]), (23, [&quot;00&quot;] )] </code></pre> <p>You will notice that each tuple in the list has two elements. The first element is the number of times a subsequence appears in the given sequence whilst the second element is the list containing the corresponding subsequences.</p> <p>E.g. the first tuple indicates that the subsequences &quot;1011&quot; and &quot;1101&quot; appear only once in the given sequence.</p> <p>The solution i have written does solve the problem (it passes all correctness tests), but it is slow and doesn't pass the performance tests (it only passes 5 out of 22 tests) in which the maximum timeout is set to 1 second. How could i make this solution faster?</p> <p>I am not allowed to import any <strike>external</strike> libraries.</p> <pre><code>def ex1(ftesto,a,b,n): with open(ftesto,encoding='utf8') as f: S = f.read().replace('\n','') N = len(S) D = {} subsequences = {} for i in range(N+1): for j in range(i+1,N+1): if a &lt;= len(S[i:j]) &lt;= b: if S[i:j] not in D: D[S[i:j]] = 1 else: D[S[i:j]] += 1 for k,v in D.items(): subsequences.setdefault(v,[]).append(k) result = sorted([(k,sorted(v)) for k,v in subsequences.items()]) return result[:n] if __name__ == '__main__': ftesto = 'ft1.txt' a = 2 b = 4 n = 20 </code></pre> <p>The amount of elements in the list must be equal or less than &quot;n&quot;. That explains why i am using the slicing at the end of the function.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T09:27:55.060", "Id": "505638", "Score": "2", "body": "from which range are the values a, b, n and the length of the 01-string" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T10:54:59.107", "Id": "505648", "Score": "0", "body": "read the post please" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T12:42:33.197", "Id": "505659", "Score": "1", "body": "so a=2, b=4 and the string is 01010010010001000111101100001010011001111000010010011110010000000 and this takes more than one second to calculate the result?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T10:27:21.427", "Id": "505786", "Score": "0", "body": "@miracle173 It takes much longer time if a very long sequence is given as input. That's why i need to improve efficiency" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T13:32:36.277", "Id": "505801", "Score": "0", "body": "that's why I want to know how long the sequence can be" } ]
[ { "body": "<h1>PEP 8</h1>\n<p>You are violating several <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> rules:</p>\n<ul>\n<li>commas should be followed by a space,</li>\n<li>variables should be <code>snake_case</code>,</li>\n<li>always surround binary operators with one space</li>\n</ul>\n<h1>Never called</h1>\n<p><code>ex1()</code> is never called by your mainline.</p>\n<h1>Declare variables closer to where they are used</h1>\n<p><code>subsequences</code> is declared 7 lines earlier than it needs to be.</p>\n<h1>Separate I/O from processing</h1>\n<p><code>ex1()</code> cannot be called with test data, unless that test data is in a file. Use two functions. One that solves the problem with an in-memory string, and a second that reads the string from a file for processing.</p>\n<h1>Avoid <code>dict.setdefault(...)</code></h1>\n<p><code>subsequences.setdefault(v, []).append(k)</code> will create a new list (<code>[]</code>) every time it is executed. Many times this default will never be used, and must be garbage collected. This is just wasting time.</p>\n<p>Instead, use <code>collections.defaultdict</code>. Note that <code>collections</code> is not an external library; it is internal, built into Python.</p>\n<h1>Counter</h1>\n<p>Similarly, use <code>collections.Counter</code> for counting objects. Again, built into Python; not an external library.</p>\n<h1>Reworked Code</h1>\n<pre class=\"lang-py prettyprint-override\"><code>\nfrom collections import Counter, defaultdict\n\ndef binary_sequence_counts(sequence, shortest, longest, limit):\n n = len(sequence)\n\n sequence_counter = Counter()\n for i in range(n + 1):\n for j in range(i + 1, n + 1):\n if shortest &lt;= len(sequence[i:j]) &lt;= longest:\n sequence_counter[sequence[i:j]] += 1\n\n subsequences = defaultdict(list)\n for subsequence, count in sequence_counter.items():\n subsequences[count].append(subsequence)\n\n result = sorted((count, sorted(subseqs)) for count, subseqs in subsequences.items())\n return result[:limit]\n\ndef ex1(ftesto, a, b, n):\n with open(ftesto, encoding='utf8') as f:\n sequence = f.read().replace('\\n', '')\n\n return binary_sequence_counts(sequence, a, b, n)\n\ndef testcase():\n seq = &quot;01010010010001000111101100001010011001111000010010011110010000000&quot;\n result = binary_sequence_counts(seq, 2, 4, 20)\n # print result, or\n # check if result is correct\n\n</code></pre>\n<p>The above code is way more readable than the original.</p>\n<h1>Efficiency</h1>\n<p>This code is just plain awful:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for i in range(n + 1):\n for j in range(i + 1, n + 1):\n if shortest &lt;= len(sequence[i:j]) &lt;= longest:\n ...\n</code></pre>\n<p>If your sequence is 100,000 digits long, the inner loop will execute about 5,000,000,000 times! That's a lot! Especially if you're only concerned with subsequences between 2 and 4 digits long, in which case you only need about 300,000 iterations.</p>\n<p>A simple modification of the <code>range(...)</code> limits would dramatically improve your speed. If you do it correctly, you can even get rid of the <code>a &lt;= len(...) &lt;= b</code> test, because with the correct ranges you will not be able to generate sequences that are the incorrect length.</p>\n<p>In fact, with the correct limits, you could even use the counter to do the counting entirely for you:</p>\n<pre class=\"lang-py prettyprint-override\"><code>sequence_counts = Counter(sequence[i:j]\n for i in range(...)\n for j in range(...))\n</code></pre>\n<p>Proper range limits left as exercise to student.</p>\n<h1>min heap</h1>\n<p>You are sorting a potentially huge list of values, and then returning only the n-smallest results. <code>sorted(iterable)[:n]</code> This can be a potentially huge waste of time!</p>\n<p>Using the <code>heapq.nsmallest(n, iterable)</code> (again, built-in, not an external library), you can reduce the amount of space used, and possibly the amount of time. Note that this is faster only for smaller values of <code>n</code>. If <code>n</code> is big, it can be faster to use <code>sorted(iterable)[:n]</code>. Always profile!</p>\n<h1>Roll Your Own</h1>\n<p>The question has been updated to disallow any imports. No problem. We'll just have to implement our own <code>defaultdict</code> and <code>Counter</code>.\nAssuming your are allowed to create your own <code>class</code> ...</p>\n<h2><code>object.__missing__</code></h2>\n<p>When a <code>dict.__getitem__</code> is called, but the dictionary does not contain that key, <a href=\"https://docs.python.org/3/reference/datamodel.html?highlight=__missing__#object.__missing__\" rel=\"nofollow noreferrer\"><code>object.__missing__(self, key)</code></a> is called. We can use this method to change the behaviour.</p>\n<h2>Counter</h2>\n<p>To implement a simple &quot;counter&quot; dictionary, we just need <code>0</code> to be returned for any missing key.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Counter(dict):\n def __missing__(self, key):\n return 0\n</code></pre>\n<p>If the key is missing, <code>0</code> is returned. If you &quot;add 1&quot; to a missing key, <code>0</code> is returned, <code>1</code> is added to the returned value, and the resulting <code>1</code> is stored back under that key:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; c = Counter()\n&gt;&gt;&gt; c['foo']\n0\n&gt;&gt;&gt; c['bar'] += 1\n&gt;&gt;&gt; c['bar'] += 1\n&gt;&gt;&gt; c\n{'bar': 2}\n</code></pre>\n<p>Notice that the <code>'foo'</code> key still does not exist; only the <code>'bar'</code> key exists because values were actually written to it.</p>\n<h2>defaultdict</h2>\n<p>You don't actually need a full <code>defaultdict</code> here. You just need a dictionary which returns an empty list when an unknown key is retrieved. Unlike the <code>Counter</code> class above, we need to remember the list that was returned for the key, because we'll be appending items to the list, which (unlike the <code>+=</code> operator) won't write the result back into the dictionary.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class DictOfLists(dict):\n def __missing__(self, key):\n self[key] = []\n return self[key]\n</code></pre>\n<p>Unlike the <code>Counter</code>, referencing an unknown key will create the key in the dictionary, filling it with an empty list:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; dol = DictOfLists()\n&gt;&gt;&gt; dol['foo']\n[]\n&gt;&gt;&gt; dol['bar'].append(&quot;baz&quot;)\n&gt;&gt;&gt; dol\n{'foo': [], 'bar': ['baz']}\n&gt;&gt;&gt; \n</code></pre>\n<p>The actual <code>defaultdict</code> allows you to specify a factory function in the constructor, to create values for the missing keys. That isn't too much more complicated. Feel free to research this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T08:09:44.563", "Id": "505634", "Score": "0", "body": "i really appreciate your answer. I am sorry. I just realized i made a mistake in the description of the exercise. The college teacher has forbidden us to use any libraries which means that we are not even allowed to type import in our code. Hence, the task becomes more difficult.\n\nThe idea of limiting the range sounds very good. I will try it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T15:55:12.080", "Id": "505680", "Score": "0", "body": "You changed \"_not allowed to import any external libraries_\" to \"_not allowed to import any libraries_\" which technically is changing the question and invalidates my answer. I will allow the change to stand, but I've added the word \"external\" back into the question post, but formatted with strikethrough to indicate it was there, and is now removed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T23:26:33.843", "Id": "505736", "Score": "0", "body": "Thank you for your answer, but how should i modify the range limits with the counter in order to improve efficiency?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:16:21.170", "Id": "505751", "Score": "0", "body": "Hint: If your binary sequence is 10 characters long, and you are looking for subsequences between 2 and 4 characters in length, what is the largest starting index you can possibly use? How did you determine that? What can you say about the ending index when you are at any given starting index. Are there special cases you might have to worry about? Do you have to handle them with separate code, or can you prevent them from occurring somehow?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T11:16:27.740", "Id": "505790", "Score": "0", "body": "I tried this: \n\nsequence_counts = Counter(sequence[i:i+j]\n for i in range(n-shortest)\n for j in range(shortest,longest+1))\n\nBut i get errors, how do i solve this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T15:17:52.793", "Id": "505810", "Score": "0", "body": "You can post a followup question on Stack Overflow. Code Review is for reviewing working code, improving efficiency, and helping identify previously unknown bugs. We've pointed out the inefficiency, you've identified how it can be fixed, and now you've got a bug or error. Include a link to this question for context, and add a link in this question to your followup question on Stack Overflow so reviewers can follow the progress." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T02:45:52.780", "Id": "256169", "ParentId": "256140", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T12:06:45.030", "Id": "256140", "Score": "2", "Tags": [ "python", "performance", "programming-challenge", "time-limit-exceeded" ], "Title": "Counting binary substrings" }
256140
<p>For a Django-Server I use several custom Error-Codes, error-titles and descriptions, possibly other fields might follow.</p> <p>I'm using right now a basic global dictionary.</p> <pre><code>errordict = {'512': { 'errorno': 512, 'errordescr': &quot;Database Down&quot;, 'toDo': &quot;Restart the database, Server: &quot;+serveradr }, '513' : .... } </code></pre> <p>And in the code something like:</p> <pre><code>def handleError(s_err): curerr=errordict[s_err] logging.error(&quot;Error &quot;+s_err+&quot; occurred: &quot;+curerr['errordescr']) </code></pre> <p>The usage looks like this:</p> <pre><code> try: findEntry(s_id) except NoSuchEntryEx as nsee: s_err=&quot;513&quot; handleError(s_err) return HttpResponse(render_to_string('error.html', { 'errorno': s_err, 'errordescr': mark_safe(str(nsee) + const.OUTPUT_NEWLINE), 'toDo': errordict[s_err]['toDo'] })) </code></pre> <p>I'm not happy with that and would rather define its own class - which would from the current perspective would just consist of this single, growing dict-object, which does not seem a great idea either.</p> <p>It's of course a constant, every change there is hard-coded.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T13:45:04.803", "Id": "505565", "Score": "0", "body": "@Peilonrayz - provided more information, but it's just reading the dict, nothing else. It has a name, but there's nothing interesting about it. The dict grows and I'd like to improve how I access the codes and descriptions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T13:50:16.947", "Id": "505566", "Score": "1", "body": "Thank you. I don't really see the problem, your code looks fine. Is there more code you could show? For example you've shown how 513 is used, could you show how 512 is used? What do the functions that call the usage look like? The more code you provide the more we can see the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T14:00:00.730", "Id": "505567", "Score": "0", "body": "@Peilonrayz - I added the usage, as said it's nothing out of the ordinary. But the dict keeps growing and I want to keep it out of the file for clearer administration and separation. When I move it I'd like to put some thought into having a better data-structure and be open for possible changes. I have searched around, but this seems to be the only solution. Can it be?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-27T21:48:49.737", "Id": "506460", "Score": "0", "body": "Sounds like you should use Pythons exception handling. This allows you to add your own exceptions..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-08T17:00:23.053", "Id": "507262", "Score": "0", "body": "@agtoever - I do that heavily: `NoSuchEntryEx` - in this specific case there is just not much left to do for me on the server" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T12:52:20.970", "Id": "256142", "Score": "1", "Tags": [ "python", "python-3.x", "hash-map", "django" ], "Title": "Global Dictionary Class" }
256142
<p>I am trying to implement message encryption/decryption with password in java. Here is the code I'm using:</p> <pre><code>import java.security.MessageDigest; import java.security.spec.InvalidKeySpecException; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; public class Cryptography { public static final int SECRET_KEY_ITERATIONS = 45928; public static final int SALT_ITERATIONS = 11879; public static final int IV_ITERATIONS = 13275; public static final int KEY_LENGTH = 256; private static Cipher cipher; private static MessageDigest sha256; private static SecretKeyFactory secretKeyFactory; static { try { cipher = Cipher.getInstance(&quot;AES/CBC/PKCS5Padding&quot;); sha256 = MessageDigest.getInstance(&quot;SHA-256&quot;); secretKeyFactory = SecretKeyFactory.getInstance(&quot;PBKDF2WithHmacSHA256&quot;); } catch (Exception e) { e.printStackTrace(); } } public static String encryptText(String password, String plaintext) throws Exception { byte[] passwordBytes = password.getBytes(); SecretKey secretKey = getKeyFromPassword(password, getSaltFromPassword(passwordBytes)); IvParameterSpec ivParameterSpec = getIvFromPassword(passwordBytes); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec); return Base64.getEncoder().encodeToString(cipher.doFinal(plaintext.getBytes())); } public static String decryptText(String password, String ciphertext) throws Exception { byte[] passwordBytes = password.getBytes(); SecretKey secretKey = getKeyFromPassword(password, getSaltFromPassword(passwordBytes)); IvParameterSpec ivParameterSpec = getIvFromPassword(passwordBytes); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec); return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext))); } private static SecretKey getKeyFromPassword(String password, byte[] salt) throws InvalidKeySpecException { PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, SECRET_KEY_ITERATIONS, KEY_LENGTH); byte[] bytes = secretKeyFactory.generateSecret(spec).getEncoded(); return new SecretKeySpec(bytes, &quot;AES&quot;); } private static byte[] getSaltFromPassword(byte[] passwordByteArray) { byte[] bytes = sha256.digest(passwordByteArray); for (int i = 0; i &lt; SALT_ITERATIONS; i++) { bytes = sha256.digest(bytes); } return bytes; } private static IvParameterSpec getIvFromPassword(byte[] passwordByteArray) { byte[] bytes = sha256.digest(passwordByteArray); for (int i = 0; i &lt; IV_ITERATIONS; i++) { bytes = sha256.digest(bytes); } byte[] ivBuffer = new byte[16]; System.arraycopy(bytes, 0, ivBuffer, 0, 16); return new IvParameterSpec(ivBuffer); } } </code></pre> <p>Is this a secure way to do encryption/decryption, or does it have serious issues?</p>
[]
[ { "body": "<pre><code> private static byte[] getSaltFromPassword(byte[] passwordByteArray) {\n byte[] bytes = sha256.digest(passwordByteArray);\n for (int i = 0; i &lt; SALT_ITERATIONS; i++) {\n bytes = sha256.digest(bytes);\n }\n return bytes;\n }\n</code></pre>\n<p>this part is an NO NO. salt has to be random. please refer this\n<a href=\"https://stackoverflow.com/questions/10051716/is-it-ok-to-derive-a-salt-from-a-password-and-then-hash-the-password-derived\">old question</a>\nThe salt has to be independent and random else it is useless.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T13:10:06.993", "Id": "256146", "ParentId": "256145", "Score": "2" } }, { "body": "<p>Yes, it has [serious issues].</p>\n<p>For instance, because the salt is not unique, the code is fully deterministic. That means that you directly leak information if you encrypt strings with the same password (similar to how ECB leaks information).</p>\n<p>The resulting ciphertext is not authenticated either, so supplying a wrong password <strong>may</strong> result in successful decryption. However, that decrypted plaintext will just consist of randomized bytes, not your original text.</p>\n<hr />\n<p>I'll perform a code review with the comments below the code.</p>\n<pre><code>public static final int SECRET_KEY_ITERATIONS = 45928;\npublic static final int SALT_ITERATIONS = 11879;\npublic static final int IV_ITERATIONS = 13275;\n</code></pre>\n<p>Passwords need iterations, keys don't. Maybe <code>KEY_DERIVATION_ITERATIONS</code> would be acceptable though.</p>\n<p>Salts may be used within iterations, but there is no such thing as a salt-iteration.</p>\n<p>IVs don't have anything to do with iterations.</p>\n<pre><code>private static Cipher cipher;\n</code></pre>\n<p>Cipher is <strong>stateful</strong>, you should not use it as a field, let alone a <code>static</code> class field. If you want to store anything, store the resulting key, not the cipher algorithm.</p>\n<pre><code>static {\n</code></pre>\n<p>Try to avoid static blocks, just use a class without <code>static</code>.</p>\n<pre><code>public static String encryptText(String password, String plaintext) throws Exception {\n</code></pre>\n<p>Since cipher is stateful, can you imagine what happens if you call this method from separate threads? Everything will become a mess - if you are <strong>lucky</strong> something breaks down early.</p>\n<pre><code>private static byte[] getSaltFromPassword(byte[] passwordByteArray) {\n</code></pre>\n<p>A salt cannot be derived from a password as it is used to make the derived key from the password unique; that's the whole point. It just needs to be random. Otherwise, it doesn't make any sense to use a salt.</p>\n<pre><code>private static IvParameterSpec getIvFromPassword(byte[] passwordByteArray) {\n</code></pre>\n<p>Similar issue, the key / IV value should be unique. If the salt was random and stored with the ciphertext you could even use a static IV. Using a random IV is somewhat nicer, but then you'd have to store that as well.</p>\n<hr />\n<p>Note that you are reinventing the wheel if you're using SHA-256 iterations; you might as well reuse PBKDF2. But in this case, it is not required anyway.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T13:47:33.883", "Id": "256148", "ParentId": "256145", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T09:57:50.903", "Id": "256145", "Score": "2", "Tags": [ "java", "security", "cryptography", "encryption" ], "Title": "Encrypting/decrypting messages in java" }
256145
<p>Here's my open source project: <a href="https://github.com/Skewjo/SysLat_Software" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software</a>. The hardware controlled by this software can be found at <a href="https://syslat.com/" rel="nofollow noreferrer">https://syslat.com/</a>. This is the 3rd question in a series of questions to get the code production ready. The other questions are <a href="https://codereview.stackexchange.com/questions/256046/turning-a-data-class-with-too-much-functionality-into-a-pod-syslat-cleanup-1">Tuning the data class 1</a> <a href="https://codereview.stackexchange.com/questions/256063/turning-a-data-class-with-too-much-functionality-into-a-pod-syslat-cleanup-2">the follow up to the tuning the data class</a> and the <a href="https://codereview.stackexchange.com/questions/256151/cleaning-up-static-member-variable-declaration-and-definition">dialog that controls the whole program</a>.</p> <p>Today I'd like to attempt to clean up my USB implementation.</p> <p>Header file here: <a href="https://github.com/Skewjo/SysLat_Software/blob/master/USBController.h" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software/blob/master/USBController.h</a> Implementation here: <a href="https://github.com/Skewjo/SysLat_Software/blob/master/USBController.cpp" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software/blob/master/USBController.cpp</a> Definition and use here: <a href="https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.cpp" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.cpp</a></p> <p><a href="https://github.com/Skewjo/SysLat_Software/blob/master/USBController.h" rel="nofollow noreferrer">USBController.h</a></p> <pre><code>#pragma once #ifndef USBCONTROLLER_H #define USBCONTROLLER_H struct SSerInfo { SSerInfo() : bUsbDevice(FALSE) {} CString strDevPath; // Device path for use with CreateFile() CString strPortName; // Simple name (i.e. COM1) CString strFriendlyName; // Full name to be displayed to a user BOOL bUsbDevice; // Provided through a USB connection? CString strPortDesc; // friendly name without the COMx }; class CUSBController { /* protected: //These vars aren't actually in use anywhere yet... const CString&amp; PortSpecifier; DWORD BaudRate = CBR_9600; //9600 Baud /*other Baud options: CBR_110 110 CBR_300 300 CBR_600 600 CBR_1200 1200 CBR_2400 2400 CBR_4800 4800 CBR_9600 9600 CBR_14400 14400 CBR_19200 19200 CBR_38400 38400 CBR_56000 56000 CBR_57600 57600 CBR_115200 115200 CBR_128000 128000 CBR_256000 256000 BYTE ByteSize = 8; //8 data bits BYTE Parity = NOPARITY; //no parity BYTE StopBits = ONESTOPBIT; //1 stop */ //--------------------------------------------------------------- // Helpers for enumerating the available serial ports. // These throw a CString on failure, describing the nature of // the error that occurred. void EnumPortsWdm(CArray&lt;SSerInfo, SSerInfo&amp;&gt;&amp; asi); void EnumPortsWNt4(CArray&lt;SSerInfo, SSerInfo&amp;&gt;&amp; asi); void EnumPortsW9x(CArray&lt;SSerInfo, SSerInfo&amp;&gt;&amp; asi); void SearchPnpKeyW9x(HKEY hkPnp, BOOL bUsbDevice, CArray&lt;SSerInfo, SSerInfo&amp;&gt;&amp; asi); public: HANDLE OpenComPort(const CString&amp; PortSpecifier); void CloseComPort(HANDLE hPort); bool IsComPortOpened(HANDLE hPort); int ReadByte(HANDLE port); //1-6-21 //This only half works on my system, so I also have to use &quot;_WINBASE_::GetCommPorts()&quot;, but it does give me the &quot;friendly name&quot;, which is what I really need. void EnumSerialPorts(CArray&lt;SSerInfo, SSerInfo&amp;&gt;&amp; asi, BOOL bIgnoreBusyPorts); }; #endif </code></pre> <p><a href="https://github.com/Skewjo/SysLat_Software/blob/master/USBController.cpp" rel="nofollow noreferrer">USBController.cpp</a></p> <pre><code>#include &quot;stdafx.h&quot; #include &quot;USBController.h&quot; //#include &lt;objbase.h&gt; //#include &lt;initguid.h&gt; #include &lt;Setupapi.h&gt; #include &lt;ntddser.h&gt; #pragma comment(lib, &quot;Setupapi.lib&quot;) HANDLE CUSBController::OpenComPort(const CString&amp; PortSpecifier) { HANDLE hPort = CreateFile(PortSpecifier, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); if (hPort == INVALID_HANDLE_VALUE) return INVALID_HANDLE_VALUE; PurgeComm(hPort, PURGE_RXCLEAR); DCB dcb = { 0 }; if (!GetCommState(hPort, &amp;dcb)) { CloseHandle(hPort); return INVALID_HANDLE_VALUE; } dcb.BaudRate = CBR_9600; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; if (!SetCommState(hPort, &amp;dcb)) { CloseHandle(hPort); return INVALID_HANDLE_VALUE; } SetCommMask(hPort, EV_RXCHAR | EV_ERR); //receive character event // Read this carefully because timeouts are important // https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-commtimeouts COMMTIMEOUTS timeouts = { 0 }; return hPort; } void CUSBController::CloseComPort(HANDLE hPort) { PurgeComm(hPort, PURGE_RXCLEAR); CloseHandle(hPort); } bool CUSBController::IsComPortOpened(HANDLE hPort) { return hPort != INVALID_HANDLE_VALUE; } int CUSBController::ReadByte(HANDLE hPort) { int retVal; BYTE Byte; DWORD dwBytesTransferred; if (FALSE == ReadFile(hPort, &amp;Byte, 1, &amp;dwBytesTransferred, 0)) //read 1 retVal = 0x101; retVal = Byte; return retVal; } /************************************************************************* * Serial port enumeration routines * * The EnumSerialPort function will populate an array of SSerInfo structs, * each of which contains information about one serial port present in * the system. Note that this code must be linked with setupapi.lib, * which is included with the Win32 SDK. * * by Zach Gorman &lt;gormanjz@hotmail.com&gt; * * Copyright (c) 2002 Archetype Auction Software, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following condition is * met: Redistributions of source code must retain the above copyright * notice, this condition and the following disclaimer. * * THIS SOFTWARE IS PROVIDED &quot;AS IS&quot; AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ARCHETYPE AUCTION SOFTWARE OR ITS * AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************************************/ // The following define is from ntddser.h in the DDK. It is also // needed for serial port enumeration. /*#ifndef GUID_CLASS_COMPORT DEFINE_GUID(GUID_CLASS_COMPORT, 0x86e0d1e0L, 0x8089, 0x11d0, 0x9c, 0xe4, \ 0x08, 0x00, 0x3e, 0x30, 0x1f, 0x73); #endif*/ //--------------------------------------------------------------- // Routine for enumerating the available serial ports. // Throws a CString on failure, describing the error that // occurred. If bIgnoreBusyPorts is TRUE, ports that can't // be opened for read/write access are not included. void CUSBController::EnumSerialPorts(CArray&lt;SSerInfo, SSerInfo&amp;&gt;&amp; asi, BOOL bIgnoreBusyPorts) { // Clear the output array asi.RemoveAll(); // Use different techniques to enumerate the available serial // ports, depending on the OS we're using OSVERSIONINFO vi; vi.dwOSVersionInfoSize = sizeof(vi); if (!::GetVersionEx(&amp;vi)) { CString str; str.Format(&quot;Could not get OS version. (err=%lx)&quot;, GetLastError()); throw str; } // Handle windows 9x and NT4 specially if (vi.dwMajorVersion &lt; 5) { if (vi.dwPlatformId == VER_PLATFORM_WIN32_NT) EnumPortsWNt4(asi); else EnumPortsW9x(asi); } else { // Win2k and later support a standard API for // enumerating hardware devices. EnumPortsWdm(asi); } for (int ii = 0; ii &lt; asi.GetSize(); ii++) { SSerInfo&amp; rsi = asi[ii]; if (bIgnoreBusyPorts) { // Only display ports that can be opened for read/write HANDLE hCom = CreateFile(rsi.strDevPath, GENERIC_READ | GENERIC_WRITE, 0, /* comm devices must be opened w/exclusive-access */ NULL, /* no security attrs */ OPEN_EXISTING, /* comm devices must use OPEN_EXISTING */ 0, /* not overlapped I/O */ NULL /* hTemplate must be NULL for comm devices */ ); if (hCom == INVALID_HANDLE_VALUE) { // It can't be opened; remove it. asi.RemoveAt(ii); ii--; continue; } else { // It can be opened! Close it and add it to the list ::CloseHandle(hCom); } } // Come up with a name for the device. // If there is no friendly name, use the port name. if (rsi.strFriendlyName.IsEmpty()) rsi.strFriendlyName = rsi.strPortName; // If there is no description, try to make one up from // the friendly name. if (rsi.strPortDesc.IsEmpty()) { // If the port name is of the form &quot;ACME Port (COM3)&quot; // then strip off the &quot; (COM3)&quot; rsi.strPortDesc = rsi.strFriendlyName; int startdex = rsi.strPortDesc.Find(&quot; (&quot;); int enddex = rsi.strPortDesc.Find(&quot;)&quot;); if (startdex &gt; 0 &amp;&amp; enddex == (rsi.strPortDesc.GetLength() - 1)) rsi.strPortDesc = rsi.strPortDesc.Left(startdex); } } } // Helpers for EnumSerialPorts void CUSBController::EnumPortsWdm(CArray&lt;SSerInfo, SSerInfo&amp;&gt;&amp; asi) { CString strErr; // Create a device information set that will be the container for // the device interfaces. GUID* guidDev = (GUID*)&amp;GUID_CLASS_COMPORT; HDEVINFO hDevInfo = INVALID_HANDLE_VALUE; SP_DEVICE_INTERFACE_DETAIL_DATA* pDetData = NULL; try { hDevInfo = SetupDiGetClassDevs(guidDev, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE ); if (hDevInfo == INVALID_HANDLE_VALUE) { strErr.Format(&quot;SetupDiGetClassDevs failed. (err=%lx)&quot;, GetLastError()); throw strErr; } // Enumerate the serial ports BOOL bOk = TRUE; SP_DEVICE_INTERFACE_DATA ifcData; DWORD dwDetDataSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + 256; pDetData = (SP_DEVICE_INTERFACE_DETAIL_DATA*) new char[dwDetDataSize]; // This is required, according to the documentation. Yes, // it's weird. ifcData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); pDetData-&gt;cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); for (DWORD ii = 0; bOk; ii++) { bOk = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, guidDev, ii, &amp;ifcData); if (bOk) { // Got a device. Get the details. SP_DEVINFO_DATA devdata = { sizeof(SP_DEVINFO_DATA) }; bOk = SetupDiGetDeviceInterfaceDetail(hDevInfo, &amp;ifcData, pDetData, dwDetDataSize, NULL, &amp;devdata); if (bOk) { CString strDevPath(pDetData-&gt;DevicePath); // Got a path to the device. Try to get some more info. CHAR fname[256]; CHAR desc[256]; BOOL bSuccess = SetupDiGetDeviceRegistryProperty(hDevInfo, &amp;devdata, SPDRP_FRIENDLYNAME, NULL, (PBYTE)fname, sizeof(fname), NULL); bSuccess = bSuccess &amp;&amp; SetupDiGetDeviceRegistryProperty(hDevInfo, &amp;devdata, SPDRP_DEVICEDESC, NULL, (PBYTE)desc, sizeof(desc), NULL); BOOL bUsbDevice = FALSE; CHAR locinfo[256]; if (SetupDiGetDeviceRegistryProperty(hDevInfo, &amp;devdata, SPDRP_LOCATION_INFORMATION, NULL, (PBYTE)locinfo, sizeof(locinfo), NULL)) { // Just check the first three characters to determine // if the port is connected to the USB bus. This isn't // an infallible method; it would be better to use the // BUS GUID. Currently, Windows doesn't let you query // that though (SPDRP_BUSTYPEGUID seems to exist in // documentation only). bUsbDevice = (strncmp(locinfo, &quot;USB&quot;, 3) == 0); } if (bSuccess) { // Add an entry to the array SSerInfo si; si.strDevPath = strDevPath; si.strFriendlyName = fname; si.strPortDesc = desc; si.bUsbDevice = bUsbDevice; asi.Add(si); } } else { strErr.Format(&quot;SetupDiGetDeviceInterfaceDetail failed. (err=%lx)&quot;, GetLastError()); throw strErr; } } else { DWORD err = GetLastError(); if (err != ERROR_NO_MORE_ITEMS) { strErr.Format(&quot;SetupDiEnumDeviceInterfaces failed. (err=%lx)&quot;, err); throw strErr; } } } } catch (CString strCatchErr) { strErr = strCatchErr; } if (pDetData != NULL) delete[](char*)pDetData; if (hDevInfo != INVALID_HANDLE_VALUE) SetupDiDestroyDeviceInfoList(hDevInfo); if (!strErr.IsEmpty()) throw strErr; } void CUSBController::EnumPortsWNt4(CArray&lt;SSerInfo, SSerInfo&amp;&gt;&amp; asi) { // NT4's driver model is totally different, and not that // many people use NT4 anymore. Just try all the COM ports // between 1 and 16 SSerInfo si; for (int ii = 1; ii &lt;= 16; ii++) { CString strPort; strPort.Format(&quot;COM%d&quot;, ii); si.strDevPath = CString(&quot;\\\\.\\&quot;) + strPort; si.strPortName = strPort; asi.Add(si); } } void CUSBController::EnumPortsW9x(CArray&lt;SSerInfo, SSerInfo&amp;&gt;&amp; asi) { // Look at all keys in HKLM\Enum, searching for subkeys named // *PNP0500 and *PNP0501. Within these subkeys, search for // sub-subkeys containing value entries with the name &quot;PORTNAME&quot; // Search all subkeys of HKLM\Enum\USBPORTS for PORTNAME entries. // First, open HKLM\Enum HKEY hkEnum = NULL; HKEY hkSubEnum = NULL; HKEY hkSubSubEnum = NULL; try { if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, &quot;Enum&quot;, 0, KEY_READ, &amp;hkEnum) != ERROR_SUCCESS) throw CString(&quot;Could not read from HKLM\\Enum&quot;); // Enumerate the subkeys of HKLM\Enum char acSubEnum[128]; DWORD dwSubEnumIndex = 0; DWORD dwSize = sizeof(acSubEnum); while (RegEnumKeyEx(hkEnum, dwSubEnumIndex++, acSubEnum, &amp;dwSize, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { HKEY hkSubEnum = NULL; if (RegOpenKeyEx(hkEnum, acSubEnum, 0, KEY_READ, &amp;hkSubEnum) != ERROR_SUCCESS) throw CString(&quot;Could not read from HKLM\\Enum\\&quot;) + acSubEnum; // Enumerate the subkeys of HKLM\Enum\*\, looking for keys // named *PNP0500 and *PNP0501 (or anything in USBPORTS) BOOL bUsbDevice = (strcmp(acSubEnum, &quot;USBPORTS&quot;) == 0); char acSubSubEnum[128]; dwSize = sizeof(acSubSubEnum); // set the buffer size DWORD dwSubSubEnumIndex = 0; while (RegEnumKeyEx(hkSubEnum, dwSubSubEnumIndex++, acSubSubEnum, &amp;dwSize, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { BOOL bMatch = (strcmp(acSubSubEnum, &quot;*PNP0500&quot;) == 0 || strcmp(acSubSubEnum, &quot;*PNP0501&quot;) == 0 || bUsbDevice); if (bMatch) { HKEY hkSubSubEnum = NULL; if (RegOpenKeyEx(hkSubEnum, acSubSubEnum, 0, KEY_READ, &amp;hkSubSubEnum) != ERROR_SUCCESS) throw CString(&quot;Could not read from HKLM\\Enum\\&quot;) + acSubEnum + &quot;\\&quot; + acSubSubEnum; SearchPnpKeyW9x(hkSubSubEnum, bUsbDevice, asi); RegCloseKey(hkSubSubEnum); hkSubSubEnum = NULL; } dwSize = sizeof(acSubSubEnum); // restore the buffer size } RegCloseKey(hkSubEnum); hkSubEnum = NULL; dwSize = sizeof(acSubEnum); // restore the buffer size } } catch (CString strError) { if (hkEnum != NULL) RegCloseKey(hkEnum); if (hkSubEnum != NULL) RegCloseKey(hkSubEnum); if (hkSubSubEnum != NULL) RegCloseKey(hkSubSubEnum); throw strError; } RegCloseKey(hkEnum); } void CUSBController::SearchPnpKeyW9x(HKEY hkPnp, BOOL bUsbDevice, CArray&lt;SSerInfo, SSerInfo&amp;&gt;&amp; asi) { // Enumerate the subkeys of the given PNP key, looking for values with // the name &quot;PORTNAME&quot; // First, open HKLM\Enum HKEY hkSubPnp = NULL; try { // Enumerate the subkeys of HKLM\Enum\*\PNP050[01] char acSubPnp[128]; DWORD dwSubPnpIndex = 0; DWORD dwSize = sizeof(acSubPnp); while (RegEnumKeyEx(hkPnp, dwSubPnpIndex++, acSubPnp, &amp;dwSize, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { HKEY hkSubPnp = NULL; if (RegOpenKeyEx(hkPnp, acSubPnp, 0, KEY_READ, &amp;hkSubPnp) != ERROR_SUCCESS) throw CString(&quot;Could not read from HKLM\\Enum\\...\\&quot;) + acSubPnp; // Look for the PORTNAME value char acValue[128]; dwSize = sizeof(acValue); if (RegQueryValueEx(hkSubPnp, &quot;PORTNAME&quot;, NULL, NULL, (BYTE*)acValue, &amp;dwSize) == ERROR_SUCCESS) { CString strPortName(acValue); // Got the portname value. Look for a friendly name. CString strFriendlyName; dwSize = sizeof(acValue); if (RegQueryValueEx(hkSubPnp, &quot;FRIENDLYNAME&quot;, NULL, NULL, (BYTE*)acValue, &amp;dwSize) == ERROR_SUCCESS) strFriendlyName = acValue; // Prepare an entry for the output array. SSerInfo si; si.strDevPath = CString(&quot;\\\\.\\&quot;) + strPortName; si.strPortName = strPortName; si.strFriendlyName = strFriendlyName; si.bUsbDevice = bUsbDevice; // Overwrite duplicates. BOOL bDup = FALSE; for (int ii = 0; ii &lt; asi.GetSize() &amp;&amp; !bDup; ii++) { if (asi[ii].strPortName == strPortName) { bDup = TRUE; asi[ii] = si; } } if (!bDup) { // Add an entry to the array asi.Add(si); } } RegCloseKey(hkSubPnp); hkSubPnp = NULL; dwSize = sizeof(acSubPnp); // restore the buffer size } } catch (CString strError) { if (hkSubPnp != NULL) RegCloseKey(hkSubPnp); throw strError; } } </code></pre> <p>And finally, here's one of the functions in <a href="https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.cpp" rel="nofollow noreferrer">SysLat_SoftwareDlg.cpp</a>, that I believe is causing me issues, where the class is used:</p> <pre><code>void CSysLat_SoftwareDlg::R_DynamicComPortMenu() { CMenu* MainMenu = GetMenu(); CMenu* SettingsMenu = MainMenu-&gt;GetSubMenu(1); CMenu* ComPortMenu = SettingsMenu-&gt;GetSubMenu(0); if (ComPortMenu) { BOOL appended = false; BOOL deleted = false; m_COMPortCount = 0; for(auto i = 0; i &lt; m_COMPortInfo.GetSize(); i++) { ComPortMenu-&gt;DeleteMenu(ID_COMPORT_START + m_COMPortCount, MF_BYCOMMAND); if (m_COMPortCount &lt; ID_COMPORT_END - ID_COMPORT_START) { string usb_info = m_COMPortInfo[i].strFriendlyName; DEBUG_PRINT(&quot;Friendly Name: &quot; + usb_info) appended = ComPortMenu-&gt;AppendMenu(MF_STRING, ID_COMPORT_START + m_COMPortCount, m_COMPortInfo[i].strFriendlyName); string menuString = m_COMPortInfo[i].strFriendlyName; size_t pos = menuString.rfind(&quot;(&quot;); menuString.replace(0, pos + 1, &quot;&quot;); pos = menuString.rfind(&quot;)&quot;); menuString.replace(pos, menuString.size(), &quot;&quot;); if (strcmp(menuString.c_str(), SysLatOpt.m_PortSpecifier.c_str()) == 0) { MainMenu-&gt;CheckMenuItem(ID_COMPORT_START + m_COMPortCount, MF_CHECKED); } m_COMPortCount++; } else { //catch or throw errors here maybe? break; } } deleted = ComPortMenu-&gt;DeleteMenu(ID_USBPORT_PLACEHOLDER, MF_BYCOMMAND); DEBUG_PRINT((&quot;String appended: &quot; + to_string(appended)).c_str()) DEBUG_PRINT((&quot;Placeholder deleted: &quot; + to_string(deleted)).c_str()) } DrawMenuBar(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T17:35:34.620", "Id": "506073", "Score": "1", "body": "You may want to check out https://libusb.info/ for a portable USB library that runs on Windows, Linux and MacOS." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T14:41:46.353", "Id": "256149", "Score": "2", "Tags": [ "c++", "windows", "embedded" ], "Title": "USB implementation of device that tests system latency on gaming computers - SysLat Cleanup #3" }
256149
<p>I have several static variables in my dialog class that I'm declaring in the header and then defining immediately in the cpp file. They are being used in an application with 2 threads, and these particular variables are mostly shared between both threads.</p> <p>This is the fourth question in an effort to get the program ready for production. The other cleanup questions are <a href="https://codereview.stackexchange.com/questions/256046/turning-a-data-class-with-too-much-functionality-into-a-pod-syslat-cleanup-1">SysLat Cleanup #1</a>, <a href="https://codereview.stackexchange.com/questions/256063/turning-a-data-class-with-too-much-functionality-into-a-pod-syslat-cleanup-2">SysLat Cleanup #2</a> and <a href="https://codereview.stackexchange.com/questions/256149/cleaning-up-usb-implementation-use-syslat-cleanup-3">SysLat Cleanup #3 (USB control)</a>. The hardware is available at <a href="https://syslat.com/" rel="nofollow noreferrer">https://syslat.com/</a>.</p> <ol> <li>Main thread that runs the dialog box and manages various connections (data objects, menus, a USB device connection, and a shared memory connection)</li> <li>A &quot;high priority&quot; thread that reads USB input, runs shared memory commands, and updates one of the core data objects (a <code>CSysLatData</code> object).</li> </ol> <p>This code is currently working with no issues, but it feels to me that it is unsafe, incorrect, or in a poor location.</p> <p>Here's the header file:</p> <pre><code>// SysLat_SoftwareDlg.h : header file // // created by Unwinder // modified by Skewjo ///////////////////////////////////////////////////////////////////////////// #ifndef _SYSLAT_SOFTWAREDLG_H_INCLUDED_ #define _SYSLAT_SOFTWAREDLG_H_INCLUDED_ #if _MSC_VER &gt; 1000 #pragma once #endif // _MSC_VER &gt; 1000 #include &quot;RTSSSharedMemory.h&quot; #include &quot;RTSSClient.h&quot; #include &quot;SysLatData.h&quot; #include &quot;HardwareID.h&quot; #include &quot;MachineInfo.h&quot; #include &quot;USBController.h&quot; class CSysLat_SoftwareDlg : public CDialogEx { // Construction public: CSysLat_SoftwareDlg(CWnd* pParent = NULL); // standard constructor ~CSysLat_SoftwareDlg(); // Dialog Data //{{AFX_DATA(CSysLat_SoftwareDlg) enum { IDD = IDD_SYSLAT_SOFTWARE_DIALOG }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSysLat_SoftwareDlg) public: protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: BOOL PreTranslateMessage(MSG* pMsg); void Refresh(); void R_GetRTSSConfigs(); BOOL R_SysLatStats(); void R_Position(); void R_ProcessNames(); void R_StrOSD(); void R_DynamicComPortMenu(); void R_DynamicAppMenu(); static void AppendError(const CString&amp; error); //this function is duplicated between this class and SysLatData - need to make this not used by the thread and then I can make it non-static like the other refresh functions //Drawing thread functions static unsigned int __stdcall CreateDrawingThread(void* data); static void DrawSquare(CRTSSClient sysLatClient, CString&amp; colorString); static string GetProcessNameFromPID(DWORD processID); static string GetActiveWindowTitle(); static void ProcessNameTrim(string&amp;, string&amp;); //Dialog menu related functions //Tools void ReInitThread();//used by the &quot;New Test&quot; menu function void ExportData(); void UploadData(); //Settings void DebugMode(); void TestUploadMode(); void DisplaySysLatInOSD(); void OpenPreferences(); void OpenTestCtrl(); void ExportData(Json::Value stuffToExport); void OnComPortChanged(UINT nID); void OnTargetWindowChanged(UINT nID); void CheckUpdate(); void SetSURegValue(string regValue); //Members HardwareID m_hardwareID; MachineInfo m_machineInfo; CRTSSClient m_SysLatStatsClient; //This RTSS client is &quot;owned&quot; by the dialog box and the &quot;drawing thread&quot; function &quot;owns&quot; the other CArray&lt;SSerInfo, SSerInfo&amp;&gt; m_COMPortInfo; HANDLE m_drawingThreadHandle; int m_COMPortCount; static std::shared_ptr&lt;CSysLatData&gt; m_pOperatingSLD; //static CSysLatData* m_pOperatingSLD; //vector&lt;CSysLatData*&gt; m_vpPreviousSLD; vector&lt;std::shared_ptr&lt;CSysLatData&gt;&gt; m_vpPreviousSLD; static constexpr const char* m_caSysLat = &quot;SysLat&quot;; static constexpr const char* m_caSysLatStats = &quot;SysLatStats&quot;; static DWORD m_sysLatOwnedSlot;//UGH - I'm specifcally making the sysLatClient object thread local... but then to get a value from it I need to make a static var in this class to track it. Seems dumb. static CString m_updateString; static CString m_strError; static CString m_strBlack; static CString m_strWhite; static DWORD m_AppArraySize; time_t m_elapsedTimeStart, m_elapsedTimeEnd; //the names and uses of the following 3 vars is stupid... Need to fix it unsigned int myCounter = 0; static unsigned int m_loopSize; //really need to change the name of this var to &quot;threadContinue&quot; or something more descriptive static unsigned int m_LoopCounterRefresh; //Debug Options BOOL m_bDebugMode = false; //save to config BOOL m_bTestUploadMode = false; //change name? BOOL m_bSysLatInOSD = false; //RTSS Configs - can't these be moved?? DWORD m_dwSharedMemoryVersion; DWORD m_dwMaxTextSize; BOOL m_bFormatTagsSupported; BOOL m_bObjTagsSupported; BOOL m_bRTSSInitConfig = false; //previously existing members BOOL m_bMultiLineOutput; BOOL m_bFormatTags; BOOL m_bFillGraphs; BOOL m_bConnected; HICON m_hIcon; UINT m_nTimerID; CFont m_font; CRichEditCtrl m_richEditCtrl; static CString m_strStatus; CString m_strInstallPath; //for dark mode COLORREF m_color; CBrush m_brush; CRect m_clientRect; CHAR pathToSysLat[MAX_PATH]; // Generated message map functions //{{AFX_MSG(CSysLat_SoftwareDlg) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnDestroy(); afx_msg LRESULT OnSTMessage(WPARAM wParam, LPARAM lParam); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. ///////////////////////////////////////////////////////////////////////////// #endif ///////////////////////////////////////////////////////////////////////////// </code></pre> <p>And here's the cpp file:</p> <pre><code>// SysLat_SoftwareDlg.cpp : implementation file // // created by Unwinder // modified by Skewjo ///////////////////////////////////////////////////////////////////////////// #include &quot;stdafx.h&quot; #include &quot;SysLat_Software.h&quot; #include &quot;SysLat_SoftwareDlg.h&quot; #include &quot;USBController.h&quot; #include &quot;HTTP_Client_Async.h&quot; #include &quot;HTTP_Client_Async_SSL.h&quot; #include &quot;SysLatPreferences.h&quot; #include &quot;AboutDlg.h&quot; #include &quot;PreferencesDlg.h&quot; #include &quot;TestCtrl.h&quot; //this one should probably have a suffix of &quot;dlg&quot;... #include &quot;version.h&quot; //probably need to move the following 2 includes to stdafx.h #include &lt;memory&gt; #include &lt;shellapi.h&gt; //TODO: // Transfer TODO to GitHub Issues... // DONE - Organize TODO... // DONE - Core Functionality // DONE - Menu // DONE - Data Issues // DONE - Optimization // DONE - Organizational Issues // DONE - Anti-Fraud // // //Issues completed before the TODO reorg: // NOT AVAILABLE(?) - Profile Setting - Set &quot;Refresh Period&quot; to 0 milliseconds - doesn't appear to be an option available via shared memory // DONE - Profile Setting - Change default corner to bottom right // DONE (opacity) - Profile Setting - Change &quot;text&quot;(foreground) color to white (255, 255, 255) with an opacity of 100 // DONE - Profile Setting - Change color of &quot;background&quot;(?) to black (0, 0, 0) with an opacity of 100 // DONE - Better yet - if I could change the box to use a plain black and plain white box so any other text isn't screwed up, that would be better // DONE - Profile Setting - Set box size to what I want it to be? // DONE - Change class/namespace name of RTSSSharedMemorySampleDlg to SysLatDlg // DONE - Change class/namespace of RTSSSharedMemorySample to SysLat // DONE - Add minimize button // DONE(well... it half-ass works) - Make System Latency appear in OSD // DONE - Save results to a table - using an array // DONE - Determine active window vs window that RTSS is operating in? // DONE(mostly) - Launch RTSS automatically in the background if it's not running // DONE - Add hotkey to restart readings (F11?) // DONE - Seperate some initialization that happens in &quot;Refresh&quot; function into a different &quot;Refresh-like&quot; function?? - partially done? // DONE - Re-org this file into 3-4 new classes - Dialog related functions, RTSS related, DrawingThread related, and USB related // DONE - BUT THERE ARE PROBLEMS(it just changed the priority of which client(syslat vs syslatStats) - Make the program statically linked so that it all packages together nicely in a single DLL // DONE(BUT NOT GREAT) - Dynamically build the &quot;drawSquare&quot; string and change the P tag to account for the current corner and all other OSD text? // DONE(Mostly...new issue created) - Then create an option to disable that setting - add keyboard arrow functionality to move it into place manually. // // // // //Core Functionality: // DONE - Add HTTP post function for uploading logs to website - use boost.beast library? // Some errors currently appear very briefly and are overwritten when the refresh function runs - Clean up the refresh function, then come up with new error scheme. // Either use error codes, or check all errors again in the refresh function(that doesn't make sense though, right?)... or maybe do dialog error pop-ups when errors occur outside of &quot;refresh&quot;? // Move ExportData function out of SysLatData? Or just use it to retrieve a jsoncpp object &amp; combine it with other jsoncpp objects // DONE - Make executable/window names mesh better together? Need a map/lookup table or something? - JUST USE PID YA IDIOT // // //Data Issues: // Save fps and frametime and other stats as well? // Add graph functionality // Put elapsed time in log file // Clear log files and put a configurable(?) cap on the number allowed // Keep track of total tests performed in a config file vs. looking for existing log files and picking up from there? // How many tests should we allow total? 100? // Would it be fine if SysLat overwrote the tests every time it was restarted? ...I think it would // // //Menu: // Enumerate all 3D programs that RTSS can run in and display them in a menu // Fix COM port change settings // Add lots more menu options - USB options, debug output, data upload, RTSS options(text color) // Box position manual override toggle // // //Anti-Fraud: // Create new dynamic build/installation process in order to obscure some code // Think about hardware/software signatures for uploading data? This probably needs more consideration on the web side // Obscure most functionality(things that don't need to be optimized) into DLLs(requires a new build/installation process) // (Anti-Fraud, Optimization, and Data)Instead of recording certain variables on every measurement(such as RTSS XY position) record them once at the start and once at the end // // //Optimization: // Move data update at the end of the CreateDrawingThread function into a different thread(or co-routine?) // Calculating the position of the box before we draw it adds unnecessary delay(?) // Make flashing square resizeable // // //Organizational Issues: // Clean up(or get rid of) static vars in SysLat_SoftwareDlg class // Clean up the refresh function a bit more by making some init functionality conditional // Attempt to get rid of most Windows type names like CString, BOOL, and INT(DWORD?) // Attempt to use a single style of string instead of &quot;string&quot;, &quot;char*&quot;, and &quot;CString&quot;. // Look further into Windows style guides &amp; straighten out all member var names with &quot;m_&quot; and the type, or do away with it completely // Look into file organization for .h and .cpp files because the repo is a mess(though it's fine in VS because of &quot;filters&quot;) // Look into class naming schemes and organization - make sure dialog classes end in &quot;dlg&quot;(?) // Check whether or not my void &quot;initialization&quot; methods need to return ints or bools for success/failure or if I can just leave them as void ////////////////////////////////////////////////////////////////////////////////////////////// //Major Bugs: // DONE - (hid the error)The SysLat RTSSClient object cannot obtain the &quot;0th&quot; RTSS OSD slot when restarting a test // Issue when switching COM ports to an existing device that isn't SysLat and back // DONE - Arrow key functionality has been optimized away somehow // // //Minor Bugs: // SysLat may not play nicely with other applications that use RTSS such as MSI Afterburner, or with advanced RTSS setups // ////////////////////////////////////////////////////////////////////////////////////////////// const int ID_COMPORT_START = 2000; const int ID_COMPORT_END = 2099; const int ID_RTSSAPP_START = 2100; const int ID_RTSSAPP_END = 2199; const int WM_STMESSAGE = WM_USER + 1; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //As a non-static non-member variable? Is this a good idea? Need to at least remove the &quot;m_&quot; from the var name... Does this make it global?? SysLatPreferences SLPref; #define SysLatOpt SLPref.m_SysLatOptions #define PrivacyOpt SLPref.m_PrivacyOptions #define DebugOpt SLPref.m_DebugOptions #define RTSSOpt SLPref.m_RTSSOptions NOTIFYICONDATA nid; int dotCounter = 0; //Define static variables - these should probably be done as inline or something... inlining is supposed to be available in C++17 and above, but Visual Studio throws a fit when I try to inline these. //also, I should probably move most of them to be global variables and NOT member variables CString CSysLat_SoftwareDlg::m_strStatus = &quot;&quot;; unsigned int CSysLat_SoftwareDlg::m_LoopCounterRefresh = 0; unsigned int CSysLat_SoftwareDlg::m_loopSize = 0xFFFFFFFF; CString CSysLat_SoftwareDlg::m_updateString = &quot;&quot;; CString CSysLat_SoftwareDlg::m_strError = &quot;&quot;; std::shared_ptr&lt;CSysLatData&gt; CSysLat_SoftwareDlg::m_pOperatingSLD = std::make_shared&lt;CSysLatData&gt;(); //does this need to be a unique_ptr? CString CSysLat_SoftwareDlg::m_strBlack = &quot;&lt;C=000000&gt;&lt;B=10,10&gt;&lt;C&gt;&quot;; CString CSysLat_SoftwareDlg::m_strWhite = &quot;&lt;C=FFFFFF&gt;&lt;B=10,10&gt;&lt;C&gt;&quot;; DWORD CSysLat_SoftwareDlg::m_sysLatOwnedSlot = 0; DWORD CSysLat_SoftwareDlg::m_AppArraySize = 0; //Windows Dialog inherited function overrides ///////////////////////////////////////////////////////////////////////////// // CSysLat_SoftwareDlg dialog ///////////////////////////////////////////////////////////////////////////// CSysLat_SoftwareDlg::CSysLat_SoftwareDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CSysLat_SoftwareDlg::IDD, pParent) { //{{AFX_DATA_INIT(CSysLat_SoftwareDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()-&gt;LoadIcon(IDR_MAINFRAME); m_strStatus = &quot;&quot;; m_strInstallPath = &quot;&quot;; m_bMultiLineOutput = TRUE; m_bFormatTags = TRUE; m_bFillGraphs = FALSE; m_bConnected = FALSE; } CSysLat_SoftwareDlg::~CSysLat_SoftwareDlg() { SLPref.WritePreferences(); } void CSysLat_SoftwareDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSysLat_SoftwareDlg) //}}AFX_DATA_MAP } ///////////////////////////////////////////////////////////////////////////// // CSysLat_SoftwareDlg message handlers ///////////////////////////////////////////////////////////////////////////// BEGIN_MESSAGE_MAP(CSysLat_SoftwareDlg, CDialogEx) //{{AFX_MSG_MAP(CSysLat_SoftwareDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_TIMER() ON_WM_DESTROY() ON_COMMAND(ID_TOOLS_EXPORTDATA, CSysLat_SoftwareDlg::ExportData) ON_COMMAND(ID_TOOLS_UPLOADDATA, CSysLat_SoftwareDlg::UploadData) ON_COMMAND(ID_SETTINGS_DEBUGMODE, CSysLat_SoftwareDlg::DebugMode) ON_COMMAND(ID_SETTINGS_TESTUPLOADMODE, CSysLat_SoftwareDlg::TestUploadMode) ON_COMMAND(ID_SETTINGS_DISPLAYSYSLATINOSD, CSysLat_SoftwareDlg::DisplaySysLatInOSD) ON_COMMAND(ID_TOOLS_NEWTEST, CSysLat_SoftwareDlg::ReInitThread) ON_COMMAND(ID_SETTINGS_PREFERENCES, CSysLat_SoftwareDlg::OpenPreferences) ON_COMMAND(ID_TOOLS_TESTCONTROL, CSysLat_SoftwareDlg::OpenTestCtrl) ON_COMMAND_RANGE(ID_COMPORT_START, ID_COMPORT_END, CSysLat_SoftwareDlg::OnComPortChanged) ON_COMMAND_RANGE(ID_RTSSAPP_START, ID_RTSSAPP_END, CSysLat_SoftwareDlg::OnTargetWindowChanged) ON_MESSAGE(WM_STMESSAGE, CSysLat_SoftwareDlg::OnSTMessage) //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CSysLat_SoftwareDlg::OnInitDialog() { CDialogEx::OnInitDialog(); m_color = RGB(136, 217, 242); m_brush.CreateSolidBrush(m_color); GetModuleFileName(NULL, pathToSysLat, MAX_PATH); CWnd* pMainDlg = GetDlgItem(IDD_SYSLAT_SOFTWARE_DIALOG); if (pMainDlg) { pMainDlg-&gt;GetClientRect(&amp;m_clientRect); } ASSERT((IDM_ABOUTBOX &amp; 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX &lt; 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu-&gt;AppendMenu(MF_SEPARATOR); pSysMenu-&gt;AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } SetIcon(m_hIcon, TRUE); CWnd* pPlaceholder = GetDlgItem(IDC_PLACEHOLDER); if (pPlaceholder) { CRect rect; pPlaceholder-&gt;GetClientRect(&amp;rect); if (!m_richEditCtrl.Create(WS_VISIBLE | ES_READONLY | ES_MULTILINE | ES_AUTOHSCROLL | WS_HSCROLL | ES_AUTOVSCROLL | WS_VSCROLL, rect, this, 0)) return FALSE; m_font.CreateFont(-11, 0, 0, 0, FW_REGULAR, 0, 0, 0, BALTIC_CHARSET, 0, 0, 0, 0, &quot;Courier New&quot;); m_richEditCtrl.SetFont(&amp;m_font); } if (PrivacyOpt.m_bFirstRun) { ::MessageBox(NULL, &quot;This appears to be the first time you've run SysLat from this directory. Please set your privacy options.&quot;, &quot;SysLat First Run&quot;, MB_OK); OpenPreferences(); PrivacyOpt.m_bFirstRun = false; } if (PrivacyOpt.m_bRunOnStartup) { SetSURegValue(pathToSysLat); } else { SetSURegValue(&quot;&quot;); } //m_bTestUploadMode = true; if(PrivacyOpt.m_bAutoCheckUpdates){ CheckUpdate(); } m_nTimerID = SetTimer(0x1234, 1000, NULL); //Used by OnTimer function to refresh dialog box &amp; OSD time(&amp;m_elapsedTimeStart); //Used to keep track of test length m_hardwareID.ExportData(SysLatOpt.m_LogDir); m_machineInfo.ExportData(SysLatOpt.m_LogDir); Refresh(); unsigned threadID; m_drawingThreadHandle = (HANDLE)_beginthreadex(0, 0, CreateDrawingThread, &amp;myCounter, 0, &amp;threadID); SetThreadPriority(m_drawingThreadHandle, THREAD_PRIORITY_ABOVE_NORMAL);//31 is(apparently?) the highest possible thread priority - may be bad because it could cause deadlock using a loop? Need to read more here: https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities return TRUE; // return TRUE unless you set the focus to a control } void CSysLat_SoftwareDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID &amp; 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else if ((nID &amp; 0xFFF0) == SC_MINIMIZE) { nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = m_hWnd; nid.uID = 100; nid.uVersion = NOTIFYICON_VERSION; nid.uCallbackMessage = WM_STMESSAGE; nid.hIcon = AfxGetApp()-&gt;LoadIcon(IDR_MAINFRAME); strcpy_s(nid.szTip, &quot;SysLat&quot;); nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; Shell_NotifyIcon(NIM_ADD, &amp;nid); ModifyStyleEx(WS_EX_APPWINDOW, WS_EX_TOOLWINDOW); // Minimizing, post to main dialogue also. AfxGetMainWnd()-&gt;ShowWindow(SW_MINIMIZE); } //else if ((nID &amp; 0xFFF0) == SC_CLOSE) { // nid.cbSize = sizeof(NOTIFYICONDATA); // nid.hWnd = m_hWnd; // nid.uID = 100; // nid.uVersion = NOTIFYICON_VERSION; // nid.uCallbackMessage = WM_STMESSAGE; // nid.hIcon = AfxGetApp()-&gt;LoadIcon(IDR_MAINFRAME); // strcpy_s(nid.szTip, &quot;SysLat&quot;); // nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; // Shell_NotifyIcon(NIM_ADD, &amp;nid); // ModifyStyleEx(WS_EX_APPWINDOW, WS_EX_TOOLWINDOW); // // Minimizing, post to main dialogue also. // AfxGetMainWnd()-&gt;ShowWindow(SW_MINIMIZE); //} else { CDialogEx::OnSysCommand(nID, lParam); } } void CSysLat_SoftwareDlg::OnPaint() { if (IsIconic()) { //THIS CODE FOR THE MINIMIZE BUTTON IS NO LONGER(NEVER WAS??) NEEDED?? //CPaintDC dc(this); // device context for painting //SendMessage(WM_ICONERASEBKGND, (WPARAM)dc.GetSafeHdc(), 0); //// Center icon in client rectangle //int cxIcon = GetSystemMetrics(SM_CXICON); //int cyIcon = GetSystemMetrics(SM_CYICON); //CRect rect; //GetClientRect(&amp;rect); //int x = (rect.Width() - cxIcon + 1) / 2; //int y = (rect.Height() - cyIcon + 1) / 2; //dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } HCURSOR CSysLat_SoftwareDlg::OnQueryDragIcon() { return (HCURSOR)m_hIcon; } void CSysLat_SoftwareDlg::OnTimer(UINT nIDEvent) { Refresh(); CDialogEx::OnTimer(nIDEvent); } void CSysLat_SoftwareDlg::OnDestroy() { if (m_nTimerID) KillTimer(m_nTimerID); m_nTimerID = NULL; MSG msg; while (PeekMessage(&amp;msg, m_hWnd, WM_TIMER, WM_TIMER, PM_REMOVE)); TerminateThread(m_drawingThreadHandle, 0); //Does exit code need to be 0 for this? m_SysLatStatsClient.ReleaseOSD(); //m_pOperatingSLD-&gt;CloseSLDMutex(); CDialogEx::OnDestroy(); } LRESULT CSysLat_SoftwareDlg::OnSTMessage(WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(wParam); UNREFERENCED_PARAMETER(lParam); if (lParam == WM_LBUTTONDBLCLK){ if (IsIconic()) { ModifyStyleEx(WS_EX_TOOLWINDOW, WS_EX_APPWINDOW); ShowWindow(SW_SHOWNORMAL); Shell_NotifyIcon(NIM_DELETE, &amp;nid); } } return 0; } //Dialog functions string CSysLat_SoftwareDlg::GetProcessNameFromPID(DWORD processID) { string ret; HANDLE Handle = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID ); if (Handle) { DWORD buffSize = 1024; CHAR Buffer[1024]; if (QueryFullProcessImageName(Handle, 0, Buffer, &amp;buffSize)) { ret = strrchr(Buffer, '\\') + 1; // I can't believe this works } else { printf(&quot;Error GetModuleBaseName : %lu&quot;, GetLastError()); } CloseHandle(Handle); } else { printf(&quot;Error OpenProcess : %lu&quot;, GetLastError()); } return ret; } string CSysLat_SoftwareDlg::GetActiveWindowTitle() { char wnd_title[256]; CWnd* pWnd = GetForegroundWindow(); ::GetWindowText((HWND)*pWnd, wnd_title, 256); //Had to use scope resolution because this function is defined in both WinUser.h and afxwin.h return wnd_title; } void CSysLat_SoftwareDlg::ProcessNameTrim(string&amp; processName, string&amp; activeWindowTitle){ size_t pos = processName.find(&quot;.exe&quot;); if (pos != string::npos) { processName.replace(pos, processName.size(), &quot;&quot;); } while ((pos = processName.find(&quot; &quot;)) != string::npos) { processName.replace(pos, 1, &quot;&quot;); } std::transform(processName.begin(), processName.end(), processName.begin(), [](unsigned char c) { return std::tolower(c); }); while ((pos = activeWindowTitle.find(&quot; &quot;)) != string::npos) { activeWindowTitle.replace(pos, 1, &quot;&quot;); } std::transform(activeWindowTitle.begin(), activeWindowTitle.end(), activeWindowTitle.begin(), [](unsigned char c) { return std::tolower(c); }); } BOOL CSysLat_SoftwareDlg::PreTranslateMessage(MSG* pMsg) { if (pMsg-&gt;message == WM_KEYDOWN) { switch (pMsg-&gt;wParam) { case VK_F11: ReInitThread(); return TRUE; case ' ': if (!m_bConnected) { if (!CRTSSClient::m_strInstallPath.IsEmpty()) ShellExecute(GetSafeHwnd(), &quot;open&quot;, CRTSSClient::m_strInstallPath, NULL, NULL, SW_SHOWNORMAL); } return TRUE; case VK_UP: if (RTSSOpt.m_internalY &gt; 0) { RTSSOpt.m_internalY--; } //else appendError ?? RTSSOpt.m_bPositionManualOverride = true; return TRUE; case VK_DOWN: if (RTSSOpt.m_internalY &lt; 255) { RTSSOpt.m_internalY++; } RTSSOpt.m_bPositionManualOverride = true; return TRUE; case VK_LEFT: if (RTSSOpt.m_internalX &gt; 0) { RTSSOpt.m_internalX--; } RTSSOpt.m_bPositionManualOverride = true; return TRUE; case VK_RIGHT: if (RTSSOpt.m_internalX &lt; 255) { RTSSOpt.m_internalX++; } RTSSOpt.m_bPositionManualOverride = true; return TRUE; case 'R': CRTSSClient::SetProfileProperty(&quot;&quot;, &quot;BaseColor&quot;, 0xFF0000); return TRUE; case 'G': CRTSSClient::SetProfileProperty(&quot;&quot;, &quot;BaseColor&quot;, 0x00FF00); return TRUE; case 'B': CRTSSClient::SetProfileProperty(&quot;&quot;, &quot;BaseColor&quot;, 0x0000FF); return TRUE; case 'F': if (m_bConnected) { m_bFormatTags = !m_bFormatTags; Refresh(); } break; case 'I': if (m_bConnected) { m_bFillGraphs = !m_bFillGraphs; Refresh(); } break; } } return CDialogEx::PreTranslateMessage(pMsg); } void CSysLat_SoftwareDlg::Refresh() { //Had to add this section because it was initializing fine in debug mode, but then initializing COMPortCount too fast in release mode??? Probably some stupid issue with my debug macros... CMenu* MainMenu = GetMenu(); CMenu* SettingsMenu = MainMenu-&gt;GetSubMenu(1); CMenu* ComPortMenu = SettingsMenu-&gt;GetSubMenu(0); char menuCString[256]; MainMenu-&gt;GetMenuString(ID_USBPORT_PLACEHOLDER, (LPSTR)menuCString, 256, (UINT)MF_BYCOMMAND); if (strcmp(menuCString, &quot;Placeholder&quot;) == 0) { m_COMPortCount = 0; } CUSBController usbController; usbController.EnumSerialPorts(m_COMPortInfo, FALSE); if (m_COMPortInfo.GetSize() != m_COMPortCount) { R_DynamicComPortMenu(); } if (m_bConnected) {//m_bConnected is never set to true?? DWORD AppArraySize = CRTSSClient::GetAppArray(); if (m_AppArraySize != AppArraySize) { R_DynamicAppMenu(); m_AppArraySize = AppArraySize; DEBUG_PRINT(&quot;AppArraySize: &quot; + to_string(AppArraySize)) } } if (!(CRTSSClient::m_profileInterface.IsInitialized())) { CRTSSClient::InitRTSSInterface(); } RTSSOpt.m_positionX = CRTSSClient::GetProfileProperty(&quot;&quot;, &quot;PositionX&quot;); RTSSOpt.m_positionY = CRTSSClient::GetProfileProperty(&quot;&quot;, &quot;PositionY&quot;); if (m_bConnected &amp;&amp; !m_bRTSSInitConfig) { R_GetRTSSConfigs(); } else { m_bRTSSInitConfig = false; } m_strStatus = &quot;&quot;; if (!R_SysLatStats()) return; if (m_bDebugMode) { R_Position(); R_ProcessNames(); } R_StrOSD(); if (!m_bSysLatInOSD) { //need to add another condition to make this only happen once so that it will clear whatever exists in the buffer... or maybe use the releaseOSD function properly? IDK m_SysLatStatsClient.UpdateOSD(&quot;&quot;); } //Need to make a new function &amp; boolean for displaying controls/hints if (CRTSSClient::m_profileInterface.IsInitialized()) { m_strStatus += &quot;\n\n-Press &lt;Up&gt;,&lt;Down&gt;,&lt;Left&gt;,&lt;Right&gt; to change OSD position in global profile&quot;; if (DebugOpt.m_bSysLatInOSD) { m_strStatus += &quot;\n-Press &lt;R&gt;,&lt;G&gt;,&lt;B&gt; to change OSD color in global profile&quot;; } } if (!m_strError.IsEmpty()) { m_strStatus += &quot;\n\nErrors:&quot;; m_strStatus.Append(m_strError); m_strError = &quot;&quot;; } m_richEditCtrl.SetWindowText(m_strStatus); } void CSysLat_SoftwareDlg::R_GetRTSSConfigs() { m_dwSharedMemoryVersion = CRTSSClient::GetSharedMemoryVersion(); m_dwMaxTextSize = (m_dwSharedMemoryVersion &gt;= 0x00020007) ? sizeof(RTSS_SHARED_MEMORY::RTSS_SHARED_MEMORY_OSD_ENTRY().szOSDEx) : sizeof(RTSS_SHARED_MEMORY::RTSS_SHARED_MEMORY_OSD_ENTRY().szOSD); m_bFormatTagsSupported = (m_dwSharedMemoryVersion &gt;= 0x0002000b); //text format tags are supported for shared memory v2.11 and higher m_bObjTagsSupported = (m_dwSharedMemoryVersion &gt;= 0x0002000c); //embedded object tags are supporoted for shared memory v2.12 and higher m_bRTSSInitConfig = true; } BOOL CSysLat_SoftwareDlg::R_SysLatStats() { //this timer stuff definitely needs to be in the SLD time(&amp;m_elapsedTimeEnd); double dif = difftime(m_elapsedTimeEnd, m_elapsedTimeStart); int minutes = static_cast&lt;int&gt;(dif) / 60; int seconds = static_cast&lt;int&gt;(dif) % 60; auto&amp; data = m_pOperatingSLD-&gt;GetData(); if (minutes &gt;= SysLatOpt.m_maxTestDuration) { ReInitThread(); } double measurementsPerSecond = data.m_statistics.counter / dif; m_strStatus.AppendFormat(&quot;Elapsed Time: %02d:%02d&quot;, minutes, seconds); if (m_pOperatingSLD-&gt;GetSystemLatency() &lt; 500) { //using &quot;c_str()&quot; here because &quot;stoi(m_pOperatingSLD-&gt;GetStringResult())&quot; was getting immediate exceptions for some reason... m_strStatus.AppendFormat(&quot;\nSystem Latency: %i&quot;, m_pOperatingSLD-&gt;GetSystemLatency()); } else { m_strStatus.AppendFormat(&quot;\nSystem Latency: Waiting&quot;); if (dotCounter == 1) { m_strStatus.AppendFormat(&quot;.&quot;); } else if (dotCounter == 2) { m_strStatus.AppendFormat(&quot;..&quot;); } else if (dotCounter == 3) { m_strStatus.AppendFormat(&quot;...&quot;); } } m_strStatus.AppendFormat(&quot;\nLoop Counter : %d&quot;, data.m_statistics.counter); if (isnan(measurementsPerSecond)) { m_strStatus.AppendFormat(&quot;\nMeasurements Per Second: 0.00&quot;); } else { m_strStatus.AppendFormat(&quot;\nMeasurements Per Second: %.2f&quot;, measurementsPerSecond); //This value should probably be in the SLD... } if (data.m_statistics.average &lt; 500) { m_strStatus.AppendFormat(&quot;\nSystem Latency Average: %.2f&quot;, data.m_statistics.average); } else { m_strStatus.AppendFormat(&quot;\nSystem Latency Average: Waiting&quot;); if (dotCounter == 1) { m_strStatus.AppendFormat(&quot;.&quot;); } else if (dotCounter == 2) { m_strStatus.AppendFormat(&quot;..&quot;); } else if (dotCounter == 3) { m_strStatus.AppendFormat(&quot;...&quot;); } } dotCounter++; if (dotCounter &gt;= 4) { dotCounter = 0; } m_strStatus.AppendFormat(&quot;\nLoop Counter EVR(expected value range, 3-100): %d &quot;, data.m_statisticsEVR.counter); m_strStatus.AppendFormat(&quot;\nSystem Latency Average(EVR): %.2f&quot;, data.m_statisticsEVR.average); return true; //this return value needs to change or be removed } void CSysLat_SoftwareDlg::R_Position() { m_strStatus.AppendFormat(&quot;\n\nClients num: %d&quot;, CRTSSClient::clientsNum); m_strStatus.AppendFormat(&quot;\nSysLat Owned Slot: %d&quot;, m_sysLatOwnedSlot); m_strStatus.AppendFormat(&quot;\nPositionX: %d&quot;, RTSSOpt.m_positionX); m_strStatus.AppendFormat(&quot;\nPositionY: %d&quot;, RTSSOpt.m_positionY); } void CSysLat_SoftwareDlg::R_ProcessNames() { DWORD dwLastForegroundAppProcessID = CRTSSClient::GetLastForegroundAppID(); m_strStatus.Append(&quot;\n\nLast RTSS Foreground App Name: &quot;); string processName = GetProcessNameFromPID(dwLastForegroundAppProcessID); m_strStatus += processName.c_str(); m_strStatus.Append(&quot;\nCurrently active window: &quot;); string activeWindowTitle = GetActiveWindowTitle(); m_strStatus += activeWindowTitle.c_str(); ProcessNameTrim(processName, activeWindowTitle); m_strStatus.Append(&quot;\nTrimmed:&quot;); m_strStatus += processName.c_str(); m_strStatus.Append(&quot;\nTrimmed:&quot;); m_strStatus += activeWindowTitle.c_str(); } void CSysLat_SoftwareDlg::R_StrOSD() { //BOOL bTruncated = FALSE; string strOSD;// = strOSDBuilder.Get(bTruncated); strOSD += m_pOperatingSLD-&gt;GetSystemLatency(); if (!(strOSD.size() == 0)) { bool bResult = m_SysLatStatsClient.UpdateOSD(strOSD.c_str()); m_bConnected = bResult; if (bResult) { m_strStatus += &quot;\nTarget Window: &quot;; m_strStatus += (SysLatOpt.m_targetApp).c_str(); /* m_strStatus += &quot;\n\nThe following text is being forwarded to OSD:\nFrom SysLat client: &quot; + m_updateString + &quot;\nFrom SysLatStats client: &quot; + strOSD; if (m_bFormatTagsSupported) m_strStatus += &quot;\n-Press &lt;F&gt; to toggle OSD text formatting tags&quot;; if (m_bFormatTagsSupported) m_strStatus += &quot;\n-Press &lt;I&gt; to toggle graphs fill mode&quot;; */ //if (bTruncated) // AppendError(&quot;Warning: The text is too long to be displayed in OSD, some info has been truncated!&quot;); } else { if (CRTSSClient::m_strInstallPath.IsEmpty()) AppendError(&quot;Error: Failed to connect to RTSS shared memory!\nHints:\n-Install RivaTuner Statistics Server&quot;); else AppendError(&quot;Error: Failed to connect to RTSS shared memory!\nHints:\n-Press &lt;Space&gt; to start RivaTuner Statistics Server&quot;); } //TODO: 1-6-21 - I THOUGHT I FREAKING FIXED THIS?? if (m_sysLatOwnedSlot != 0) { //AppendError(&quot;The SysLat client is unable to occupy RTSS client slot 0.\nThis may cause issues with the blinking square appearing in the corner.\nTo resolve this error try one of the following:\n\t1. Close other applications that use RTSS(such as MSI Afterburner)\n\t2. Restart RTSS\n\t3. Restart the testing phase(by pressing &lt;F11&gt;).&quot;); } } } void CSysLat_SoftwareDlg::R_DynamicComPortMenu() { CMenu* MainMenu = GetMenu(); CMenu* SettingsMenu = MainMenu-&gt;GetSubMenu(1); CMenu* ComPortMenu = SettingsMenu-&gt;GetSubMenu(0); if (ComPortMenu) { BOOL appended = false; BOOL deleted = false; m_COMPortCount = 0; for(auto i = 0; i &lt; m_COMPortInfo.GetSize(); i++) { ComPortMenu-&gt;DeleteMenu(ID_COMPORT_START + m_COMPortCount, MF_BYCOMMAND); if (m_COMPortCount &lt; ID_COMPORT_END - ID_COMPORT_START) { string usb_info = m_COMPortInfo[i].strFriendlyName; DEBUG_PRINT(&quot;Friendly Name: &quot; + usb_info) appended = ComPortMenu-&gt;AppendMenu(MF_STRING, ID_COMPORT_START + m_COMPortCount, m_COMPortInfo[i].strFriendlyName); string menuString = m_COMPortInfo[i].strFriendlyName; size_t pos = menuString.rfind(&quot;(&quot;); menuString.replace(0, pos + 1, &quot;&quot;); pos = menuString.rfind(&quot;)&quot;); menuString.replace(pos, menuString.size(), &quot;&quot;); if (strcmp(menuString.c_str(), SysLatOpt.m_PortSpecifier.c_str()) == 0) { MainMenu-&gt;CheckMenuItem(ID_COMPORT_START + m_COMPortCount, MF_CHECKED); } m_COMPortCount++; } else { //catch or throw errors here maybe? break; } } deleted = ComPortMenu-&gt;DeleteMenu(ID_USBPORT_PLACEHOLDER, MF_BYCOMMAND); DEBUG_PRINT((&quot;String appended: &quot; + to_string(appended)).c_str()) DEBUG_PRINT((&quot;Placeholder deleted: &quot; + to_string(deleted)).c_str()) } DrawMenuBar(); } void CSysLat_SoftwareDlg::R_DynamicAppMenu() { CMenu* MainMenu = GetMenu(); CMenu* SettingsMenu = MainMenu-&gt;GetSubMenu(1); CMenu* TargetAppMenu = SettingsMenu-&gt;GetSubMenu(1); if (TargetAppMenu) { BOOL appended = false; BOOL deleted = false; int count = 0; for (auto const&amp; [pid, pName] : CRTSSClient::m_vszAppArr) { SettingsMenu-&gt;DeleteMenu(ID_RTSSAPP_START + count, MF_BYCOMMAND); if (count &lt; ID_RTSSAPP_END - ID_RTSSAPP_START) { if (pName != &quot;SysLat_Software&quot;) { string id_name = pName + &quot; (&quot; + to_string(pid) + &quot;)&quot;; appended = TargetAppMenu-&gt;AppendMenu(MF_STRING, ID_RTSSAPP_START + count, id_name.c_str()); if (strcmp(pName.c_str(), SysLatOpt.m_targetApp.c_str()) == 0) { MainMenu-&gt;CheckMenuItem(ID_RTSSAPP_START + count, MF_CHECKED); } count++; } } else { //error here? break; } } deleted = TargetAppMenu-&gt;DeleteMenu(ID_TARGETWINDOW_PLACEHOLDER, MF_BYCOMMAND); DEBUG_PRINT((&quot;String appended: &quot; + to_string(appended)).c_str()) DEBUG_PRINT((&quot;Placeholder deleted: &quot; + to_string(deleted)).c_str()) } DrawMenuBar(); } void CSysLat_SoftwareDlg::AppendError(const CString&amp; error) { m_strError.Append(&quot;\n&quot;); m_strError.Append(error); m_strError.Append(&quot;\n&quot;); } //SysLat thread functions void CSysLat_SoftwareDlg::ReInitThread() { m_loopSize = 0; WaitForSingleObjectEx(m_drawingThreadHandle, INFINITE, false); m_pOperatingSLD-&gt;m_targetApp = SysLatOpt.m_targetApp; m_pOperatingSLD-&gt;SetEndTime(); m_loopSize = 0xFFFFFFFF; //Reset the timer time(&amp;m_elapsedTimeStart); myCounter = 0; //Save the data from the test that just completed in a vector of &quot;SysLatData&quot;s m_vpPreviousSLD.push_back(m_pOperatingSLD); m_pOperatingSLD = std::make_shared&lt;CSysLatData&gt;(); //Restart the thread m_drawingThreadHandle = (HANDLE)_beginthreadex(0, 0, CreateDrawingThread, &amp;myCounter, 0, 0); SetThreadPriority(m_drawingThreadHandle, THREAD_PRIORITY_ABOVE_NORMAL); //Convert the previous data to JSON m_vpPreviousSLD.back()-&gt;CreateJSONSLD(); //Export and upload the data if enabled if (PrivacyOpt.m_bAutoExportLogs &amp;&amp; SysLatOpt.m_maxLogs &gt; 0) { ExportData(); } if (PrivacyOpt.m_bAutoUploadLogs) { UploadData(); } } unsigned int __stdcall CSysLat_SoftwareDlg::CreateDrawingThread(void* data) //this is probably dangerous, right? { int TIMEOUT = 5; //this should probably be a defined constant int serialReadData = 0; string sysLatResults; CRTSSClient sysLatClient(&quot;SysLat&quot;, 0); m_sysLatOwnedSlot = sysLatClient.ownedSlot; //the following should not be here because if RTSS isn't running when this is hit, the version is &quot;0&quot; m_pOperatingSLD-&gt;m_RTSSVersion = &quot;v&quot; + to_string(sysLatClient.sharedMemoryVersion); CUSBController usbController; HANDLE hPort = usbController.OpenComPort(SysLatOpt.m_PortSpecifier.c_str()); while (!usbController.IsComPortOpened(hPort) &amp;&amp; m_loopSize &gt; 0) { hPort = usbController.OpenComPort(SysLatOpt.m_PortSpecifier.c_str()); AppendError(&quot;Failed to open COM port: &quot;); AppendError(SysLatOpt.m_PortSpecifier.c_str()); Sleep(1000); } DrawSquare(sysLatClient, m_strBlack); LARGE_INTEGER StartingTime, EndingTime, ElapsedMicrosecondsDraw, ElapsedMicrosecondsExtra, Frequency; QueryPerformanceFrequency(&amp;Frequency); vector&lt;long long&gt; timeVectorDraw, timeVectorExtra; for (unsigned int loopCounter = 0; loopCounter &lt; m_loopSize; loopCounter++) { QueryPerformanceCounter(&amp;StartingTime); time_t start = time(NULL); while (serialReadData != 65 &amp;&amp; time(NULL) - start &lt; TIMEOUT) { serialReadData = usbController.ReadByte(hPort); } DrawSquare(sysLatClient, m_strWhite); while (serialReadData != 66 &amp;&amp; time(NULL) - start &lt; TIMEOUT) { serialReadData = usbController.ReadByte(hPort); } DrawSquare(sysLatClient, m_strBlack); sysLatResults = &quot;&quot;; while (serialReadData != 67 &amp;&amp; time(NULL) - start &lt; TIMEOUT) { serialReadData = usbController.ReadByte(hPort); if (serialReadData != 67 &amp;&amp; serialReadData != 65 &amp;&amp; serialReadData != 66) { sysLatResults += (char)serialReadData; } } QueryPerformanceCounter(&amp;EndingTime); ElapsedMicrosecondsDraw.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart; ElapsedMicrosecondsDraw.QuadPart *= 1000000; ElapsedMicrosecondsDraw.QuadPart /= Frequency.QuadPart; timeVectorDraw.push_back(ElapsedMicrosecondsDraw.QuadPart); //I think everything below(ESPECIALLY the &quot;UpdateSLD&quot; method) should be happening in a different thread so that the serial reads can continue uninterrupted - could the following be a coroutine? // 1-3-2021 thinking on this more, I need the following work to be &quot;queued&quot; up for the main thread... Not sure what the best way to accomplish that is. // 1-13-2021 - After some extensive testing, these functions are taking anywhere from 100-500 microseconds(half of a milllisecond) to complete, and should not be affecting the test accuracy by very much... still needs to be fixed though //push_back() lots of this stuff to a vector and then have the Refresh(?) function handle it? QueryPerformanceCounter(&amp;StartingTime); string processName = GetProcessNameFromPID(CRTSSClient::GetLastForegroundAppID()); string activeWindowTitle; if (loopCounter &lt; m_loopSize) { //this was for a really strange issue when trying to end the thread. activeWindowTitle = GetActiveWindowTitle(); } else { activeWindowTitle = &quot;&quot;; } ProcessNameTrim(processName, activeWindowTitle); //This does the same as the block above, but uses PID instead of a bunch of unnecessary string editing. //Both of the following work? I bet there's another(probably better way) to use the class name instead of the macro-definition(?) &quot;_WINUSER_&quot;. //HWND hWnd = ::GetForegroundWindow(); HWND hWnd = _WINUSER_::GetForegroundWindow(); DWORD PID; GetWindowThreadProcessId(hWnd, &amp;PID); DWORD RTSS_Pid = CRTSSClient::GetLastForegroundAppID(); m_pOperatingSLD-&gt;UpdateSLD(loopCounter, sysLatResults, processName, activeWindowTitle, PID, RTSS_Pid); QueryPerformanceCounter(&amp;EndingTime); ElapsedMicrosecondsExtra.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart; ElapsedMicrosecondsExtra.QuadPart *= 1000000; ElapsedMicrosecondsExtra.QuadPart /= Frequency.QuadPart; timeVectorExtra.push_back(ElapsedMicrosecondsExtra.QuadPart); //DEBUG_PRINT(&quot;Draw: \t&quot; + to_string(ElapsedMicrosecondsDraw.QuadPart) + &quot;\tExtra: \t&quot; + to_string(ElapsedMicrosecondsExtra.QuadPart)) } long long totalMicroseconds = 0; long long averageMicroseconds = 0; for (auto i = 0; i &lt; timeVectorDraw.size(); i++) { totalMicroseconds += timeVectorDraw[i]; } double averageMilliseconds; if (timeVectorDraw.size() != 0) { averageMicroseconds = totalMicroseconds / timeVectorDraw.size(); averageMilliseconds = averageMicroseconds / 1000; //DEBUG_PRINT(&quot;Draw Total microseconds: &quot; + to_string(totalMicroseconds)) //DEBUG_PRINT(&quot;Draw Average microseconds: &quot; + to_string(averageMicroseconds)) //DEBUG_PRINT(&quot;Draw Average milliseconds: &quot; + to_string(averageMilliseconds)) } totalMicroseconds = 0; averageMicroseconds = 0; if (timeVectorExtra.size() != 0) { for (auto i = 0; i &lt; timeVectorExtra.size(); i++) { totalMicroseconds += timeVectorExtra[i]; } averageMicroseconds = totalMicroseconds / timeVectorExtra.size(); averageMilliseconds = averageMicroseconds / 1000; } //DEBUG_PRINT(&quot;Extra Total microseconds: &quot; + to_string(totalMicroseconds)) //DEBUG_PRINT(&quot;Extra Average microseconds: &quot; + to_string(averageMicroseconds)) //DEBUG_PRINT(&quot;Extra Average milliseconds: &quot; + to_string(averageMilliseconds)) usbController.CloseComPort(hPort); sysLatClient.ReleaseOSD(); return 0; } void CSysLat_SoftwareDlg::DrawSquare(CRTSSClient sysLatClient, CString&amp; colorString) { m_updateString = &quot;&quot;; //The following conditional is FAR from perfect... In order for it to work properly I may need to count the number of rows and columns(in zoomed pixel units?) and use that value. if (sysLatClient.ownedSlot == 0 &amp;&amp; !RTSSOpt.m_bPositionManualOverride) { if ((int)RTSSOpt.m_positionX &lt; 0) { RTSSOpt.m_internalX = 0; } if ((int)RTSSOpt.m_positionY &lt; 0) { //y = CRTSSClient::clientsNum * 20; RTSSOpt.m_internalY = 20; } m_updateString.AppendFormat(&quot;&lt;P=%d,%d&gt;&quot;, RTSSOpt.m_internalX, RTSSOpt.m_internalY); m_updateString += colorString; m_updateString += &quot;&lt;P=0,0&gt;&quot;; } else if (RTSSOpt.m_bPositionManualOverride) { m_updateString.AppendFormat(&quot;&lt;P=%d,%d&gt;&quot;, RTSSOpt.m_internalX, RTSSOpt.m_internalY); m_updateString += colorString; m_updateString += &quot;&lt;P=0,0&gt;&quot;; } else { m_updateString += colorString; } sysLatClient.UpdateOSD(m_updateString); } //Dialog menu functions //Tools //The version without a parameter uses the other classes &quot;ExportData&quot; functions void CSysLat_SoftwareDlg::ExportData() { if (m_vpPreviousSLD.size() &gt; 0) { for (unsigned int i = 0; i &lt; m_vpPreviousSLD.size(); i++) { //The following code is for testing file export changes - maybe I should make it run only in debugMode? //Json::Value newJSON; //const Json::Value* const sources[] = { // &amp;m_previousSLD[i]-&gt;m_JSONsld, // &amp;m_hardwareID.HardwareIDJSON, // &amp;m_machineInfo.MachineInfoJSON //}; //for (const Json::Value* src : sources) // for (auto srcIt = src-&gt;begin(); srcIt != src-&gt;end(); ++srcIt) // newJSON[srcIt.name()] = *srcIt; //ExportData(newJSON); if (!m_vpPreviousSLD[i]-&gt;m_bDataExported) { m_vpPreviousSLD[i]-&gt;ExportData(i, SysLatOpt.m_LogDir, SysLatOpt.m_maxLogs); } //else { // string error = &quot;Data from test &quot; + to_string(i) + &quot; already exported.&quot;; //this error message is garbage in every way // AppendError(error.c_str()); //} } } else { //this is one of the errors that only appears for a few seconds and then dissapears... open an error dialog instead maybe? AppendError(&quot;No tests have completed yet. \nPress F11 to begin a new test(ending the current test), or wait for the current test to finish. \nYou can change the test size in the menu.&quot;); // (Not yet you can't lol) } } //This overload with a &quot;Json::Value&quot; as a parameter does the export here using streams void CSysLat_SoftwareDlg::ExportData(Json::Value stuffToExport) { std::ofstream exportData; exportData.open(&quot;./logs/exportSLD.json&quot;); if (exportData.is_open()) { exportData &lt;&lt; stuffToExport; } else { DEBUG_PRINT(&quot;\nError exporting JSON SLD file.\n&quot;) } exportData.close(); } void CSysLat_SoftwareDlg::UploadData() { //I DIDN'T WANT TO SET THE API TARGET LIKE THIS - HAD TO DO IT THIS WAY BECAUSE FUNCTIONS THAT ARE USED BY DIALOG MENU BUTTONS CAN'T HAVE PARAMETERS &lt;.&lt; const char* APItarget = &quot;/api/benchmarkData&quot;; if (m_vpPreviousSLD.size() &gt; 0) { for (unsigned int i = 0; i &lt; m_vpPreviousSLD.size(); i++) { http::response&lt;http::string_body&gt; uploadStatus; if (!m_vpPreviousSLD[i]-&gt;m_bDataUploaded) { Json::Value newJSON; const Json::Value* const sources[] = { &amp;m_vpPreviousSLD[i]-&gt;GetJSONData(), &amp;m_hardwareID.HardwareIDJSON, &amp;m_machineInfo.MachineInfoJSON }; for (const Json::Value* src : sources) for (auto srcIt = src-&gt;begin(); srcIt != src-&gt;end(); ++srcIt) newJSON[srcIt.name()] = *srcIt; if (m_bTestUploadMode) { uploadStatus = upload_data(newJSON, APItarget); } else { uploadStatus = upload_data_secure(newJSON, APItarget); } m_vpPreviousSLD[i]-&gt;m_bDataUploaded = true; //need to make uploadStatus return a bool or something and use it to set this var } /*else { string error = &quot;Data from test &quot; + to_string(i) + &quot; already uploaded.&quot;; AppendError(error.c_str()); }*/ } } else { //this is one of the errors that only appears for a few seconds and then dissapears... open an error dialog instead maybe? AppendError(&quot;No tests have completed yet. \nPress F11 to begin a new test(ending the current test), or wait for the current test to finish. \nYou can change the test size in the menu.&quot;); // (Not yet you can't lol) } } void CSysLat_SoftwareDlg::OnComPortChanged(UINT nID) { int nButton = nID - ID_COMPORT_START; ASSERT(nButton &gt;= 0 &amp;&amp; nButton &lt; 100); CMenu* MainMenu = GetMenu(); int count = 0; for (auto i = 0; i &lt; m_COMPortInfo.GetSize(); i++) { if (count == nButton) { MainMenu-&gt;CheckMenuItem(nID, MF_CHECKED); char menuCString[256]; MainMenu-&gt;GetMenuString(nID, (LPSTR)menuCString, 256, (UINT)MF_BYCOMMAND); string menuString = menuCString; size_t pos = menuString.rfind(&quot;(&quot;); menuString.replace(0, pos + 1, &quot;&quot;); pos = menuString.rfind(&quot;)&quot;); menuString.replace(pos, menuString.size(), &quot;&quot;); SysLatOpt.m_PortSpecifier = menuString; } else { MainMenu-&gt;CheckMenuItem(count + ID_COMPORT_START, MF_UNCHECKED); } count++; } //1-6-21: getting an error on my machine when going from COM1 to COM4(they are currently 2 different devices) &amp; it's clearly being caused by recreating the thread(and therefore the USB connection) ReInitThread(); } void CSysLat_SoftwareDlg::OnTargetWindowChanged(UINT nID) { int nButton = nID - ID_RTSSAPP_START; ASSERT(nButton &gt;= 0 &amp;&amp; nButton &lt; 100); CMenu* MainMenu = GetMenu(); int count = 0; for (auto const&amp; [pid, pName] : CRTSSClient::m_vszAppArr) { if (count == nButton) { MainMenu-&gt;CheckMenuItem(nID, MF_CHECKED); char menuCString[256]; MainMenu-&gt;GetMenuString(nID, (LPSTR)menuCString, 256, (UINT)MF_BYCOMMAND); string menuString = menuCString; size_t pos = menuString.rfind(&quot; &quot;); menuString.replace(pos, menuString.size(), &quot;&quot;); SysLatOpt.m_targetApp = menuString; } else { MainMenu-&gt;CheckMenuItem(count + 1100, MF_UNCHECKED); } count++; } } void CSysLat_SoftwareDlg::DebugMode() { CMenu* settingsMenu = GetMenu(); if (m_bDebugMode) { settingsMenu-&gt;CheckMenuItem(ID_SETTINGS_DEBUGMODE, MF_UNCHECKED); m_bDebugMode = false; } else { settingsMenu-&gt;CheckMenuItem(ID_SETTINGS_DEBUGMODE, MF_CHECKED); m_bDebugMode = true; } } void CSysLat_SoftwareDlg::TestUploadMode() { CMenu* settingsMenu = GetMenu(); if (m_bTestUploadMode) { settingsMenu-&gt;CheckMenuItem(ID_SETTINGS_TESTUPLOADMODE, MF_UNCHECKED); m_bTestUploadMode = false; } else { settingsMenu-&gt;CheckMenuItem(ID_SETTINGS_TESTUPLOADMODE, MF_CHECKED); m_bTestUploadMode = true; } } void CSysLat_SoftwareDlg::DisplaySysLatInOSD() { //this needs to default to &quot;on&quot; if you have a version with no LCD on &quot;off&quot; if your SysLat does have an LCD CMenu* settingsMenu = GetMenu(); if (m_bSysLatInOSD) { settingsMenu-&gt;CheckMenuItem(ID_SETTINGS_DISPLAYSYSLATINOSD, MF_UNCHECKED); m_bSysLatInOSD = false; } else { settingsMenu-&gt;CheckMenuItem(ID_SETTINGS_DISPLAYSYSLATINOSD, MF_CHECKED); m_bSysLatInOSD = true; } } void CSysLat_SoftwareDlg::OpenPreferences() { PreferencesDlg preferencesDlg(&amp;SLPref); preferencesDlg.DoModal(); //this should probably be set somewhere else... if (PrivacyOpt.m_bRunOnStartup) { SetSURegValue(pathToSysLat); } else { SetSURegValue(&quot;&quot;); } } void CSysLat_SoftwareDlg::OpenTestCtrl() { TestCtrl testCtrl(&amp;m_vpPreviousSLD); testCtrl.DoModal(); } /* //init some settings to global(?) profile - probably- scratch that, DEFINITELY need to move these //SetProfileProperty(&quot;&quot;, &quot;BaseColor&quot;, 0xFFFFFF); //SetProfileProperty(&quot;&quot;, &quot;BgndColor&quot;, 0x000000); //this value isn't actually modifiable in RTSS lol //SetProfileProperty(&quot;&quot;, &quot;FillColor&quot;, 0x000000); //SetProfileProperty(&quot;&quot;, &quot;ZoomRatio&quot;, 2); //SetProfileProperty(&quot;&quot;, &quot;RefreshPeriod&quot;, 0); //found this property by looking at the plaintext of the RTSSHooks.dll. Doesn't appear to change the value. Also attempted to use the &quot;Inc&quot; function as well, but it also failed. //SetProfileProperty(&quot;&quot;, &quot;RefreshPeriodMin&quot;, 0); //found this property by looking at the plaintext of the RTSSHooks.dll ... It didn't appear to change the value in RTSS... I hope I didn't break something lol //SetProfileProperty(&quot;&quot;, &quot;CoordinateSpace&quot;, 1); //IDK what these do, but I thought they would //SetProfileProperty(&quot;&quot;, &quot;CoordinateSpace&quot;, 0); //DWORD coordinateSpace = CRTSSClient::GetProfileProperty(&quot;&quot;, &quot;CoordinateSpace&quot;); //CGroupedString strOSDBuilder(dwMaxTextSize - 1); //I have no freaking clue what this CGroupedString class does, so I'm kind of scared to get rid of it. //m_SysLatStatsClient.GetOSDText(strOSDBuilder, bFormatTagsSupported, bObjTagsSupported); // get OSD text */ HBRUSH CSysLat_SoftwareDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { pDC-&gt;SetTextColor(RGB(255, 0, 0)); return m_brush; } //This is a duplicate function that was only used for testing, but I think it needs to be moved here so I left it for now... void CSysLat_SoftwareDlg::CheckUpdate() { const char* APItarget = &quot;/api/updateSysLat&quot;; Json::Value versionNumber; versionNumber[&quot;version&quot;] = VER_PRODUCT_VERSION_STR; versionNumber[&quot;versionMajor&quot;] = VERSION_MAJOR; versionNumber[&quot;versionMinor&quot;] = VERSION_MINOR; DEBUG_PRINT(VER_PRODUCT_VERSION_STR) boost::beast::http::response&lt;boost::beast::http::string_body&gt; uploadStatus; if (m_bTestUploadMode) { uploadStatus = upload_data(versionNumber, APItarget); } else { uploadStatus = upload_data_secure(versionNumber, APItarget); } DEBUG_PRINT(&quot;uploadStatus.body(): &quot; + uploadStatus.body()) int userUpdateChoice = 0; if (uploadStatus.result_int() == 302) { userUpdateChoice = ::MessageBox(NULL, &quot;Click ok to download the newest version of SysLat or cancel to continue&quot;, &quot;Update Available&quot;, MB_OKCANCEL); } if (userUpdateChoice == 1) { string newFilePath = pathToSysLat; SL::RemoveFileNameFromPath(newFilePath); newFilePath += &quot;\SysLat.exe&quot;; URLDownloadToFile(NULL, uploadStatus.body().c_str(), newFilePath.c_str(), 0, NULL); //if download completed properly... ::MessageBox(NULL, (&quot;Download complete. Please close this window and start the new version of SysLat at: &quot; + newFilePath).c_str(), &quot;Update Complete&quot;, MB_OK); //else { //download failed //} } } // if option is no, check to see if it exists and delete it if it does(probably can't use &quot;RegOpenKeyEx&quot; for this) // if option is yes open and/or create the key //if it already exists, delete its value? or delete the entire thing itself? //then (re)create it void CSysLat_SoftwareDlg::SetSURegValue(string regValue) { string regSubKey(&quot;SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\&quot;);//SysLat string regValueName = &quot;SysLat&quot;; DEBUG_PRINT(regValue) try { size_t bufferSize = 0xFFF; // If too small, will be resized down below. auto cbData = static_cast&lt;DWORD&gt;(regValue.size() * sizeof(char) + sizeof(char));//leaving off &quot;bufferSize * sizeof(char)&quot; caused Windows defender to think SysLat was a trojan... Maybe? IDK, the problem just went away all of a sudden. HKEY hKey; DWORD position; auto rc = RegCreateKeyEx(HKEY_CURRENT_USER, regSubKey.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &amp;hKey, &amp;position); if ((position == REG_OPENED_EXISTING_KEY || position == REG_CREATED_NEW_KEY) &amp;&amp; rc == ERROR_SUCCESS) { if (position == REG_OPENED_EXISTING_KEY) { DEBUG_PRINT(&quot;Key already exists &amp; has been opened.&quot;) } else if (position == REG_CREATED_NEW_KEY) { DEBUG_PRINT(&quot;Created new key.&quot;) } auto rc = RegSetValueEx(hKey, regValueName.c_str(), 0, REG_SZ, (BYTE*)regValue.data(), cbData); if (rc != ERROR_SUCCESS){ throw std::runtime_error(&quot;Windows system error code: &quot; + to_string(rc)); } } else if(rc != ERROR_SUCCESS){ DEBUG_PRINT(&quot;Error setting key.\n&quot;) } else { DEBUG_PRINT(&quot;UNKNOWN ERROR: Key does not exist, and a new key was not created.&quot;) } } catch (std::exception&amp; e) { DEBUG_PRINT(e.what()) } } //DEBUG_PRINT(&quot;BYTE*: &quot; + to_string(sizeof(BYTE*))); //DEBUG_PRINT(&quot;BYTE: &quot; + to_string(sizeof(BYTE))); //DEBUG_PRINT(&quot;char*: &quot; + to_string(sizeof(char*))); //DEBUG_PRINT(&quot;char: &quot; + to_string(sizeof(char))); //ASSERT(sizeof(BYTE*) == sizeof(char)); //I never used this function, but it seemed like it could be really nice in the future... //inline std::wstring convert(const std::string&amp; as) //{ // wchar_t* buf = new wchar_t[as.size() * 2 + 2]; // swprintf(buf, L&quot;%S&quot;, as.c_str()); // std::wstring rval = buf; // delete[] buf; // return rval; //} </code></pre> <p>Full files if interested:<br /> <a href="https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.h" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.h</a> <a href="https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.cpp" rel="nofollow noreferrer">https://github.com/Skewjo/SysLat_Software/blob/master/SysLat_SoftwareDlg.cpp</a></p>
[]
[ { "body": "<h1>General Observations</h1>\n<p>This section is about the program as a whole and not the specific files you mentioned in the question.</p>\n<p>You are using publicly available libraries rather than writing all of the solution yourself, this is very good.</p>\n<p>You are using GitHub for source control and that is also very good. Since you are using GitHub for source control you should remove all commented out code since you can go back to earlier versions of the code using git. Commented out code generally indicates that the code is not production ready and also not ready for code review.</p>\n<p>This answer also applies to your 3 other questions <a href=\"https://codereview.stackexchange.com/questions/256046/turning-a-data-class-with-too-much-functionality-into-a-pod-syslat-cleanup-1\">SysLat Cleanup #1</a>, <a href=\"https://codereview.stackexchange.com/questions/256063/turning-a-data-class-with-too-much-functionality-into-a-pod-syslat-cleanup-2\">SysLat Cleanup #2</a> and <a href=\"https://codereview.stackexchange.com/questions/256149/cleaning-up-usb-implementation-use-syslat-cleanup-3\">SysLat Cleanup #3</a>.</p>\n<h2>SOLID Object Oriented Programming</h2>\n<p>I would suggestion that you learn about <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID Object Oriented Programming</a>, especially the Single Responsibility Principle. Most of the classes and class methods in the program are too complex (do too much). This makes the program and each of the classes in the program harder to read, write, debug, and maintain. A well designed class or method does only one thing but does it well. Well designed classes or methods can be used as building blocks for more complex classes and allow reuse in other programs or solutions.</p>\n<p>SOLID is 5 object oriented design principles. <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better.</p>\n<ol>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">Open–closed Principle</a> - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov Substitution Principle</a> - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"nofollow noreferrer\">Interface segregation principle</a> - states that no client should be forced to depend on methods it does not use.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">Dependency Inversion Principle</a> - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details.</li>\n</ol>\n<h2>Use Design Patterns</h2>\n<p>The 2 design patterns that would be of the most use to this program are the <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">MVC (Model View Controller)</a> design pattern and the <a href=\"https://en.wikipedia.org/wiki/Composite_pattern\" rel=\"nofollow noreferrer\">Composite Design Pattern</a>.</p>\n<blockquote>\n<p>Model–view–controller (usually known as MVC) is a software design pattern commonly used for developing user interfaces &gt; that divides the related program logic into three interconnected elements. This is done to separate internal\nrepresentations of information from the ways information is presented to and accepted from the user.</p>\n</blockquote>\n<p>Among other things, using the MVC design pattern will allow you to have portable code for the <code>model</code> portion and hopefully the <code>controller</code> portion of your software so if you want to port the program to other systems besides Windows you can with less work.</p>\n<p>The Composite Design Pattern allows you to create a hierarchy of classes within a class building very complex objects from very simple objects that do only one thing. It also reduces the complexity of inheritance. While C++ allows for inheritance from multiple classes, many programming languages do not and composition is a way around that.</p>\n<h2>Use Released Libraries</h2>\n<p>Rather than use the boost::beast library from GitHub, use the entire boost library from boost.org which contains both the beast library and the <code>asio</code> libraries. This will ensure that the library is debugged to the best of the developers ability and it will be stable. The link from your README.md is pointing to the development branch of the <code>beast</code> library rather than the master version which means your are using unproven/undebugged code. That may have caused some of your issues in development.</p>\n<h2>Use Portable Variable Types</h2>\n<p>In some of the program that interacts with low level Microsoft libraries you are using Microsoft specific variable types such as <code>DWORD</code>. This will make the program harder to port to other platforms. Instead I recommend finding the definition of those types in the header files and using the base definition instead (for <code>DWORD</code> it is unsigned long). Another Microsoft type I see in use is <code>BOOL</code>, C++ has the type <code>bool</code> instead, the Microsoft type was necessary for the C programming language before the <code>stdbool.h</code> header was introduced. In some cases when you port the software you will need to have code in #ifdef Win32 for the Windows version and #else for Linux.</p>\n<p>The later versions of C++ (C++17 and C++20) have portable code for dealing with the <a href=\"https://en.cppreference.com/w/cpp/filesystem\" rel=\"nofollow noreferrer\">file system</a>, it would be better to use the C++ libraries because the code is portable.</p>\n<h2>More Portability Issues</h2>\n<p>The code uses a Microsoft defined macro, <code>MAX_PATH</code> to creat arrays of char, I would suggest creating your own constants instead and use <code>const</code> or <code>constexpr</code> to declare them rather than using macros. <code>#define</code> macros should generally be avoided in C++, they don't provide type checking, where C++ <code>const</code> and <code>constexpr</code> do.</p>\n<h2>Headers</h2>\n<p>Rather than including all the standard headers in <code>StdAfx.h</code> only include them where you need them. By including them in <code>StdAfx.h</code> you are making <code>StdAfx.h</code> huge, which makes every one of the <code>.cpp</code> files that includes it huge. For maintenance reasons it is also better to include the headers in the <code>.cpp</code> file so that whoever is maintaining the code can find it easily (If this program does well then you may have to hire employees to maintain the code).</p>\n<p>Rather than putting the following code into <code>StdAfx.h</code>:</p>\n<pre><code>using std::string;\nusing std::vector;\nusing std::map;\nusing std::string_view;\nusing std::to_string;\n</code></pre>\n<p>it would be better to just put <code>std::?????</code> into the code. Putting <code>using std::string;</code> into <code>StdAfx.h</code> may break other string implementations (the boost library is sometimes used to develop features that are later added to the C++ standard). If you do want to shorten <code>std::string</code> to <code>string</code> then do it on a file by file basis so someone that needs to maintain the code knows where it came from.</p>\n<p>You may also want to define your own <code>map</code> or <code>string_view</code> at some point and may run into name collisions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T14:23:00.977", "Id": "505805", "Score": "0", "body": "Thank you for this @pacmaninbw! I think my lack of following the SOLID method has made templating much more difficult to learn/implement. I'll study all of this and get back to you in a couple of weeks to let you know how it went." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T15:12:23.270", "Id": "505809", "Score": "1", "body": "@Skewjo I think it rather important that you switch to the released versions of the libraries as well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:47:26.567", "Id": "256215", "ParentId": "256151", "Score": "2" } } ]
{ "AcceptedAnswerId": "256215", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T15:26:15.590", "Id": "256151", "Score": "2", "Tags": [ "c++", "windows", "embedded" ], "Title": "Dialog that controls external USB device that tests the latency of gaming computers - SysLat Cleanup #4" }
256151
<p>A Few years back I used to opt the below method to run the shell program in a Parallel way to open multiple ssh session at a time to get a quick result.</p> <p>I know there are various other good utilities available, however due to some pressing needs I've to use this way, this dirty piece of code works well however I would like to know if there are some suggestion to improve it further considering the fact I have to use it for some compelling reasons over other better tools.</p> <pre><code>#!/bin/bash echo &quot;$(date) Starting the SSH Connection Check....&quot; #set -x read -rsp $'Please Enter password below: ' SSHPASS export SSHPASS SSH_Connection () { hostTarget=${1} sshpass -e ssh -q &quot;${hostTarget}&quot; &quot;true&quot; -o StrictHostKeyChecking=no -o ConnectTimeout=60 2&gt;&gt;/dev/null if [[ $? -eq 0 ]] then echo &quot;$CurrntTime $MachineName : SSH connection is Up&quot; elif [[ $? -eq 255 ]] then echo &quot;$CurrntTime $MachineName : SSH Authentication Failed&quot; elif [[ $? -eq 2 ]] then echo &quot;$CurrntTime $MachineName : SSH connection is Down&quot; elif [[ $? -eq 1 ]] then echo &quot;$CurrntTime $MachineName : SSH Authentication Failed&quot; else echo &quot;$CurrntTime $MachineName : SSH connection is Down&quot; fi } HostList=$(&lt;~/host2) CurrntTime=$(date +'%m/%d/%Y %T') for MachineName in ${HostList} do SSH_Connection &quot;${MachineName}&quot; &amp; done # wait for all outstanding background jobs to complete before continuing wait # at last clear the exported variable containing the password unset SSHPASS </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T21:28:03.233", "Id": "505612", "Score": "0", "body": "Do you have compelling reasons for not using ssh keys? https://www.digitalocean.com/community/tutorials/how-to-configure-ssh-key-based-authentication-on-a-linux-server" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T04:23:01.467", "Id": "505628", "Score": "0", "body": "Yes.. I can not supply keys even. I know about ssh keys and another methods as well even about pssh but as i mentioned, its not always where we have liberty to choose our freedom over companies policies for any reasons." } ]
[ { "body": "<p>The only part I would change are the chained <code>if</code> statements. Use <code>case</code>:</p>\n<pre><code>CurrntTime=&quot;some_timestamp&quot;\nMachineName=&quot;some_host&quot;\nfor retval in 0 255 2 1 8; do\n echo &quot;Testing exitcode ${retval}&quot;\n case ${retval} in\n 0)\n echo &quot;$CurrntTime $MachineName : SSH connection is Up&quot;;;\n 255)\n echo &quot;$CurrntTime $MachineName : SSH Authentication Failed&quot;;;\n 2)\n echo &quot;$CurrntTime $MachineName : SSH connection is Down&quot;;;\n 1)\n echo &quot;$CurrntTime $MachineName : SSH Authentication Failed&quot;;;\n *)\n echo &quot;$CurrntTime $MachineName : SSH connection is Down&quot;;;\n esac\ndone\n</code></pre>\n<p>More optimisation is not needed. The alternative beneath is slightly shorter but makes the code harder to read (more fun, though):</p>\n<pre><code>CurrntTime=&quot;some_timestamp&quot;\nMachineName=&quot;some_host&quot;\n\nssh_err_0=&quot;connection is Up&quot;\nssh_err_1=&quot;Authentication Failed&quot;\nssh_err_2=&quot;connection is Down&quot;\nssh_err_255=&quot;Authentication Failed&quot;\nssh_err_other=&quot;connection is Down&quot;\n\nfor retval in 0 255 2 1 8; do\n echo &quot;Testing exitcode ${retval}&quot;\n printf &quot;%s&quot; &quot;$CurrntTime $MachineName : SSH &quot;\n case ${retval} in\n 0|1|2|255)\n message=&quot;ssh_err_${retval}&quot;\n echo &quot;${!message}&quot;;;\n *)\n echo &quot;${ssh_err_other}&quot;;;\n esac\ndone\n</code></pre>\n<p>When you use the first <code>case</code> in the total script, and move the <code>SSH_Connection()</code> function to the start of the script, it would be</p>\n<pre><code>#!/bin/bash\n\nSSH_Connection () {\n hostTarget=${1}\n sshpass -e ssh -q &quot;${hostTarget}&quot; &quot;true&quot; -o StrictHostKeyChecking=no \\\n -o ConnectTimeout=60 2&gt;/dev/null\n\n case $? in\n 0)\n echo &quot;$CurrntTime $hostTarget: SSH connection is Up&quot;;;\n 255)\n echo &quot;$CurrntTime $hostTarget: SSH Authentication Failed&quot;;;\n 2)\n echo &quot;$CurrntTime $hostTarget: SSH connection is Down&quot;;;\n 1)\n echo &quot;$CurrntTime $hostTarget: SSH Authentication Failed&quot;;;\n *)\n echo &quot;$CurrntTime $hostTarget: SSH connection is Down&quot;;;\n esac\n}\n\necho &quot;$(date) Starting the SSH Connection Check....&quot;\n\nread -rsp $'Please Enter password below: ' SSHPASS\nexport SSHPASS\n\nHostList=$(&lt;~/host2)\n\nCurrntTime=$(date +'%m/%d/%Y %T')\n\nfor MachineName in ${HostList}; do\n SSH_Connection &quot;${MachineName}&quot; &amp;\ndone\n# wait for all outstanding background jobs to complete before continuing\nwait\n# at last clear the exported variable containing the password\nunset SSHPASS\n</code></pre>\n<p>I did not move the <code>CurrentTime=$(..)</code> inside the function. When you want to see the date/time after the <code>ssh</code> is finished, then you will need to store the exit code in a variable:</p>\n<pre><code>...\nsshpass -e ssh ...\nretval=$?\nCurrentTime=$(date +'%m/%d/%Y %T')\ncase ${retval} in ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T17:48:31.633", "Id": "508765", "Score": "0", "body": "Thanks Walter, How the complete code would look like then, can your formulate the code with you adjustment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-14T19:39:18.677", "Id": "511958", "Score": "0", "body": "Is the code clear for you?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T11:10:37.783", "Id": "257566", "ParentId": "256155", "Score": "2" } } ]
{ "AcceptedAnswerId": "257566", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T18:06:56.330", "Id": "256155", "Score": "0", "Tags": [ "bash", "shell" ], "Title": "Dirty Bash hack to run the ssh connections in the Parallel mode" }
256155
<p>I'm currently working on an uncrafting tool for minecraft and got a neat output working that shows all the materials needed in a tree. I wonder if the code used to print that tree could be improved somehow. I only have the recursion depth as a measurement and the <code>ArrayList</code> gets filled in the same order as seen in the input example below. The output format should also stay the same, I'm quite happy with that. The input format is a bit sketchy though, any ideas on that are appreciated as well.</p> <h3>The Algorithm</h3> <pre><code> private static void treeprint(ArrayList&lt;Object[]&gt; tree) { ArrayList&lt;String&gt; stem = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; tree.size() - 1; i++) { System.out.print(String.join(&quot;&quot;, stem)); Object[] o = tree.get(i); int cdepth = (int) o[0]; String cname = (String) o[1]; int camt = (int) o[2]; int ndepth = (int) tree.get(i + 1)[0]; if (ndepth &gt; cdepth) { if (isLastOfDepth(tree, cdepth, i + 1)) { System.out.print(&quot;\\---&quot;); stem.add(&quot; &quot;); } else { System.out.print(&quot;+---&quot;); stem.add(&quot;| &quot;); } } if (ndepth == cdepth) { if (isLastOfDepth(tree, cdepth, i + 1)) { System.out.print(&quot;\\---&quot;); } else { System.out.print(&quot;+---&quot;); } } if (ndepth &lt; cdepth) { System.out.print(&quot;\\---&quot;); for (int j = 0; j &lt; cdepth - ndepth; j++) { stem.remove(stem.size() - 1); } } System.out.println(cname + &quot; x &quot; + camt); } System.out.println(String.join(&quot;&quot;, stem) + &quot;\\---&quot; + (String) tree.get(tree.size() - 1)[1] + &quot; x &quot; + (int) tree.get(tree.size() - 1)[2]); } private static boolean isLastOfDepth(ArrayList&lt;Object[]&gt; tree, int depth, int start) { for (int i = start; i &lt; tree.size(); i++) { int cdepth = (int) tree.get(i)[0]; if (cdepth &lt; depth) { return true; } if (cdepth == depth) { return false; } } return true; } </code></pre> <h3>Test Input</h3> <p>Format is recuresion depth / item name / item amount</p> <pre><code>1 component heat vent 1 2 iron bars 4 3 iron 6 2 heat vent 1 3 electric motor 1 4 coil 2 5 copper cable 8 5 iron 1 4 iron 1 4 tin item casing 2 3 iron bars 4 4 iron 6 3 iron plate 4 2 tin plate 4 </code></pre>
[]
[ { "body": "<p>Nice solution, my suggestions:</p>\n<ul>\n<li><p><strong>Short variable names</strong>: variables like <code>camt</code> and <code>cname</code> can be extended to <code>currentAmount</code> and <code>currentName</code>. It's better to have longer names to improve readability. For example, I am not sure what <code>stem</code> stands for.</p>\n</li>\n<li><p><strong>Types and input validation</strong>: there are a lot of casting in the methods which are not validated. Accepting an array of <code>Object</code> without any validation is a recipe for troubles. Using a class you can solve both problems, something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class Node{\n private int depth;\n private String itemName;\n private int amount;\n public Node(int depth, String itemName, int amount) {\n // Input validation here\n this.depth = depth;\n this.itemName = itemName;\n this.amount = amount;\n }\n // Getters, etc.\n}\n</code></pre>\n<p>So this code:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Object[] o = tree.get(i);\nint cdepth = (int) o[0];\nString cname = (String) o[1];\nint camt = (int) o[2];\n</code></pre>\n<p>Can become:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Node node = tree.get(i);\nint currentDepth = node.getDepth();\nString currentItemName = node.getItemName();\nint currentAmount = node.getAmount();\n</code></pre>\n<p>You can also make the properties of the class <code>final</code> to have an immutable node.</p>\n</li>\n<li><p><strong>Constants</strong>: the strings <code>\\---</code> and <code>+---</code> are repeated multiple times. Consider creating constants for such special strings so that they will be easier to change in the future.</p>\n</li>\n<li><p><strong>Functionality</strong>: If the list is not properly built, the tree will not be printed correctly. For example:\nThe input:</p>\n<pre><code>1 a 1\n2 b 1\n3 c 1\n4 d 1\n</code></pre>\n<p>Produces the correct output:</p>\n<pre><code>\\---a x 1\n \\---b x 1\n \\---c x 1\n \\---d x 1\n</code></pre>\n<p>But if we add one more node in the middle:</p>\n<pre><code>1 a 1\n2 b 1\n3 c 1\n2 e 1\n4 d 1\n</code></pre>\n<p>The output becomes:</p>\n<pre><code>\\---a x 1\n +---b x 1\n | \\---c x 1\n \\---e x 1\n \\---d x 1\n</code></pre>\n<p>Now <code>d</code> changed its depth from <code>4</code> to <code>3</code> and <code>e</code> became its father.</p>\n<p>Providing a well-formed list of nodes with corresponding depth is not a simple task if the tree grows in size. A solution might be to create a <code>Tree</code> class that knows how to add and remove nodes. Then the <code>treePrint</code> method will do a <a href=\"https://en.wikipedia.org/wiki/Tree_traversal#Pre-order\" rel=\"nofollow noreferrer\">Pre-order</a> scan of the tree and print the nodes on the way.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T14:24:10.403", "Id": "505667", "Score": "1", "body": "Thanks! Var names and constants do need a refactoring. \nAs for the `Object[]`: The entries are either internal counters or validated elsewhere. Still a valid point, perhaps a class would still be better for readability.\nAs for functionality, this is a bug but one that shouldn't occur. The `ArrayList` is generated in order as the tree of recipe dependencies is explored depth-first via recursion. This way, the `cdepth` can only grow by 1 (but shrink to any number >0)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T06:41:44.347", "Id": "256175", "ParentId": "256159", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T21:27:04.653", "Id": "256159", "Score": "2", "Tags": [ "java", "tree" ], "Title": "Pretty print a tree from minimal data input" }
256159
<p>I'm not very experienced with OOP and Python and I've been wanting to kind of professionalize my way of writing code, etc. My question is; in what departments can I improve?</p> <p>Main.py (how I interact with the other files/classes)</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime, timedelta import coins import plot end_date = datetime.today().timestamp() start_date = (datetime.today() - timedelta(days=365)).timestamp() coin = coins.CoinClient('cardano') resp = coin.get_between(start_date, end_date) raw = coins.RawResponse(resp) parse = coins.ParseClear(raw.beautify_between()) response = plot.sanitize_response(parse.parse_days(30), &quot;prices&quot;, False) plotarr = plot.PlotArray(response['x_axis'], response['y_axis']) plotarr.line_graph_price(&quot;Cardano&quot;, False) </code></pre> <p>Coins.py</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime from pycoingecko import CoinGeckoAPI import config def raise_type_error(message): # Raises a type error raise TypeError(message) class CoinClient: # Response object keys (per coin) # prices # market_caps # total_volumes def __init__(self, ticker): self.ticker = ticker self.cg = CoinGeckoAPI() self.response_dict = dict() # Gets raw data between start and end date (UNIX time format) def get_between(self, start_date: float, end_date: float): # Returns one CoinGecko response object for coin specified if isinstance(self.ticker, str): return False, self.cg.get_coin_market_chart_range_by_id(self.ticker, config.currency, start_date, end_date) # Returns a dict of CoinGecko response objects for coins specified elif isinstance(self.ticker, list): for c in self.ticker: self.response_dict[c] = self.cg.get_coin_market_chart_range_by_id(c, config.currency, start_date, end_date) return True, self.response_dict # Raise TypeError is self.ticker isn't a string or list. else: raise_type_error( &quot;Ticker must either be a string or list of strings.&quot;) class RawResponse: # Turns CoinClient response object into readable (UNIX -&gt; DATETIME) def __init__(self, data): self.data = data self.response_dict = dict() def __iterate(self, ls): # Iterate over the array with values [unix, value] arr = list() for i in ls: # Return an array in the same format as the original object. arr.append([datetime.fromtimestamp(i[0] / 1000).date(), i[1]]) return arr def beautify_between(self): l, data = self.data[0], self.data[1] if isinstance(data, dict): # Check if data is a list or not, if yes it iterates over the names of the coins if l: self.response_dict['multiple'] = True for c in data: self.response_dict[c] = {} for k in data[c]: # Update dict_key[coin] with k(price, total_volumes, market_caps) with [[datetime, value], etc.] self.response_dict[c].update( {k: self.__iterate(data[c][k])}) else: self.response_dict['multiple'] = False for k in data: # Update k(price, total_volumes, market_caps) with [[datetime, value], etc.] self.response_dict.update({k: self.__iterate(data[k])}) else: # Raise type error, data is not a dict. raise_type_error(&quot;Data must either be of type dict&quot;) # Return response dict return self.response_dict class ParseClear: # Reformat clear/parsed data from RawResponse def __init__(self, data: dict): self.data = data # Interval = amount of days to skip (7 to get weekly data, 30 to get monthly, etc.) def parse_days(self, interval: int): is_multiple = self.data['multiple'] del self.data['multiple'] if is_multiple: for c in self.data: for k in self.data[c]: self.data[c][k] = self.data[c][k][::interval] else: for k in self.data: self.data[k] = self.data[k][::interval] return self.data </code></pre> <p>plot.py (not yet finished)</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import seaborn as sns sns.set() def sanitize_response(obj, key, multiple: bool): # Get an X and Y axis for the key (prices, total_volumes, market_caps) for coins. # Multiple flag is used to see if there's multiple coins given # Creating response dictionary and x and y list response = dict() x = list() y = list() if multiple: for c in obj: response[c] = {} for arr in obj[c][key]: x.append(arr[0]) y.append(arr[1]) response[c][&quot;x_axis&quot;] = x response[c][&quot;y_axis&quot;] = y else: for arr in obj[key]: x.append(arr[0]) y.append(arr[1]) response[&quot;x_axis&quot;] = x response[&quot;y_axis&quot;] = y return response class PlotArray: # Plot a graph from an array/list (x and y axis are lists) def __init__(self, x: list, y: list): self.x_axis = x self.y_axis = y def line_graph_price(self, coin: str, multiple: bool): # Plot a line graph for the price overtime if multiple: pass else: plt.plot(self.x_axis, self.y_axis) plt.xlabel('Timeframe (YYYY-MM)') plt.ylabel(f'{coin} price') plt.title(f'Coin price graph') plt.legend([coin]) plt.show() </code></pre> <p>config.py</p> <pre class="lang-py prettyprint-override"><code>currency = &quot;usd&quot; </code></pre> <p>This is my first real attempt at programming in an object oriented manner, so even general information is much appreciated.</p> <p><strong>Edit</strong></p> <p>As was suggested, here is a basic overview of what the program does;</p> <ol> <li>Gets data from CoinGecko API from selected coin(s)</li> <li>Turns CoinGecko API object to readable format (UNIX timestamps -&gt; Datetime)</li> <li>Parses data from the CoinGecko API that a user want (<code>prices</code>, <code>total_volumes</code>, <code>market_caps</code>)</li> <li>The CoinGecko API sends daily data over the time period you specified (365 records for one year). Program then gets data with an interval a user sets (30 days = 1 month) so you don't have data of every day but every <code>n</code> days.</li> <li>Graphs the data (doesn't yet work for multiple coins and it's a pretty ugly graph, just learning stuff about visualizing data)</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T23:16:07.053", "Id": "505619", "Score": "0", "body": "Welcome to Code Review! I can see that the code has something to do with coins and responses. 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](https://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](https://meta.codereview.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T23:36:42.087", "Id": "505620", "Score": "1", "body": "Thanks for your comment! I've changed the post!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T22:54:07.213", "Id": "256162", "Score": "1", "Tags": [ "python" ], "Title": "Turning CoinGecko API response to then plot graphs with the data | Python" }
256162
<p><strong>Application context</strong></p> <p>I am working on a game I call &quot;Apes and Snakes&quot;. So far the code only allows players to connect to a host using a room code and WebRTC. Players and the host send messages back and forth to each other over WebRTC. When a player receives a message, it is passed to a &quot;handler&quot;. This kind of pattern is somewhat comparable to the way an HTTP request to a certain route gets passed on to a method of a controller in an MVC architecture.</p> <p><em>The full repository can be found at <a href="https://github.com/colesam/apes-and-snakes" rel="nofollow noreferrer">https://github.com/colesam/apes-and-snakes</a>, but I will be posting the relevant code snippets below.</em> It's a react application but the portion I'm dealing with for this post mainly has to do regular javascript/typescript logic and jest, as well as reading/writing from a zustand (simplified redux) flux storage.</p> <p><strong>What I want reviewed</strong></p> <p>The code I want reviewed is the &quot;handler&quot; for when the host receives a reconnect message. Specifically I would like my strategy for testing this function reviewed.</p> <p>The function I am testing is called <code>handleReconnect</code>. What this function does in short is allow players to reconnect to the game from a new peerId if they still have their old secret key (what I use to auth/link a player to their data). My original implementation of the method looks like this:</p> <pre class="lang-js prettyprint-override"><code>import { TActionHandlerProps } from &quot;../handleAction&quot;; import GeneralError from &quot;../../error/GeneralError&quot;; import { getPrivate } from &quot;../../store/privateStore&quot;; import { StoreAction } from &quot;../../store/StoreAction&quot;; const handleReconnect = ({ peerId, payload, respond, error, }: TActionHandlerProps) =&gt; { // SIDE EFFECT 1: Pull secret key map from flux storage const { secretKeyPlayerIdMap } = getPrivate(); const playerId = secretKeyPlayerIdMap.get(payload.secretKey); if (!playerId) { return error( new GeneralError(&quot;Could not find playerId. Failed to reconnect.&quot;) ); } // SIDE EFFECT 2: Update the peerId of the player in flux storage StoreAction.setPlayerConnection(playerId, { peerId }); return respond(); }; export default handleReconnect; </code></pre> <p>This function has two side-effects that make this difficult to test:</p> <ol> <li><p><code>getPrivate</code> is a function that returns the current state of my flux storage.</p> </li> <li><p><code>StoreAction.setPlayerConnection</code> is a function that updates my store. The <code>StoreAction</code> object is really just used as a namespace for functions that mutate the store because a lot of the actions have very general names that collide with other areas of my application.</p> </li> </ol> <p>To get around this, I decided to make a factory function that returns the handler, injecting the necessary side-effects. The default export still exports the function as it exists in the previous code snippet, while exposing a way for me to inject mocks when testing.</p> <p>Here is how I rewrote <code>handleReconnect</code>:</p> <pre class="lang-js prettyprint-override"><code>import { TActionHandlerProps } from &quot;../handleAction&quot;; import GeneralError from &quot;../../error/GeneralError&quot;; import { getPrivate } from &quot;../../store/privateStore&quot;; import { StoreAction } from &quot;../../store/StoreAction&quot;; export const makeHandleReconnect = ( _getPrivate: typeof getPrivate, _StoreAction: typeof StoreAction ) =&gt; ({ peerId, payload, respond, error }: TActionHandlerProps) =&gt; { const { secretKeyPlayerIdMap } = _getPrivate(); const playerId = secretKeyPlayerIdMap.get(payload.secretKey); if (!playerId) { return error( new GeneralError(&quot;Could not find playerId. Failed to reconnect.&quot;) ); } _StoreAction.setPlayerConnection(playerId, { peerId }); return respond(); }; const handleReconnect = makeHandleReconnect(getPrivate, StoreAction); export default handleReconnect; </code></pre> <p>Here is how I tested this rewritten version:</p> <pre class="lang-javascript prettyprint-override"><code>/* eslint-disable */ import { makeHandleReconnect } from &quot;./handleReconnect&quot;; import { Map } from &quot;immutable&quot;; const makeParams = (opts = {}) =&gt; ({ peerId: &quot;123&quot;, payload: { secretKey: &quot;existing-secret&quot; }, respond: jest.fn(), error: jest.fn(), ...opts, }); const makeGetPrivate = (opts = {}) =&gt; () =&gt; ({ secretKeyPlayerIdMap: Map([[&quot;existing-secret&quot;, &quot;player-id&quot;]]), ...opts, }); const makeStoreAction = (opts = {}) =&gt; ({ setPlayerConnection: jest.fn(), ...opts, }); let callHandleReconnect; beforeEach(() =&gt; { callHandleReconnect = ({ params = makeParams(), getPrivate = makeGetPrivate(), StoreAction = makeStoreAction(), }) =&gt; { // noinspection JSCheckFunctionSignatures const handleReconnect = makeHandleReconnect(getPrivate, StoreAction); return handleReconnect(params); }; }); test(&quot;responds if secret key is found&quot;, () =&gt; { const params = makeParams(); callHandleReconnect({ params }); expect(params.respond.mock.calls.length).toBe(1); }); test(&quot;updates player's peer id if secret key is found&quot;, () =&gt; { const params = makeParams(); const StoreAction = makeStoreAction(); callHandleReconnect({ params, StoreAction }); const { mock } = StoreAction.setPlayerConnection; expect(mock.calls.length).toBe(1); const [playerId, { peerId }] = mock.calls[0]; expect(playerId).toBe(&quot;player-id&quot;); expect(peerId).toBe(&quot;123&quot;); }); test(&quot;errors if secret key is not found&quot;, () =&gt; { const params = makeParams({ payload: { secretKey: &quot;missing-secret&quot; }, }); callHandleReconnect({ params }); expect(params.error.mock.calls.length).toBe(1); }); </code></pre> <p>I'm open to any and all feedback on the project as a whole, but specifically I am interested in:</p> <ol> <li>If my strategy makes sense or if it's way off base</li> <li>How it can be improved</li> <li>How my tests can be made more readable/improved</li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-17T22:58:16.580", "Id": "256163", "Score": "2", "Tags": [ "javascript", "unit-testing", "functional-programming", "typescript" ], "Title": "Testing a javascript function that performs side effects" }
256163
<p>I have two dataframes I need to map over and combine into one. The first data frame contains NBA players. The headers are 'Date', 'Player', 'Team', 'Position', 'Salary', 'Pos_ID', 'Minutes', 'FPTS', 'USG'. I then have a second dataframe that's the first dataframe but grouped by date and team. The headers for this df are 'Date', 'Team', 'Minutes', 'FGA', 'FTA', 'To'. I'm trying to calculate USG rate for every player in the first dataframe. To do this I need to know what the total minutes, field goal attempts, free throw attempts, and turnover are for each team in each game for a given date. I then divide the same player's stats by the team's total stats. I have a working solution, but it's really slow and doesn't seem to be the most efficient way of doing this.</p> <p>Here is the code:</p> <pre><code>import pandas as pd player_df = pd.read_csv('Sample Data') # replace with sample data file no_dups = player_df.drop_duplicates() no_dups.loc[:, 'USG'] = pd.Series(dtype=float) no_dups = no_dups[no_dups.Minutes != 0] grouped_teams = no_dups.groupby(['Date', 'Team']).agg({'Minutes':['sum'], 'FGA': ['sum'], 'FTA': ['sum'], 'TO': ['sum'] }) grouped_teams.columns = ['Minutes', 'FGA', 'FTA', 'TO'] grouped_teams = grouped_teams.reset_index() for index, row in no_dups.iterrows(): for i, r in grouped_teams.iterrows(): if no_dups.at[index, 'Team'] == grouped_teams.at[i, 'Team'] and no_dups.at[index, 'Date'] == grouped_teams.at[i, 'Date']: no_dups.at[index, 'USG'] = (100*((no_dups.at[index, 'FGA'] + 0.44 * no_dups.at[index, 'FTA'] + no_dups.at[index, 'TO'])*(grouped_teams.at[i, 'Minutes']/5))) / (no_dups.at[index, 'Minutes']*(grouped_teams.at[i, 'FGA']+0.44*grouped_teams.at[i, 'FTA']+grouped_teams.at[i, 'TO'])) final_df = no_dups[['Date', 'Player', 'Team', 'Position', 'Salary', 'Minutes', 'FPTS', 'USG']] print(final_df) </code></pre> <p>I have removed all players who didn't play and there are duplicates because the same player can play in multiple contests in a single night so I removed those. I then create a df called <code>grouped_teams</code> which is every single team in the df grouped by date and team name. I then iterate over the first df using <code>iterrows</code> and the second df the same way. I need to find each players team and specific date and divide his stats by the calculated total to get the usage rate. The column for that is <code>no_dups.at[index, 'USG']</code>. There are 73k rows in my df so iterating over each one is taking a very long time.</p> <p><a href="https://docs.google.com/spreadsheets/d/1g0ccTbBn8QsElk_9e9wmGQn_KVmONOuQFM7MGLYrajU/edit?usp=sharing" rel="nofollow noreferrer">Sample Data</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T00:06:13.923", "Id": "256165", "Score": "2", "Tags": [ "python" ], "Title": "Optimize mapping over large DF" }
256165
<p>This question is an extension of <a href="https://stackoverflow.com/questions/66249671/how-can-i-limit-stop-the-number-of-characters-fgets-reads">this other question from Stackoverflow</a>.</p> <p>The objective is to limit the input of characters read by fgets to up to a certain number of characters. And in the following code, that I've come up with as a solution, we are working with a limit of 10 characters as an example:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; int main() { char v[12]; printf(&quot;Type a word with up to 10 chracters:\n&quot;); //Loop checks if fgets succeeded and if there is '\n' in the string: while (!fgets(v, 12, stdin) || strcspn(v, &quot;\n&quot;) == 11){ if(feof(stdin)) { printf(&quot;Error: End of file reached.\n&quot;); exit(EXIT_FAILURE); } printf(&quot;Error: The word is longer than 10 characters, try again.\n&quot;); for(int ch=getchar(); ch != '\n' &amp;&amp; ch != EOF; ch=getchar()); printf(&quot;Type a word with up to 10 chracters:\n&quot;); } v[strcspn(v, &quot;\n&quot;)] = '\0'; printf(&quot;%s\n&quot;, v); return 0; } </code></pre> <p>It works as intended. However <a href="https://stackoverflow.com/questions/66249671/how-can-i-limit-stop-the-number-of-characters-fgets-reads#comment117130088_66250051">@chux-ReinstateMonica has pointed out that there may still be corner weaknesses and possible improvements to be made to this solution</a>.</p> <p>So, how can this code/solution be improved?</p>
[]
[ { "body": "<p>This would obviously be better as a function, so we can call with different parameters.</p>\n<p>Instead of repeating the constant <code>12</code> in the <code>fgets()</code> call, we could simply use <code>sizeof v</code>. Then it remains consistent if we change <code>v</code>.</p>\n<p>Instead of <code>strcspn()</code> with only one character, I'd prefer <code>strchr()</code>. Conveniently, that returns a null pointer if not found, so we don't need to calculate the length to search. And we shouldn't repeat the search to replace the newline with null character.</p>\n<p>Error messages should go to <code>stderr</code>, not <code>stdout</code>.</p>\n<p>We can skip the rest of line with a simple <code>scanf(&quot;%*[^\\n]&quot;)</code> (note the <code>*</code> to suppress assignment). That would replace the <code>ch</code> loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T13:57:58.477", "Id": "505663", "Score": "0", "body": "Make a function: Yes. -- Use `sizeof v` instead of `12`: In a function I think the maximum number of characters (10 in the example) would be more important, and it would better to simply assume that the char array is large enough (length of at least the maximum number of character + 2)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T14:04:15.143", "Id": "505664", "Score": "0", "body": "Use `strchr()` instead of `strcspn()`: Good idea. -- Send error messages to `stderr`: Yes. -- Use `scanf(\"%*[^\\n]\")` to clear excess characters: That would leave a `'\\n'` in `stdin` that would be read by `fgets()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T16:11:31.940", "Id": "505683", "Score": "0", "body": "`sizeof v` wouldn't be necessary in a function, as caller should pass buffer and capacity. Yes, we'd need a `getchar()` after that `scanf()` (which we could use to check for `EOF`) - sorry for not being explicit about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T19:21:00.103", "Id": "505706", "Score": "0", "body": "Is there a performance advantage to using `scanf(\"%*[^\\n]\")` instead of the `getchar()` loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T19:41:02.090", "Id": "505707", "Score": "0", "body": "Unlikely - just readability. BTW, it occurs to me that we could simply add `%*c` to the format string to consume the newline - no need to check the return value here, as the subsequent `fgets()` provides all the check we need (but I'd comment why we're ignoring it)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T20:29:33.087", "Id": "505713", "Score": "0", "body": "No, for some reason I've never understood adding `%*c` to make `scanf(\"%*[^\\n]%*c\")` doesn't work, the `\\n` still remains in `stdin` as if there wasn't the `%*c` specifier. And it is necessary to use 2 consecutive scanfs like this `scanf(\"%*[^\\n]\"); scanf(\"%*c\");` to clean everything (so it would be better to use `getchar()` instead of the second scanf)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T23:32:20.667", "Id": "505739", "Score": "1", "body": "\"add `%*c` to the format string to consume the newline\" as with `%*[^\\n]%*c` fails to read a trailing newline if it is the first character." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T02:01:29.713", "Id": "505757", "Score": "0", "body": "@isrnick: To properly detect rare input errors, 2 consecutive `scanf`s and/or `getchar()` should check the result before proceeding to the next." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T02:02:56.183", "Id": "505758", "Score": "0", "body": "`scanf(\"%*[^\\n]\")` does not quite \"skip the rest of line\". It fails to read the `'\\n'` at the end of the line. Also, its return value is important to detect input errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T02:08:12.157", "Id": "505759", "Score": "1", "body": "A nice attribute about `strcspn()` is `v[strcspn(v, \"\\n\\r\")] = '\\0';` to handle text files from foreign systems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T07:53:49.093", "Id": "505776", "Score": "1", "body": "@chux: (1) yes, we need to read the newline as well as the rest of the non-newline characters. I didn't think that needed saying (but earlier comments proved otherwise!). (2) Can you give an example of where a `scanf()`/`getchar()` could fail but not be detected on the next stream operation? (3) I like that `strcspn()` use to handle CRLF so simply." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T16:14:28.160", "Id": "505814", "Score": "1", "body": "TobySpeight Pedantic concern: The rare input error causes `scanf(), getchar()` to return `EOF`. The next input function may/may not return `EOF` - it depends on the nature of the input error. So without checking the first, an input error may lack detection. This is unlike \"end-of-file\", where \"If the end-of-file indicator for the stream is set, **or** if the stream is at end-of-file\". Some [additional thoughts](https://stackoverflow.com/a/32654299/2410359)." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T12:04:54.263", "Id": "256185", "ParentId": "256166", "Score": "4" } }, { "body": "<p>IMO a much simpler solution is to use <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/functions/getdelim.html\" rel=\"nofollow noreferrer\">POSIX <code>getline()</code></a>. And if your platform doesn't provide <code>getline()</code>, there are more than a few open-source implementations available.</p>\n<p>Bare code to illustrate the processing in a smaller number of lines (as in without scroll bars...):</p>\n<pre><code>int main()\n{\n char *line = NULL;\n size_t len = 0;\n for ( ;; )\n {\n printf( &quot;Type a word with up to 10 characters:\\n&quot; );\n ssize_t result = getline( &amp;line, &amp;len, stdin );\n if ( result &lt; 0 )\n {\n exit( EXIT_FAILURE );\n }\n\n line[ strcspn( line, &quot;\\n&quot; ) ] = '\\0';\n if ( strlen( line ) &lt;= 10 )\n {\n break;\n }\n\n printf( &quot;Error: The word is longer than 10 characters, try again.\\n&quot; );\n }\n\n printf( &quot;Your input: %s\\n&quot;, line ); \n return 0;\n}\n</code></pre>\n<p>The use of <code>strcspn()</code> and <code>strlen()</code> could be made more efficient so the line only gets traversed once, but we're dealing with user input here so code clarity overrides almost every performance consideration.</p>\n<p>With full error checking:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nint main()\n{\n char *line = NULL;\n size_t len = 0;\n\n for ( ;; )\n {\n printf( &quot;Type a word with up to 10 characters:\\n&quot; );\n\n ssize_t result = getline( &amp;line, &amp;len, stdin );\n if ( result &lt; 0 )\n {\n if ( feof( stdin ) )\n {\n fprintf( stderr, &quot;EOF reached\\n&quot; );\n }\n else\n {\n perror( &quot;getline(..., stdin)&quot; );\n }\n\n free( line );\n exit( EXIT_FAILURE );\n }\n\n line[ strcspn( line, &quot;\\n&quot; ) ] = '\\0';\n\n if ( strlen( line ) &lt;= 10 )\n {\n break;\n }\n\n printf(&quot;Error: The word is longer than 10 characters, try again.\\n&quot;);\n }\n\n printf( &quot;Your input: %s\\n&quot;, line );\n\n free( line );\n\n return 0;\n}\n</code></pre>\n<p>As a function:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nchar *getLine( unsigned int maxLen )\n{\n char *line = NULL;\n size_t len = 0;\n\n // sanity check passed variable\n if ( 0 == maxLen )\n {\n return( NULL );\n }\n\n for ( ;; )\n {\n printf( &quot;Type a word with up to %u characters:\\n&quot;, maxLen );\n\n ssize_t result = getline( &amp;line, &amp;len, stdin );\n if ( result &lt; 0 )\n {\n if ( feof( stdin ) )\n {\n fprintf( stderr, &quot;EOF reached\\n&quot; );\n }\n else\n {\n perror( &quot;getline(..., stdin)&quot; );\n }\n\n free( line );\n return( NULL );\n }\n\n line[ strcspn( line, &quot;\\n&quot; ) ] = '\\0';\n\n if ( strlen( line ) &lt;= maxLen )\n {\n break;\n }\n\n printf( &quot;Error: The word is longer than %u characters, try again.\\n&quot;,\n maxLen );\n }\n\n printf( &quot;Your input: %s\\n&quot;, line );\n\n return( line );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T16:13:24.940", "Id": "505685", "Score": "1", "body": "I was assuming that the code was posted as an attempt to reimplement `getline()`, but you're right that's not stated, so good answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T19:03:35.763", "Id": "505705", "Score": "0", "body": "What is the `size` used as an argument in the `getline()` function? Please elaborate on why a solution using `getline()` is better in your opinion. And if possible tell me where I can find a reliable open-source implementation of `getline()` that I can use with MinGW and other Windows compilers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T20:21:34.767", "Id": "505710", "Score": "1", "body": "@isrnick *Please elaborate on why a solution using `getline()` is better in your opinion.* Because \"Get complete line, check length\" is a lot simpler and less bug-prone than \"read string, check length, see if it ends with a newline, if it doesn't clear input buffer\"? Count the lines of code - and remember to count `while (!fgets(v, 12, stdin) || strcspn(v, \"\\n\") == 11)` as five or six lines because you've put that many operations there, and `for(int ch=getchar(); ch != '\\n' && ch != EOF; ch=getchar());` counts as five to seven also. Every line of code you write is a chance to create bugs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T20:23:08.750", "Id": "505711", "Score": "0", "body": "(cont) Your code will have been tested a handful of times against a smattering of different input - if you tested it at all... Your system's `getline()` implementation has been tested probably **trillions** of times - if not more - against all kinds of input. Take glibc's implementation, for example. It was developed by an experienced team, formally reviewed by multiple experienced developers, passed through rigorous formal testing, and been open for comment for probably several decades now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T23:35:28.547", "Id": "505740", "Score": "2", "body": "A weakness to `getline( &line, &len, stdin );` is that it allows a nefarious user to overwhelm memory resources with an excessive long line. Defensive programming prevents that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T01:12:59.947", "Id": "505853", "Score": "0", "body": "@chux-ReinstateMonica If that's something you need to protect against, that's what limits are for. Because if overwhelming memory resources is a threat, there are much simpler ways to do that. `tail -f /dev/zero` or `dd bs=1024k if=/dev/zero of=/dev/shm/asdf` come to mind immediately. Nevermind anyone with access to a compiler..." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T14:31:36.427", "Id": "256192", "ParentId": "256166", "Score": "1" } }, { "body": "<p><strong>Does not detect input errors on <code>stdin</code></strong></p>\n<p>When <code>fgets()</code> returns <code>NULL</code> due to an <em>input error</em>, code simply loops when a loop exit is more common. If the input error is permanent, code is stuck in a infinite loop.</p>\n<p><strong>Avoid naked magic numbers</strong></p>\n<p>Rather than 12, 11, etc, use a <code>#define BUF_N 12</code> and code accordingly.</p>\n<pre><code>// while (!fgets(v, 12, stdin) || strcspn(v, &quot;\\n&quot;) == 11){\nwhile (!fgets(v, BUF_N, stdin) || strcspn(v, &quot;\\n&quot;) == BUF_N - 1){\n</code></pre>\n<p><strong>Good use of <code>int</code></strong></p>\n<pre><code>// vvv --- proper type to save the typical 257 different responses from `fgetc()`\nfor(int ch=getchar(); ch != '\\n' &amp;&amp; ch != EOF; ch=getchar());\n</code></pre>\n<p><strong>Spell check</strong></p>\n<p>chracters --&gt; characters</p>\n<hr />\n<p><strong>Sample code</strong></p>\n<p>Following OP's style, as a <em>function</em> returning a flag rather than printing errors:</p>\n<pre><code>// Look for an input &lt;= N-2 non-\\n characters.\n// Return error/EOF flag\nbool OP_readline(char *v, size_t n, const char *re_prompt) {\n char *fgets_retval;\n size_t len = 0;\n while ((fgets_retval = fgets(v, n, stdin)) != NULL &amp;&amp; (len = strcspn(v, &quot;\\n&quot;)) + 1 == n) {\n int ch;\n while ((ch = getchar()) != '\\n' &amp;&amp; ch != EOF) {\n ;\n }\n if (ch == EOF) {\n return true; // Error or EOF;\n }\n if (re_prompt) {\n fputs(re_prompt, stdout);\n fflush(stdout):\n }\n len = 0;\n }\n v[len] = 0;\n return fgets_retval == NULL;\n}\n</code></pre>\n<p><strong>Other improvements</strong></p>\n<ol>\n<li><p>Better code would not need a buffer of +1 size. This allows one to read directly into an array of size <code>N</code> without providing a <code>N+1</code> size array just for the benefit the read function. Detecting long lines is the read function's problem and should not oblige the caller to provide a +1 buffer to solve it.</p>\n</li>\n<li><p><em>Null character</em> input can fool above code a bit, but leave that for another day.</p>\n</li>\n<li><p>Detection/Handling of extreme <code>n</code>. Should be in the range <code>2 &lt;= n &lt;= INT_MAX</code>, or some other well thought out limits.</p>\n</li>\n<li><p>Consider a <code>prompt</code> parameter too.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:51:03.220", "Id": "505755", "Score": "0", "body": "Very important about input errors; should also detect input errors from `getchar`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:54:06.423", "Id": "505756", "Score": "0", "body": "@Neil Agreed. Good to test `ch`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T23:34:22.743", "Id": "505851", "Score": "0", "body": "returning `true` for errors is confusing. Most other functions return `true` on success. `ferror` is a notable exception, of course." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T03:18:51.120", "Id": "505861", "Score": "0", "body": "@RolandIllig Yes, `stream` was a poor choice. Code amended." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:34:48.427", "Id": "256213", "ParentId": "256166", "Score": "3" } }, { "body": "<p>Really nice style; super clear. I'll try not to duplicate existing and really good answers. What I think you intend to do is a kind of state machine looking something like this:</p>\n<p><a href=\"https://i.stack.imgur.com/IMDsv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IMDsv.png\" alt=\"The state machine with fgets and getchar.\" /></a></p>\n<p>The error, in this case, includes <code>stdin</code> EOF before return was pressed. However, you are only checking for EOF and ignoring other errors, as pointed out. I believe that the <code>fgets</code>, <code>getchar</code>, and <code>error</code> states will probably make your code clearer.</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;assert.h&gt;\n#include &lt;errno.h&gt;\n#include &lt;limits.h&gt;\n\n// user-defined errno values; should all be negative to avoid conflicts\nenum { NOT_POSIX_COMPLIANT = -2, EOF_ERROR };\n\n/** Blocks, prompting the user again and again. If true, `v` is full up to\n `v_size`, including &quot;&quot;. If false, `errno` is set to and expanded range. `v`\n must be capable of holding `v_size` bytes. */\nstatic int prompt(char *const v, const size_t v_size) {\n size_t len;\n int ch;\n assert(v &amp;&amp; v_size &gt; 2 &amp;&amp; v_size &lt;= INT_MAX);\n //Loop checks if `fgets` succeeded and if there is '\\n' in the string:\n for( ; ; ) {\n printf(&quot;Type a word with up to %zu chracters:\\n&quot;, v_size - 2);\n if(!fgets(v, (int)v_size, stdin)) goto eof;\n if(v[len = strcspn(v, &quot;\\n&quot;)] == '\\n') return v[len] = '\\0', 1;\n //fprintf(stderr, &quot;Error: input line too long.\\n&quot;);\n fprintf(stderr, &quot;Discarding malformed line.\\n&quot;);\n while(ch = getchar(), ch != '\\n') if(ch == EOF) goto eof;\n }\neof:\n if(feof(stdin)) errno = EOF_ERROR; // in this use-case, it is an error\n else if(!errno) errno = NOT_POSIX_COMPLIANT; // &quot;Extension to the ISO&quot;\n return 0;\n}\n\nint main(void) {\n char v[12];\n\n if(!prompt(v, sizeof v)) goto error;\n printf(&quot;%s\\n&quot;, v);\n\n return 0;\n\nerror:\n switch(errno) {\n case NOT_POSIX_COMPLIANT:\n fprintf(stderr, &quot;An unknown read error occurred.\\n&quot;); break;\n case EOF_ERROR:\n fprintf(stderr, &quot;Premature EOF.\\n&quot;); break;\n default:\n perror(&quot;input&quot;);\n }\n return EXIT_FAILURE;\n}\n</code></pre>\n<p>I've re-arraged some stuff using what it says in the man pages about errors to match the diagram. It's hard to do interactive programmes in purely <code>ISO C</code>. I would consider, depending on your application, returning failure immediately upon mis-formed input. Especially if you think there is a good reason to pipe data to <code>stdin</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T19:25:36.290", "Id": "505837", "Score": "1", "body": "Consider a redirected `stdin` where the last line of input is `\"abc\"` with no `'\\n'`. `prompt(v, 12)` here rejects that short line with `\"Error: input line too long.\\n\"` instead of accepting it. IMO, better to accept such lines. Lines that end with an end-of-file rather than a `'\\n'` are often a corner case to deliberate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T22:49:12.840", "Id": "505848", "Score": "0", "body": "@chux-ReinstateMonica good catch; there are definitely even more edge cases that I didn't think of. On my computer, an EOF in state `getchar` causes the message `too long` and then it keeps reading. I think this is probably undesirable, too. I think a terminal control library is really what is needed, but probably overkill for most applications." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T23:29:21.467", "Id": "505849", "Score": "0", "body": "Neil, Good catch on the \"keeps reading\". IMO, the standard C library simple lacks a nice \"read a line into a buffer\" function. `fgets()` is OK, but has weaknesses." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T08:53:11.973", "Id": "256225", "ParentId": "256166", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T00:40:28.580", "Id": "256166", "Score": "4", "Tags": [ "c", "strings", "io" ], "Title": "Limit fgets input to up to a certain number of characters" }
256166
<p>I have a nested object and I would like to calculate the number of times the property 'error'. I am able to go n levels deep and find the count. Is there a better solution than mine?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const data = { "item1": { "value": 88, "error": false }, "item2": { "value": 651, "error": false }, "item3": false, "item4": [], "item5": "", "item6": "", "item7": false, "item8": { "error": true }, "item9": { "value": [], "error": true }, "item10": { "value": [], "error": true }, "item11": { "value": [], "error": true }, "item12": false, "item13": { "subItem1": { "name": "Country", "groups": {}, "instances": [], "error": true }, "subItem2": { "name": "Group", "groups": {}, "instances": [], "error": true }, "subItem3": { "name": "Product", "groups": {}, "instances": [], "error": true } } } function traverseAndFlatten(currentNode, target, flattenedKey) { for (var key in currentNode) { if (currentNode.hasOwnProperty(key)) { var newKey; if (flattenedKey === undefined) { newKey = key; } else { newKey = flattenedKey + '.' + key; } var value = currentNode[key]; if (typeof value === "object") { traverseAndFlatten(value, target, newKey); } else { target[newKey] = value; } } } } function flatten(obj) { var flattenedObject = {}; traverseAndFlatten(obj, flattenedObject); return flattenedObject; } var flattened = flatten(data); const keys = _.keys(flattened); const errorCount = _.map(keys, key =&gt; { let count = 0; if (key.includes('.error') &amp;&amp; flattened[key]) { count++ } return count }) console.log(_.sumBy(errorCount))</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T14:12:46.147", "Id": "505665", "Score": "0", "body": "Given that the code uses lodash, when you state “_I am open to use lodash as well._” did you actually mean that you are open to _not using_ lodash?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T14:28:55.630", "Id": "505668", "Score": "0", "body": "I am open to using lodash. I will fix the OP" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T14:33:03.447", "Id": "505670", "Score": "0", "body": "Are you also open to vanilla JS i.e. without lodash?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T14:51:06.633", "Id": "505673", "Score": "0", "body": "Sure. I am open.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T15:21:52.427", "Id": "505678", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ Any luck?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T16:11:56.363", "Id": "505684", "Score": "0", "body": "please clarify what qualifies as \"better\" - fewer lines of code? faster? uses less memory?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T16:18:46.997", "Id": "505686", "Score": "0", "body": "Yeah, just in terms of performance and less lines of code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T06:27:30.690", "Id": "505772", "Score": "1", "body": "Maybe not the best idea, but could be easiest to implement: `count = 0; JSON.stringify(data, function (x, y) { if (x === 'error' && y) count++; return y; }); alert(count);`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T02:26:22.620", "Id": "256167", "Score": "0", "Tags": [ "javascript", "object-oriented", "lodash.js" ], "Title": "Find number of times a property has a truthy value in a nested object" }
256167
<p>I know embarassingly little about asynchronous programming in C#, so decided to start catching up. It would help me a lot if anyone checked this basic example I've created.</p> <p><strong>Assumption</strong>: we're creating a simulation where the time passes turn by turn with predefined minimal interval, e.g. 1 second. However, if any important calculations during the turn would take longer than this interval, next turn should not begin until they're done.</p> <p>I would be grateful if you could tell me if there any visible issues, code smells, or if it can be optimized. I've read bad things about using <code>Task.Run</code>, but I don't really know how to tackle it better.</p> <pre><code>public static class Program { static void Main() { var gameTurnsController = new GameTurnsController(); var cts = new CancellationTokenSource(); try { // Asynchronously wait for input to send cancellation token Task.Run(() =&gt; { Console.ReadKey(true); cts.Cancel(); }); gameTurnsController.PassTurns(TimeSpan.FromSeconds(1), cts.Token).Wait(cts.Token); } // It smells of controlling the execution flow through exception. Isn't there a better way to handle cancellation? catch (OperationCanceledException) { Console.WriteLine(Environment.NewLine + &quot;Cancelled.&quot;); Environment.ExitCode = 0; } Console.WriteLine(&quot;Execution finished.&quot;); } } </code></pre> <pre><code>public class GameTurnsController { public async Task PassTurns(TimeSpan interval, CancellationToken cancellationToken) { while (true) { if (cancellationToken.IsCancellationRequested) { return; } // Wait until both delay and calculation is finished await Task.WhenAll(Task.Delay(interval, cancellationToken), LongRunningOperation(cancellationToken)); } } // expensive method example private async Task&lt;long&gt; LongRunningOperation(CancellationToken cancellationToken) { return await Task.Run(() =&gt; { long result; // ... // expensive math operation that returns long value // ... return result; }, cancellationToken); } } </code></pre> <p>In the above code I've removed most of the logs and stopwatches for clarity.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T09:28:34.483", "Id": "505639", "Score": "0", "body": "What .NET and C# version are you using? I'm asking it because for example [async main](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.1/async-main) is supported since C# 7.1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T09:54:25.817", "Id": "505644", "Score": "0", "body": "I'm using 7.0, but I know about `async main`. Do I get it right that the only change here would be awaiting the `PassTurns` call instead of using `.Wait` on it?" } ]
[ { "body": "<p>The <code>Wait</code> call is tricky.</p>\n<ul>\n<li>It throws by default <code>AggregateException</code> not <code>OperationCanceledException</code>.</li>\n<li>If you provide the <code>cancellationToken</code> to the <code>Wait</code> then it will throw an <code>OperationCanceledException</code>.</li>\n<li>The biggest problem with this approach is that it cancels <strong>only</strong> the <code>Wait</code> not the underlying task.\n<ul>\n<li>Please read this <a href=\"https://lbadri.wordpress.com/2016/10/04/cancellationtoken-with-task-run-and-wait/\" rel=\"nofollow noreferrer\">article</a> for more details.</li>\n</ul>\n</li>\n</ul>\n<p>So, if we switch to <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-7.1/async-main\" rel=\"nofollow noreferrer\">async main</a> then the application will not stop after user cancellation:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static async Task Main()\n{\n var gameTurnsController = new GameTurnsController();\n var userRequestedCancellation = new CancellationTokenSource();\n\n try\n {\n _ = Task.Run(() =&gt;\n {\n Console.WriteLine(&quot;Please press any key to cancel&quot;);\n Console.ReadKey(true);\n userRequestedCancellation.Cancel();\n });\n\n await gameTurnsController.PassTurns(TimeSpan.FromSeconds(1), userRequestedCancellation.Token);\n }\n catch (OperationCanceledException)\n {\n Console.WriteLine(Environment.NewLine + &quot;Cancelled.&quot;);\n Environment.ExitCode = 0;\n }\n\n Console.WriteLine(&quot;Execution finished.&quot;);\n}\n</code></pre>\n<ul>\n<li>Because the underlying <code>LongRunningOperation</code> will not terminate.\n<ul>\n<li>(Let me use <code>Thread.Sleep(5000)</code> to simulate complex CPU bound operation)</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>private async Task&lt;long&gt; LongRunningOperation(CancellationToken cancellationToken)\n{\n return await Task.Run(() =&gt;\n {\n long result;\n Thread.Sleep(5000);\n return result;\n }, cancellationToken);\n}\n</code></pre>\n<ul>\n<li>If I run this app and I press any key then it will not cancel the <code>LongRunningOperation</code> method that's why the output will be the <code>Execution finished.</code>.</li>\n</ul>\n<h2>How to fix it?</h2>\n<p>By passing all the way long the cancellationToken:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private async Task&lt;long&gt; LongRunningOperation(CancellationToken cancellationToken)\n{\n var job = Task.Run(() =&gt; LongRunningOperationInternal(cancellationToken), cancellationToken);\n return await job;\n}\n\nprivate long LongRunningOperationInternal(CancellationToken cancellationToken)\n{\n long result = 1;\n for (int i = 0; i &lt; 5; i++)\n {\n cancellationToken.ThrowIfCancellationRequested();\n Thread.Sleep(1000); \n }\n\n return result;\n}\n</code></pre>\n<p>If need to do graceful cancellation then consider to use the following pattern:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>if(cancellationToken.IsCancellationRequested)\n{\n //TODO: clean up whatever is needed\n\n cancellationToken.ThrowIfCancellationRequested();\n}\n</code></pre>\n<p>TL;DR: You need to check the cancellationToken at milestones/checkpoints to be able to truly cancel the whole application.</p>\n<hr />\n<p>Might be an interesting read: <a href=\"https://devblogs.microsoft.com/pfxteam/how-do-i-cancel-non-cancelable-async-operations/\" rel=\"nofollow noreferrer\">How to can non-cancelable async operations</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T10:45:35.580", "Id": "256181", "ParentId": "256168", "Score": "3" } } ]
{ "AcceptedAnswerId": "256181", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T02:41:30.873", "Id": "256168", "Score": "1", "Tags": [ "c#", "asynchronous" ], "Title": "C# asynchronous tasks training (turn-based simulation)" }
256168
<p>I'm trying to teach myself assembly via MASM, below is my first implementation of the recursive form of the fibonacci sequence. I timed it against an equivalent C implementation in release mode and the C implementation was much better optimized. What can I do better? I haven't gotten the hang of how the various side effects of instructions impact the state of registers or flags yet, or, well, most things in assembly.</p> <p>Assembly:</p> <pre><code>;extern &quot;C&quot; unsigned long fibonacci_asm_canonical(unsigned long number) fibonacci_asm_canonical proc number: dword LOCAL fib_lhs:DWORD mov eax, number ; store number parameter in eax register (also used as return value). .IF eax &gt; 1 ; recursively call this function, retrieving the value for the left-hand side. dec eax mov edx, eax invoke fibonacci_asm_canonical, edx mov fib_lhs, eax ; store the result of fibonacci_asm_canonical(number - 1) into fib_lhs. mov eax, number ; store number parameter in eax register to set up right-hand side of addition. ; recursively call this function, retrieving the value for the right-hand side. sub eax, 2 invoke fibonacci_asm_canonical, eax ;eax now contains result of fibonacci_asm_canonical(number - 2), following the invocation, ;so add it with the result of fibonacci_asm_canonical(number - 1) which is in fib_lhs. add eax, fib_lhs .ENDIF ret fibonacci_asm_canonical endp </code></pre> <p>C version:</p> <pre><code>unsigned long fib_canonical(unsigned long number) { if (number &lt;= 1) return number; return fib_canonical(number - 1) + fib_canonical(number - 2); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T16:35:33.303", "Id": "505689", "Score": "1", "body": "There is not much to micro-optimize. Function calls are relatively expensive, same as lots of loads/stores into the stack. But calls & stack usage are result of choosing recursive solution. Number of iterations is exponential, for n=20 it performs in the ballpark of a million iterations. If you were to implement iterative solution it would only need 20 iterations (for n=20). Iterative solution may also be more susceptible to micro-optimization." } ]
[ { "body": "\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>dec eax\nmov edx, eax\n</code></pre>\n</blockquote>\n<p>This you can write as the single instruction <code>lea edx, [eax-1]</code>, but your code doesn't need to use the extra register <code>EDX</code> at all. The single <code>dec eax</code> is enough.</p>\n<p>If you really want to optimize code then don't use constructs like <code>.IF eax &gt; 1</code> <code>.ENDIF</code> (and many others) for which you don't necessarily know how they get encoded.</p>\n<p><code>invoke</code>, <code>proc</code>, <code>local</code>, and <code>endp</code> will very probably entail that prologue and epilogue codes are inserted. This is fine for the interfacing with the main program but is demanding on the recursion.</p>\n<pre class=\"lang-none prettyprint-override\"><code>push ebp ; Prologue\nmov ebp, esp\nsub esp, 4 ; Local\n...\nmov esp, ebp ; Epilogue\npop ebp\nret 4 ; Parameter removal\n</code></pre>\n<p>With a separate recursive routine <em>DoFib</em>, you can:</p>\n<ul>\n<li>avoid using the above and rely on the faster <code>[esp]</code> relative addressing.</li>\n<li>reuse the argument from the first recursive call. All it takes is a second <code>dec</code> on the already decremented value.</li>\n<li>pass the single dword argument via the <code>EAX</code> register instead of on the stack.</li>\n</ul>\n<pre class=\"lang-none prettyprint-override\"><code>;extern &quot;C&quot; unsigned long fibonacci_asm_canonical(unsigned long number)\nfibonacci_asm_canonical proc number: dword\n mov eax, number\n call DoFib ; -&gt; EAX\n ret\nfibonacci_asm_canonical endp\n\n; IN (eax) OUT (eax)\nDoFib:\n cmp eax, 1\n jbe .done\n sub esp, 8 ; Room for local storage\n dec eax\n mov [esp], eax ; (number - 1)\n call DoFib ; -&gt; EAX\n mov [esp+4], eax ; Store lhs result\n mov eax, [esp] ; (number - 1)\n dec eax ; (number - 2)\n call DoFib ; -&gt; EAX\n add eax, [esp+4] ; rhs + lhs\n add esp, 8\n .done:\n ret\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-07T20:13:51.013", "Id": "256854", "ParentId": "256172", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T05:49:30.280", "Id": "256172", "Score": "1", "Tags": [ "c", "assembly", "fibonacci-sequence" ], "Title": "MASM) assembly implementation of recursive Fibonacci" }
256172
<p>Wrote a function to calculate the square root.</p> <p>Magic from: <a href="https://tour.golang.org/flowcontrol/8" rel="nofollow noreferrer">https://tour.golang.org/flowcontrol/8</a></p> <p>The result is almost always the same as <code>math.sqrt</code>. Difference percentage is always around 10%. All difference (if any) is almost always in magnitude e-10.</p> <p>How can the function be more accurate? Does is even need to be more accurate?</p> <pre><code>import math from random import randint def sqrt(n): x = 1 # initial guess h1, h2 = 0.0, 0.0 # history while True: # if answer or if number reappears if x*x == n or x == h1 or x == h2: return x h2 = h1 h1 = x x = x - ((x*x - n) / (2*x)) # magic if __name__ == &quot;__main__&quot;: error_count = 0 repeat = 300 for _ in range(repeat): number = randint(0, 10000000000000) result = sqrt(number) math_result = math.sqrt(number) error = abs(result - math_result) if error: error_count += 1 print(number, result, math_result, error) print() print(f&quot;Errors: {error_count}&quot;) print(f&quot;Percentage: {error_count/repeat:%}&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T06:28:17.090", "Id": "505629", "Score": "3", "body": "Does it even need to be more accurate? That's a question probably only you can answer. We don't know what you intend to do with it..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T10:25:38.930", "Id": "505647", "Score": "3", "body": "Using \"==\" in floating point arithmetic usually does not make sense. Additionally assuming that all digits returned by `math.sqrt(number)` are correct needs at least some justification. I think this is not true. So you should think about a better 'termination criterion' and a better way to check the quality of your result." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T06:21:38.590", "Id": "256174", "Score": "1", "Tags": [ "python" ], "Title": "simple square root function" }
256174
<p>I'm doing some work with Vulkan, in this I need to pass a set of values of various types.</p> <p>Currently I'm using <code>std::array&lt;std::variant&lt;&gt;&gt;</code> in my interface, but I must pass Vulkan a <code>void*</code>.</p> <p>To convert to the <code>void*</code> I use this function:</p> <pre class="lang-cpp prettyprint-override"><code>template &lt;uint32_t Size&gt; void* voidArray(std::array&lt;std::variant&lt;uint32_t,float&gt;,Size&gt;&amp; array, uint32_t size) { char* bytes = new char[size]; uint32_t byteCounter = 0; for(uint32_t i=0;i&lt;array.size();++i) { if(float* flt = std::get_if&lt;float&gt;(&amp;array[i])) { *reinterpret_cast&lt;float*&gt;(bytes+byteCounter) = *flt; byteCounter += sizeof(float); } else if(uint32_t* uin = std::get_if&lt;uint32_t&gt;(&amp;array[i])) { *reinterpret_cast&lt;uint32_t*&gt;(bytes+byteCounter) = *uin; byteCounter += sizeof(uint32_t); } } void* data = static_cast&lt;void*&gt;(bytes); return data; } </code></pre> <p>I get the <code>size</code> variable earlier within a larger function (names are a little more context specific):</p> <pre class="lang-cpp prettyprint-override"><code>// std::array&lt;std::variant&lt;uint32_t,float&gt;,NumPushConstants&gt;&amp; pushConstants std::optional&lt;uint32_t&gt; pushConstantSize = std::nullopt; // later used for `size` auto size_fn = [](auto variant) -&gt; uint32_t { using T = std::decay_t&lt;decltype(variant)&gt;; if constexpr (std::is_same_v&lt;uint32_t, T&gt;) { return sizeof(uint32_t); } if constexpr (std::is_same_v&lt;float, T&gt;) { return sizeof(float);} }; pushConstantSize = std::accumulate(pushConstants.begin(),pushConstants.end(),0, [size_fn](uint32_t acc, auto variant) { return std::move(acc) + std::visit(size_fn,variant); } ); </code></pre> <p>Both of these implementations, most prominently the first rouse my suspicion of being bad.</p> <p>Are they bad? Is there a better way? Am I missing something?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T08:25:42.600", "Id": "505635", "Score": "3", "body": "It would be nice to have some more information (and code). Why do you need the variants? Why not use two separate arrays?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T09:42:02.840", "Id": "505641", "Score": "0", "body": "@user673679 Using variants allows flexibility in ordering, more closely matches the real structure and better allows for possible further templating in allowing the array to contain a mixture of any user-specified types (Vulkan in taking a `void*` means the array can contain any types, I have for now simply set 2 very common types I am using), is my current thinking." } ]
[ { "body": "<p>It's hard to provide overall feedback, since you don't want to provide any details. There's probably a much simpler way to structure all of this.</p>\n<p>But some things about the specific code:</p>\n<hr />\n<p><strong>don't do manual memory management</strong>:</p>\n<pre><code>char* bytes = new char[size];\n</code></pre>\n<p>I hope this gets <code>delete[]</code>d somewhere. We should use a <code>std::vector</code> instead, and get a pointer from <code>vector.data()</code> when we actually need to.</p>\n<hr />\n<p><strong>use std::byte in C++17</strong>:</p>\n<pre><code>char* bytes = new char[size];\n</code></pre>\n<p>If we have it, we should use <code>std::byte</code> instead of <code>char</code> (since we're dealing with object representations in memory).</p>\n<hr />\n<p><strong>use memcpy, not reinterpret_cast; simplify</strong>:</p>\n<pre><code> if(float* flt = std::get_if&lt;float&gt;(&amp;array[i])) {\n *reinterpret_cast&lt;float*&gt;(bytes+byteCounter) = *flt;\n byteCounter += sizeof(float);\n }\n else if(uint32_t* uin = std::get_if&lt;uint32_t&gt;(&amp;array[i])) {\n *reinterpret_cast&lt;uint32_t*&gt;(bytes+byteCounter) = *uin;\n byteCounter += sizeof(uint32_t);\n }\n</code></pre>\n<p>Due to &quot;strict aliasing rules&quot; I don't think this is technically correct (even if it apparently works). Our <code>char</code> array doesn't have floats in it, so we shouldn't pretend that it does and copy in a float. We should instead use <code>std::memcpy</code> to copy the underlying representation of the float into the array.</p>\n<p>Note also that we're doing the exact same thing for both types, so we could probably do something like:</p>\n<pre><code>std::apply([&amp;] (auto const&amp; var) {\n using T = std::decay_t&lt;decltype(var)&gt;;\n std::memcpy(bytes + byteCounter, static_cast&lt;void const*&gt;(&amp;var), sizeof(T));\n byteCounter += sizeof(T);\n}, array[i]);\n</code></pre>\n<hr />\n<p><strong>same again (again)</strong>:</p>\n<p>The same thing is true of the second code snippet:</p>\n<pre><code>std::optional&lt;uint32_t&gt; pushConstantSize = std::nullopt; // later used for `size`\nauto size_fn = [](auto variant) -&gt; uint32_t {\n using T = std::decay_t&lt;decltype(variant)&gt;;\n if constexpr (std::is_same_v&lt;uint32_t, T&gt;) { return sizeof(uint32_t); }\n if constexpr (std::is_same_v&lt;float, T&gt;) { return sizeof(float);}\n};\npushConstantSize = std::accumulate(pushConstants.begin(),pushConstants.end(),0,\n [size_fn](uint32_t acc, auto variant) { return std::move(acc) + std::visit(size_fn,variant); }\n);\n</code></pre>\n<p>We don't need the <code>if</code> statements:</p>\n<pre><code>auto size_fn = [] (auto const&amp; var) {\n using T = std::decay_t&lt;decltype(var)&gt;;\n return sizeof(T);\n};\nstd::size_t size = std::accumulate(pushConstants.begin(), pushConstants.end(), std::size_t{ 0 },\n [=](std::size_t acc, auto var) { return acc + std::visit(size_fn, var); }\n);\n</code></pre>\n<p><code>std::move</code> won't help with a trivially copyable type, and we should be using <code>std::size_t</code> for the size.</p>\n<p>The <code>optional</code> also seems redundant; we always have a size, even if the array is empty.</p>\n<p>This snippet should be made a whole complete function by itself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:01:27.003", "Id": "505748", "Score": "1", "body": "Strict aliasing isn’t an issue when using `((un)signed) char` (or `std::byte`, which is basically just a strongly-typedef-ed `unsigned char`); there’s a specific exemption just for those. What *is* an issue, and what is never dealt with anywhere in the code, is alignment. Using `std::memcpy()` will dodge that issue *somewhat* (where simply casting and assigning won’t), but even if it doesn’t bite you in *this* code, it will almost certainly bite you elsewhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T04:42:04.410", "Id": "505764", "Score": "1", "body": "Good points! I had some issues with the implementation of `std::apply` and I instead went this approach for that part instead https://pastebin.com/LpYxiQ2z." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T11:23:25.057", "Id": "256183", "ParentId": "256176", "Score": "0" } } ]
{ "AcceptedAnswerId": "256183", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T06:45:15.700", "Id": "256176", "Score": "0", "Tags": [ "c++", "array", "casting" ], "Title": "Converting from `std::array<std::variant<>>` to `void*`" }
256176
<p>I have this rails controller which works fine but a lot of business logic is confined in the controller which I believe is not a good practice.</p> <pre><code>class MoviesController &lt; ApplicationController before_action :set_movie, only: [ :edit, :update, :destroy ] rescue_from ActiveRecord::RecordNotFound, with: :render_404 def index year = params[:year].split('-') unless params[:year].nil? starting_year = year[0] unless year.nil? || year.empty? ending_year = year[year.length - 1] unless year.nil? || year.empty? genre = params[:genre][0] unless params[:genre].nil? language = params[:language][0] unless params[:language].nil? quality = params[:quality][0] unless params[:quality].nil? rating = params[:rating_bound][0] unless params[:rating_bound].nil? order_by = params[:orders_filter][0] unless params[:orders_filter].nil? @movies = Movie.search_title(params[:title]).search_language(language).search_on_starting_year(starting_year).search_on_ending_year(ending_year).search_video_quality(quality).search_genre( genre ).search_rating(rating).order_on_filter(order_by).includes(:profile_photo) end def show @movie = Movie.includes( :profile_photo, :created_by, movie_roles: [:actor], feedback: [:user] ).left_outer_joins(:likes, :ratings).select( 'movies.*, CAST(AVG(ratings.value) AS DECIMAL(10,1)) AS rating, count(likes.likeable_id) * 6 as total_likes' ).find params[:id] @reviews = @movie.feedback.select { |item| item.type == 'Review' } @comments = @movie.feedback.select { |item| item.type == 'Comment' } @directors = @movie.movie_roles.select { |role| role.role_played == 'director' } @actors = @movie.movie_roles.select { |role| role.role_played == 'actor' } end def new @movie = Movie.new @movie.build_profile_photo end def edit end def render_404 render file: &quot;#{Rails.root}/public/404&quot;, status: :not_found end # POST /movies # POST /movies.json def create parameters = movie_params @movie = Movie.new(parameters) @movie.created_by = current_user if @movie.save redirect_to @movie, notice: 'Movie was successfully created.' else render :new, notice: 'Not Saved!' end end def update respond_to do |format| if @movie.update(movie_params) format.html { redirect_to @movie, notice: 'Movie was successfully updated.' } format.json { render :show, status: :ok, location: @movie } else format.html { render :edit } format.json { render json: @movie.errors, status: :unprocessable_entity } end end end def destroy @movie.destroy respond_to do |format| format.html { redirect_to movies_url, notice: 'Movie was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_movie @movie = Movie.find(params[:id]) end # Only allow a list of trusted parameters through. def movie_params params.fetch(:movie, {}).permit(:name, :release_date, :video_quality, :synopsis, :genres, :language) params.fetch(:movie, {}).permit(:name, :release_date, :video_quality, :synopsis, :genres, :language, profile_photo_attributes: [:path]) end end </code></pre> <p>I need to shrink the controller size and make the code look much clear and readable!</p>
[]
[ { "body": "<p>Well there plenty different ways to do it, not sure how you are making these parameters, as they should not have [0] as I knew somewhere you doing differently. But any how. You can create simple Poro class and send your parameters to give you all records and then show to user. Currently there is a lot hype of Interactor and business logics, so I thought to give it a try. Here is what I have done.</p>\n<pre><code>bundle add interactor\n</code></pre>\n<p>Installed interactor which is used to create such logic you can read here <a href=\"https://github.com/collectiveidea/interactor\" rel=\"nofollow noreferrer\">Interactor</a>. Then I created folder called <code>interactors</code> in the root of my project, note not in app but in root and added following line in <code>config/application.rb</code></p>\n<pre><code>config.autoload_paths &lt;&lt; Rails.root.join('interactors')\n</code></pre>\n<p>Now I changed action of controller like following</p>\n<pre><code> def index\n @movies = SearchMoviesInteractor.call(params)\n if @movies.success?\n @movies\n else\n 'No movies found'\n end\n end\n</code></pre>\n<p>and add one new class in my interactor folder called <code>interactors/search_movies_interactor.rb</code> yes search, well interactor are supposed to be each file for one operation like CRUD four files, now following is my interactor which is creating dynamically from private methods the condition field, I am not sure it is very clean but I love this as this way you can add as many filter as you want.</p>\n<pre><code>class SearchMoviesInteractor\n include Interactor\n\n def call\n filtering\n end\n\n def filtering\n if conditions.empty?\n Movies.all\n else\n 'Movies.' &lt;&lt; condition_clauses.join('.').to_s\n end\n end\n\n def conditions\n [conditions_clauses.join('.'), *conditions_options]\n end\n\n def conditions_clauses\n conditions_parts.map { |condition| condition.first }\n end\n\n def conditions_parts\n private_methods(false).grep(/_conditions/).map { |m| send(m) }.compact\n end\n\n def conditions_options\n conditions_parts.map { |condition| condition[1..-1] }.flatten\n end\n\n private\n\n def start_year_conditions\n year = conext.year.split('-') unless year.nil?\n &quot;search_on_starting_year(#{context.year[0]})&quot; unless year.nil? || year.empty?\n end\n\n def ending_year_conditions\n ending_year = context.year[context.year.length - 1] unless context.year.nil? || context.year.empty?\n &quot;search_on_ending_year(#{ending_year})&quot;\n end\n\n def title_conditions\n &quot;search_on_starting_title(#{context.year})&quot;\n end\nend\n</code></pre>\n<p>Not I can see condition is being made correctly but I don't have database to check actual result so you have to check how does interactor return data, and then show it to user. those parts are just concept.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T11:59:45.367", "Id": "505655", "Score": "0", "body": "Thanks for the answer! but adding \nconfig.autoload_paths << Rails.root.join('interactors') , in the config/application.rb causes a NameError for me!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T12:40:25.440", "Id": "505658", "Score": "0", "body": "what is your version of rails? mine is 6 are you adding this inside config block? add after ` class Application < Rails::Application` line" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T09:14:22.940", "Id": "505782", "Score": "0", "body": "Im also running rails 6, and I've added the config block as you've mentioned above, and it still gives me \" NameError, uninitialized Constant\" for my Search interactor!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T10:21:37.927", "Id": "505785", "Score": "0", "body": "oh sorry for that any how you can make simple class in `lib` folder or even in your `model` not recomended and then call it, it will work without adding, and no need to add Gem make simple Poro class and make your controller actions think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T10:28:28.257", "Id": "505787", "Score": "0", "body": "Right! Got it, thanks a lot!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T09:05:45.840", "Id": "256179", "ParentId": "256177", "Score": "0" } }, { "body": "<p>One thing you can do to simplify your controllers is use something like the scaffolding gem <a href=\"https://github.com/tubbo/controller_resources\" rel=\"nofollow noreferrer\">https://github.com/tubbo/controller_resources</a> - that would reduce some of the boilerplate code.</p>\n<p>For the <code>#index</code> method I would rewrite it chainging relations something like</p>\n<pre><code> def index\n @movies = Movie.all.includes(:profile_photo)\n if params[:year].present?\n years = params[:year].split('-')\n @movies = @movies.search_on_ending_year(years.first)\n @movies = @movies.search_on_ending_year(years.last)\n end\n @movies = @movies.search_genre( params[:genre].first ) if params[:genre].present? \n # etc\n @movies = @movies.order_on_filter(params[:orders_filter].filter) if params[:orders_filter].present?\n end\n</code></pre>\n<p>If you define your scopes something like\n<code>scope search_on_ending_year, -&gt;(year) { year ? some_condition : all }</code>\nthen you can also remove the conditionals above</p>\n<p>Note that you can combine that a simple way to check both <code>nil?</code> and <code>empty?</code> in one step is to use <code>blank?</code>. Likewise <code>present?</code> is very universal and checks that values are not nil, strings are not blank, arrays are not empty, etc</p>\n<p>In the <code>movie_params</code> method</p>\n<pre><code> def movie_params\n params.fetch(:movie, {}).permit(:name, :release_date, :video_quality, :synopsis, :genres, :language)\n params.fetch(:movie, {}).permit(:name, :release_date, :video_quality, :synopsis, :genres, :language, profile_photo_attributes: [:path]) \n end\n</code></pre>\n<p>the first line is both redundant and ignored</p>\n<p>I think your code would also be simpler if you structured your html to avoid array parameters like this <code>params[:orders_filter][0]</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T21:37:18.547", "Id": "256244", "ParentId": "256177", "Score": "1" } } ]
{ "AcceptedAnswerId": "256179", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T07:43:07.350", "Id": "256177", "Score": "1", "Tags": [ "ruby-on-rails", "controller" ], "Title": "Making the controller clean and readable in (Ruby on Rails)" }
256177
<p>In the app that works only for training purposes I have a React component that serves(among others) as an 'event catcher' for all events that happen on its rendered children. It contains (at the time being, besides other stuff) eight expressions similar to the following:</p> <pre><code> const debouncedFetchSingleBook = useCallback( // using lodash debounce() debounce(target =&gt; { const button = target.closest(&quot;button&quot;); // Catch event target. In this case, it is fetchSinglebook. fetchSingleBook(redirect, button.dataset.content, true); }, 200), [fetchSingleBook] ); </code></pre> <p>The duty of such the expression is to return a callback that debounces and executes an event action fired on button pressing.</p> <p>I tried to write a function that would take actual function as argument and return what described above, in order to keep code DRY. So, here is what I have written:</p> <pre><code>const useCreateDebouncedCallback=(fn)=&gt;{ const result = useCallback( debounce(target =&gt; { const button = target.closest(&quot;button&quot;); fn(button.dataset.content); }, 200), [fn] ); return result; } </code></pre> <p>That is defined above component self where it is called, in the same file. Basically, it works(no error, task done).</p> <p>My question is whether: It conforms to React standards? Are there any possible failures in the code that do not expose themselves immediately?</p> <p>This is my first custom React Hook. Any help would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T12:39:20.173", "Id": "505657", "Score": "0", "body": "Welcome to the Code Review Community. For us to be able to do a good review of the code all or most of the code should be presented in the question. Is it possible for you to present the entire object rather than just snippets? Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T08:07:23.380", "Id": "256178", "Score": "0", "Tags": [ "react.js" ], "Title": "A kind of function factory within react component" }
256178
<p>I am trying to make logger class with debug, info, warn and error methods that &quot;extends&quot; basic log method.</p> <p>However it is not written using <strong>DRY</strong> principle, how can I make it <strong>DRY</strong>, not <strong>WET</strong>?</p> <h3>Code snippet</h3> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const logLevels = { 0: 'debug', 1: 'info', 2: 'warn', 3: 'error', 'debug': 0, 'info': 1, 'warn': 2, 'error': 3, } class Logger { logLevel = logLevels.debug log(logLevel, ...messages) { if (logLevel &gt;= this.logLevel) { const logType = logLevels[logLevel] messages.unshift(logType) console.log(...messages) } } debug(...messages) { this.log(logLevels.debug, ...messages) } info(...messages) { this.log(logLevels.info, ...messages) } warn(...messages) { this.log(logLevels.warn, ...messages) } error(...messages) { this.log(logLevels.error, ...messages) } } const myLogger = new Logger() const dateNowHex = () =&gt; Date.now().toString(16) myLogger.debug('this is a test', dateNowHex()) myLogger.info('this is a test', dateNowHex()) myLogger.warn('this is a test', dateNowHex()) myLogger.error('this is a test', dateNowHex())</code></pre> </div> </div> </p> <p>Should I make better class composition? Can you provide examples?</p>
[]
[ { "body": "<p>Interesting question;</p>\n<ul>\n<li><p>getting the <code>logType</code> and then unshifting it seems complicated, why not</p>\n<p><code>console.log(logLevels[logLevel], ...messages)</code></p>\n</li>\n<li><p>The mapping from an integer to a string and back from string to integer must be addressed to make this DRY</p>\n</li>\n<li><p>This code seems a good fit for monads, which can also help with making this DRY</p>\n</li>\n</ul>\n<p>Other than that there is not much to say.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function Logger() {\n \n const logLevels = ['debug', 'info', 'warn', 'error'];\n this.logLevel = 0;\n\n this.log = function log(logLevel, ...messages) {\n if (logLevel &gt;= this.logLevel) {\n console.log(logLevels[logLevel], ...messages)\n }\n }\n \n for(let i = 0; i&lt; logLevels.length; i++){\n this[logLevels[i]] = this.log.bind(this, i);\n }\n\n} \n\nconst myLogger = new Logger()\nconst dateNowHex = () =&gt; Date.now().toString(16) \n//debugger; \nmyLogger.debug('this is a test', dateNowHex())\nmyLogger.info('this is a test', dateNowHex())\nmyLogger.warn('this is a test', dateNowHex())\nmyLogger.error('this is a test', dateNowHex())</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T19:01:25.790", "Id": "505704", "Score": "0", "body": "Yeah, thank you very much! The logLevels is actually enum in TypeScript, just ignore it, probably important to be mentioned before. The reason behind unshift is that I am using additional coloring, so it is simplier to make it bold and then make all the messages of some color. Is there a way to make a extend based class composition? Could you please add it to your anwser as second variant? Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T20:28:39.460", "Id": "505712", "Score": "1", "body": "@RamoFX I could not get it to work as a class in jsbin :/" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T17:54:50.500", "Id": "256198", "ParentId": "256180", "Score": "1" } } ]
{ "AcceptedAnswerId": "256198", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T10:14:32.183", "Id": "256180", "Score": "0", "Tags": [ "javascript" ], "Title": "How to make DRY logger class with debug, info, warn and error methods that extends private method" }
256180
<p>I have a question about something maybe not so much important, but every time when I have to decide, I feel it can write in another way.</p> <p>Imagine I am developing and system about authentication and then I have to receive a pin after sending my phone number.</p> <p>So I am writing some <code>UseCase</code> and, in this case, I have an interactor and a Worker as protocol.</p> <p>Let's show the code</p> <pre class="lang-swift prettyprint-override"><code>import Foundation protocol SendPinWorker { func run(onResult: ((Result&lt;Bool, Error&gt;)-&gt;Void)?) } protocol SendPinUseCaseInteractor { func error(e: SendPINUseCaseError) func sent() func processing() } enum SendPINUseCaseError { case invalidPhone case couldNotSend } class SendPINUseCase { private let worker: SendPinWorker private let output: SendPinUseCaseInteractor init(worker: SendPinWorker, output: SendPinUseCaseInteractor) { self.worker = worker self.output = output } func execute(phone: String) { guard !phone.isEmpty else { self.output.error(e: .invalidPhone) return } self.output.processing() self.worker.run { [weak self] result in guard let self = self else { return } guard let sent = try? result.get(), sent else { self.output.error(e: .couldNotSend) return } self.output.sent() } } } </code></pre> <p>Should I put these protocols and enums in another file or should I still with these structures in the same file?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T11:40:17.143", "Id": "505951", "Score": "1", "body": "I don't think there is one true answer to your question. I personally would put them in a separate file but leaving them where they are used would also be fine. I think this question can only have opinionated answers. \n\nAlso, you can declare your class as `final` if no other class is subclassing from it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T17:34:46.357", "Id": "505984", "Score": "1", "body": "Same thoughts with @emrepun. I think this is more likely personal taste. One point to be considered is that while a wide range of various types remain in the same file, we might have a hard readable code-base to be faced with. In this situation, we would put in separate file." } ]
[ { "body": "<p>Consider nesting your types:</p>\n<p>If you have two types that start with the same prefix, it's possible that one type is better nested inside the other.\nFor example: <strong>SendPINUseCase</strong> raises <strong>SendPINUseCase</strong>Error's</p>\n<pre><code>class SendPINUseCase {\n enum Error {\n case invalidPhone\n case couldNotSend\n }\n}\n</code></pre>\n<p>Now you have a type called SendPINUseCase.Error, it's scoped to the SendPINUseCase. If you want to use throwing functions instead of returning Result&lt;..., Error&gt;'s, then you would make your SendPINUseCase.Error enum conform to <em>Swift.Error</em></p>\n<p>Protocols can't be nested, but in this case you could <em>avoid them entirely</em> by changing your design so that, for example, execute function takes, as arguments, the callback functions involved. If you eliminate the protocols, then there's no worry about which file to put them in, and protocols are not without their problems, I would say protocols are not the right abstraction in this case.</p>\n<p>Your SendPINUseCase is a class but doesn't encapsulate any state, so consider making it a struct.</p>\n<p>You have execute function take a String as input, and then validate that string is a 'phone'. Instead, consider making a struct Phone that has a failable initializer, so that only valid 'Phone's can be constructed. Then execute function would take a Phone struct that you know is valid, that eliminates the invalidPhone error case entirely.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T21:58:26.540", "Id": "506092", "Score": "0", "body": "I really like your points to improve my code, I just have a point which I want to discuss with you, about the `Protocols`. I chose to use them because I thought it was a good way to mock and create spies for unit tests, For example, I can make spies for `Interactor` and mock to `Worker`, I wonder to know what do you think about that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T09:15:01.493", "Id": "506207", "Score": "0", "body": "Too hard to explain in a reply here - search for \"How to Control the World\" by Stephen Celis at NSSpain" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T10:02:12.987", "Id": "256330", "ParentId": "256186", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T13:15:15.907", "Id": "256186", "Score": "0", "Tags": [ "swift" ], "Title": "Add protocols inside the same file as controller" }
256186
<p>I'm beginner in django and python. I have models :</p> <pre><code> class Employee(models.Model): full_name = models.CharField(max_length = 64) title = models.CharField(max_length = 64) def __str__(self): return f&quot;{self.full_name} ( {self.title} )&quot; class Skill(models.Model): name = models.CharField(max_length = 64) def __str__(self): return f&quot;{self.name}&quot; class Candidate(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name=&quot;employee&quot;) skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name=&quot;skill&quot;) def __str__(self): return f&quot;{self.id}: {self.employee} knows - {self.skill}&quot; class Job(models.Model): title = models.CharField(max_length = 64) skills = models.ManyToManyField(Skill, blank=True, related_name=&quot;Jobs&quot;) def __str__(self): return f&quot;{self.title}&quot; </code></pre> <p>In views.py, i have 'finder' function :</p> <pre><code>def finder(job_id): job = Job.objects.get(id=job_id) # get the specific job relevant_candidates = [] # all the relevant candidates of this kob common = [] # number of common skills between the employee_skill and the relevant_employees_by_title = Employee.objects.filter(title = job.title) # first filter the candidates by the job title job_skills = [] for skill in job.skills.all(): print(skill.id) job_skills.append(skill.id) for employee in relevant_employees_by_title: employee_skills =[] candidateCorrect = Candidate.objects.filter(employee__id = employee.id).values_list('skill', flat=True) for skill in candidateCorrect: employee_skills.append(skill) common_skills = list(set(job_skills) &amp; set(employee_skills)) if (len(common_skills)&gt;0): #if there are common skills relevant_candidates.append(employee) common.append(len(common_skills)) candidates = zip(relevant_candidates,common) candidates = sorted(candidates,key = lambda t: t[1], reverse = True) # sort the candidates by the number of common skiils , descending order candidates = candidates[:50] # Select the best 50 candidates return candidates </code></pre> <p>This function get the job_id and need to find the best candidates for this job : first by matching between the job title to the employee title (for ex' : software developer), and then matching between candidate's skills to job's required skiils .</p> <p>I think that my function is <strong>inefficient</strong>. Someone has any idea how to write it in efficient way?</p>
[]
[ { "body": "<p>You could use comprehensions to greater effect (here: directly build <code>job_skills</code> using a set comprehension) and also let got of having to put everything into a list.</p>\n<p>You could also store your suitable candidates in a <code>collections.Counter</code>, to get the <code>most_common(n)</code> method for free.</p>\n<pre><code>from collections import Counter\n\ndef finder(job_id, n=50):\n job_skills = {skill.id for skill in Job.objects.get(id=job_id).skills.all()}\n\n candidates = Counter()\n for employee in Employee.objects.filter(title=job.title): \n employee_skills = Candidate.objects\\\n .filter(employee__id=employee.id)\\\n .values_list('skill', flat=True)\n common_skills = len(job_skills.intersection(employee_skills))\n if common_skills:\n candidates[employee] = common_skills\n return candidates.most_common(n)\n</code></pre>\n<p>I also followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends not surrounding <code>=</code> with spaces when using it for keyword arguments, used the fact that the number <code>0</code> is falsey, while all other numbers are truthy and made the number of candidates to return configurable (with 50 the default value).</p>\n<hr />\n<p>Note that this task would have been slightly easier, if the <code>Employee</code> object already had the skill attached, or at least a link to the <code>Candidate</code> object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T14:22:49.823", "Id": "256229", "ParentId": "256187", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T13:31:23.337", "Id": "256187", "Score": "3", "Tags": [ "python", "django" ], "Title": "Find best candidates in efficient way, Django" }
256187
<p>I want to be able to persist context to local storage.</p> <p>My router looks like:</p> <pre><code>import React, { useState } from 'react'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import { Login } from './routes/login'; import { ResetPassword } from './routes/reset-password'; import { ResetEmailSent } from './routes/reset-email-sent'; import { App } from './routes/app'; import { GlobalContext, InitialState } from './globalContext'; import { Layout } from './layout'; function Router() { const [global, setGlobal] = useState(InitialState); return ( &lt;GlobalContext.Provider value={{ global, setGlobal }}&gt; &lt;BrowserRouter&gt; &lt;Route render={() =&gt; ( &lt;Layout&gt; &lt;Switch&gt; &lt;Route exact path='/'&gt; &lt;Login /&gt; &lt;/Route&gt; &lt;Route exact path='/reset-password'&gt; &lt;ResetPassword /&gt; &lt;/Route&gt; &lt;Route exact path='/reset-email-sent'&gt; &lt;ResetEmailSent /&gt; &lt;/Route&gt; &lt;Route exact path='*'&gt; &lt;App /&gt; &lt;/Route&gt; &lt;/Switch&gt; &lt;/Layout&gt; )} /&gt; &lt;/BrowserRouter&gt; &lt;/GlobalContext.Provider&gt; ); } export default Router; </code></pre> <p>and <code>globalConext</code> looks like</p> <pre><code>import { createContext, useContext } from 'react'; interface StateContextType { global: any; setGlobal: (State: any) =&gt; void; } const savedState = localStorage.getItem('state'); const state = savedState ? JSON.parse(savedState) : {}; const InitialState: any = state; const GlobalContext = createContext&lt;StateContextType&gt;({ global: InitialState, setGlobal: () =&gt; console.warn('no state provider'), }); const useGlobal = () =&gt; useContext(GlobalContext); export { InitialState, GlobalContext, useGlobal }; </code></pre> <p>Should I set up a <code>useEffect</code> in the router to save to local storage whenever <code>global</code> changes?</p> <br>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T14:09:22.883", "Id": "256189", "Score": "2", "Tags": [ "react.js", "typescript" ], "Title": "How to best persist context to local storage" }
256189
<p>I created this tiny script to full fill a repeated request from audit. I want to expand it but ran into an issue with file creation.</p> <p>This code will create the <code>$attachment</code> in the directory it is run from. When using ISE it stores the <code>$attachment</code> to the <code>system32</code> folder. When run from the script repository it leaves the file in the same directory. The goal is for the file to be attached and emailed out not leaving any remnants behind. This script is used in many functions for auditing so I will be using this as a &quot;standard&quot; process for automating audit reports. I am very new to scripting but looking for all feedback!!</p> <p>Eventually there will be multiple attachments to be added and this run weekly. Right now they are all individual scripts that are run as requested.</p> <pre><code> #Run Cleanup for ISE Variables using Preloaded Profile #Cleanup #Mailsettings $SmtpSender = &quot;Email@mail.com&quot; $SmtpReceiver = &quot;User@mail.com&quot; $SmtpSubject = &quot;User accounts enabled-Auditonly&quot; $SmtpBody = &quot;Attached is run from PDQ using script Users.enabled-Auditonly.ps1&quot; $Smtpservr = &quot;smtp.mail.com&quot; #Variables $attachment = New-Item &quot;Users.enabled-Auditonly$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv&quot; -ItemType File Get-ADuser -Filter * -Properties Name, SamAccountName,Description, Enabled | Select Name, SamAccountName,Description, Enabled | export-csv $attachment #Grabs the attachment from the above location and emails it out. Send-MailMessage -Attachments $attachment -Body $SmtpBody -BodyAsHtml -From $SmtpSender -To $SmtpReceiver -Subject $SmtpSubject -SmtpServer $Smtpservr </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T20:02:47.347", "Id": "505709", "Score": "0", "body": "The [`-Attachments`](https://docs.microsoft.com/en-gb/powershell/module/Microsoft.PowerShell.Utility/Send-MailMessage) parameter allows specifying _the **path and file names** of files to be attached to the email message_. For instance, `$attachment = New-Item \"$env:temp\\Users.enabled-Auditonl…` could help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-15T14:06:55.340", "Id": "514669", "Score": "0", "body": "set your $attachment variable to just the file (path and) name: `$attachment = \"Users.enabled-Auditonly$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv\"`. It will be created by the `Export-Csv` cmdlet (where BTW I would add switch `-NoTYpeInformation`. You don't want to use `New-Item`" } ]
[ { "body": "<p>Whenever possible I try to avoid creating temp files during script execution because they tend to introduce side effects and bugs related to security, permission, cleanup and duplicates.</p>\n<p><code>Export-Csv</code> creates a file but <a href=\"https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-csv?view=powershell-7.1\" rel=\"nofollow noreferrer\">ConvertTo-Csv</a> creates a string variable, which will allow you to avoid an intermediate file.</p>\n<p>The <code>Send-MailMessage</code> cmdlet you're using takes attachments that rely on a local path, but the .Net object <code>System.Net.Mail.MailMessage</code> allows adding attachments from an in-memory string. There's a good example of its use on <a href=\"https://stackoverflow.com/questions/53049923/send-mailmessage-attachment-from-memory\">send-mailmessage-attachment-from-memory</a>.\nInstead of <code>$([System.Net.Mail.Attachment]::CreateAttachmentFromString(&quot;HELLO2&quot;, &quot;Test2.txt&quot;))</code> you can use this:</p>\n<pre><code>$AttachmentName = &quot;Users.enabled-Auditonly$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv&quot;\n$AttachmentContents = Get-ADuser -Filter * -Properties Name, SamAccountName,Description, Enabled | Select Name, SamAccountName,Description, Enabled | ConvertTo-Csv \n\n$MailAttachment = [System.Net.Mail.Attachment]::CreateAttachmentFromString($AttachmentContents,$AttachmentName)\n</code></pre>\n<p>... and pass that <code>$MailAttachment</code> object to the function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-02T21:02:59.663", "Id": "265645", "ParentId": "256190", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T14:12:07.603", "Id": "256190", "Score": "2", "Tags": [ "email", "powershell", "automation" ], "Title": "Powershell SMTP report with attachment issues needs corrections" }
256190
<p>I have a bunch of large XML files that I have to parse and store in Postgres. I have done a lot of procedural code but I want to think in terms of objects and reap the benefits. Any help in that direction is greatly appreciated.</p> <p>The XML itself is fairly straightforward - Each Person object has employer, employer office, education information. I am wondering how best to design a Python Class to hold this data with the end goal of efficiently inserting data into Postgres.</p> <p><strong>Sample XML File</strong></p> <pre><code>&lt;?xml version=&quot;1.2&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;data&gt; &lt;person name=&quot;Mary Kitchen&quot; personkey=&quot;123&quot;&gt; &lt;employers&gt; &lt;employer name=&quot;ABC Tech&quot; id=&quot;767&quot; startdate=&quot;02-2020&quot; enddate=&quot;&quot;&gt; &lt;officeaddrs&gt; &lt;officeaddr str1=&quot;101 MAIN ST&quot; str2=&quot;&quot; city=&quot;NYC&quot; state=&quot;NY&quot; zip=&quot;07789&quot; /&gt; &lt;officeaddr str1=&quot;111 POOLE ST&quot; str2=&quot;&quot; city=&quot;NYC&quot; state=&quot;NY&quot; zip=&quot;07780&quot; /&gt; &lt;/officeaddrs&gt; &lt;/employer&gt; &lt;employer name=&quot;XYZ Tech&quot; id=&quot;909&quot; startdate=&quot;06-2012&quot; enddate=&quot;01-2020&quot;&gt; &lt;officeaddrs&gt; &lt;officeaddr str1=&quot;122 Main St&quot; str2=&quot;&quot; city=&quot;NYC&quot; state=&quot;NY&quot; zip=&quot;07789&quot; /&gt; &lt;officeaddr str1=&quot;199 Poole St&quot; str2=&quot;&quot; city=&quot;NYC&quot; state=&quot;NY&quot; zip=&quot;07780&quot; /&gt; &lt;/officeaddrs&gt; &lt;/employer&gt; &lt;/employers&gt; &lt;educationrecords&gt; &lt;educationrecord type=&quot;Masters&quot; school =&quot;ABC School&quot; graduated=&quot;12-14-2005&quot;/&gt; &lt;educationrecord type=&quot;Bachelors&quot; school =&quot;XYZ School&quot; graduated=&quot;12-14-2001&quot;/&gt; &lt;/educationrecords&gt; &lt;/person&gt; &lt;person name=&quot;JASON KNIGHT&quot; personkey=&quot;129&quot;&gt; &lt;employers&gt; &lt;employer name=&quot;NYState Bank&quot; id=&quot;66&quot; startdate=&quot;02-2015&quot; enddate=&quot;&quot;&gt; &lt;officeaddrs&gt; &lt;officeaddr str1=&quot;188 Main St&quot; str2=&quot;&quot; city=&quot;NYC&quot; state=&quot;NY&quot; zip=&quot;07789&quot; /&gt; &lt;officeaddr str1=&quot;100 Poole St&quot; str2=&quot;&quot; city=&quot;NYC&quot; state=&quot;NY&quot; zip=&quot;07780&quot; /&gt; &lt;/officeaddrs&gt; &lt;/employer&gt; &lt;employer name=&quot;ZYK Tech&quot; id=&quot;543&quot; startdate=&quot;02-2010&quot; enddate=&quot;01-2015&quot;&gt; &lt;officeaddrs&gt; &lt;officeaddr str1=&quot;333 MAIN ST&quot; str2=&quot;&quot; city=&quot;NYC&quot; state=&quot;NY&quot; zip=&quot;07789&quot; /&gt; &lt;/officeaddrs&gt; &lt;/employer&gt; &lt;/employers&gt; &lt;educationrecords&gt; &lt;educationrecord type=&quot;Bachelors&quot; school =&quot;Top School&quot; graduated=&quot;04-01-2009&quot;/&gt; &lt;/educationrecords&gt; &lt;/person&gt; &lt;/data&gt; </code></pre> <p><strong>Python code</strong></p> <pre><code># import xml.etree.ElementTree as ET from lxml import etree def fast_iter(context, func, args=None, kwargs=None): # http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ # Author: Liza Daly if kwargs is None: kwargs = {} if args is None: args = [] for event, elem in context: func(elem, *args, **kwargs) elem.clear() while elem.getprevious() is not None: del elem.getparent()[0] del context class PersonParser: def __init__(self, element): self.element = element def myparser(self): print('hello') print(self.element) class PersonData: def __init__(self, person=None, employer=None, office=None, education=None): self.person = person self.employer = employer self.office = office self.education = education class Person: def __init__(self, personkey=None, name=None): self.name = name.title() self.personkey = personkey # print(self.name, self.personkey) def __repr__(self): return '(name={}, personkey={})'.format( self.name, self.personkey) class Employer: def __init__(self, id=None, name=None, startdate=None, enddate=None): self.id = id self.name = name self.startdate = startdate self.enddate = enddate def __repr__(self): return f'(name={self.name}, id={self.id}, startdate={self.startdate}, enddate={self.enddate})' class Office: def __init__(self, str1=None, str2=None, city=None, state=None, zip=None, personkey=None, empid=None): self.empid = empid self.personkey = personkey self.str1 = str1 self.str2 = str2 self.city = city self.state = state self.zip = zip # print(self.name, self.personkey) def __repr__(self): return '(name={}, personkey={})'.format( self.name, self.personkey) class Education: def __init__(self, personkey=None, name=None): self.name = name self.personkey = personkey # print(self.name, self.personkey) def __repr__(self): return '(name={}, personkey={})'.format( self.name, self.personkey) def myfunction(element): print(element) for person in element.iter('person'): # print('person', person.attrib) person_rec = person.attrib print(person_rec) for employer in element.iter('employer'): # print('employer', employer.attrib) employer_rec = employer.attrib employer_rec['personkey'] = person_rec['personkey'] print(employer_rec) for office in employer.iter('officeaddr'): # print('office', office.attrib) office_rec = office.attrib office_rec['empid'] = employer_rec['id'] office_rec['personkey'] = person_rec['personkey'] print(office_rec) for education in element.iter('educationrecord'): # print('education', education.attrib) edu_rec = education.attrib edu_rec['personkey'] = person_rec['personkey'] print(edu_rec) def main(): # tree = ET.parse('person_data.xml') context = etree.iterparse('person_data.xml', events=('end',), tag='person') fast_iter(context, myfunction) myPersonParser = PersonParser(context) myPersonParser.myparser() if __name__ == &quot;__main__&quot;: main() </code></pre> <p><strong>Current Output</strong></p> <pre><code>&lt;Element person at 0x1006f9a40&gt; {'name': 'Mary Kitchen', 'personkey': '123'} {'name': 'ABC Tech', 'id': '767', 'startdate': '02-2020', 'enddate': '', 'personkey': '123'} {'str1': '101 MAIN ST', 'str2': '', 'city': 'NYC', 'state': 'NY', 'zip': '07789', 'empid': '767', 'personkey': '123'} {'str1': '111 POOLE ST', 'str2': '', 'city': 'NYC', 'state': 'NY', 'zip': '07780', 'empid': '767', 'personkey': '123'} {'name': 'XYZ Tech', 'id': '909', 'startdate': '06-2012', 'enddate': '01-2020', 'personkey': '123'} {'str1': '122 Main St', 'str2': '', 'city': 'NYC', 'state': 'NY', 'zip': '07789', 'empid': '909', 'personkey': '123'} {'str1': '199 Poole St', 'str2': '', 'city': 'NYC', 'state': 'NY', 'zip': '07780', 'empid': '909', 'personkey': '123'} {'type': 'Masters', 'school': 'ABC School', 'graduated': '12-14-2005', 'personkey': '123'} {'type': 'Bachelors', 'school': 'XYZ School', 'graduated': '12-14-2001', 'personkey': '123'} </code></pre> <ul> <li>Is it beneficial to create a class for each table (I will have a List of dicts for each table that I have to bulk store in Postgres to avoid multiple roundtrips) I am wanting to store in the database?</li> <li>Do I instantiate an object in the function <em>myfunction</em>?</li> <li>How best to load the data in Postgres in bulk? A Person class that has all the individual List of dicts (employer, person, office, education) as variables and a method to load the data into the database?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T14:47:01.460", "Id": "505808", "Score": "0", "body": "What happened to JASON KNIGHT in your example output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T16:08:38.937", "Id": "505813", "Score": "1", "body": "Edited him out to keep output short." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T14:26:14.740", "Id": "256191", "Score": "1", "Tags": [ "python", "performance", "object-oriented", "xml", "classes" ], "Title": "Parsing a large XML file and storing in Postgres efficiently using Pythonic code" }
256191
<p>Pretty simple 2-Dimensional Vector template with operators and two utility functions making use of C++20 concepts. Header-only templates, function inlining and operator overloading, etc. is not exactly my strong foot, so that's why i wrote this hoping to get some feedback.</p> <pre><code>#pragma once #include &lt;cmath&gt; #include &lt;type_traits&gt; namespace math { template&lt;typename T&gt; concept Arithmetic = std::is_arithmetic_v&lt;T&gt;; template&lt;Arithmetic T&gt; struct Vector2D { T X = 0; T Y = 0; Vector2D() = default; Vector2D(T x, T y); Vector2D(const Vector2D&lt;T&gt; &amp;other); inline T Magnitude() const; inline Vector2D&lt;T&gt; Normal() const; }; template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt;::Vector2D(T x, T y) : X(x), Y(y) {} template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt;::Vector2D(const Vector2D&lt;T&gt; &amp;other) : X(other.X), Y(other.Y) {} template&lt;Arithmetic T&gt; inline T Vector2D&lt;T&gt;::Magnitude() const { return std::sqrt(X * X + Y * Y); } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; Vector2D&lt;T&gt;::Normal() const { auto magnitude = Magnitude(); return Vector2D&lt;T&gt;(X / magnitude, Y / magnitude); } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; operator-(const Vector2D&lt;T&gt; &amp;vec) { return Vector2D&lt;T&gt;(-vec.X, -vec.Y); } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; operator+(const Vector2D&lt;T&gt; &amp;first, const Vector2D&lt;T&gt; &amp;second) { return Vector2D&lt;T&gt;(first.X + second.X, first.Y + second.Y); } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; operator-(const Vector2D&lt;T&gt; &amp;first, const Vector2D&lt;T&gt; &amp;second) { return Vector2D&lt;T&gt;(first.X + second.X, first.Y + second.Y); } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; operator*(const Vector2D&lt;T&gt; &amp;vec, const T factor) { return Vector2D&lt;T&gt;(vec.X * factor, vec.Y * factor); } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; operator*(const T factor, const Vector2D&lt;T&gt; &amp;vec) { return Vector2D&lt;T&gt;(factor * vec.X, factor * vec.Y); } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; operator/(const Vector2D&lt;T&gt; &amp;vec, const T divisor) { return Vector2D&lt;T&gt;(vec.X / divisor, vec.Y / divisor); } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; &amp;operator+=(Vector2D&lt;T&gt; &amp;first, const Vector2D&lt;T&gt; &amp;second) { first.X += second.X; first.Y += second.Y; return first; } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; &amp;operator-=(Vector2D&lt;T&gt; &amp;first, const Vector2D&lt;T&gt; &amp;second) { first.X -= second.X; first.Y -= second.Y; return first; } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; &amp;operator*=(Vector2D&lt;T&gt; &amp;vec, const T factor) { vec.X *= factor; vec.Y *= factor; return vec; } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; &amp;operator/=(Vector2D&lt;T&gt; &amp;vec, const T factor) { vec.X /= factor; vec.Y /= factor; return vec; } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; &amp;operator==(const Vector2D&lt;T&gt; &amp;first, const Vector2D&lt;T&gt; &amp;second) { return (first.X == second.X) &amp;&amp; (second.Y == second.Y); } template&lt;Arithmetic T&gt; inline Vector2D&lt;T&gt; &amp;operator!=(const Vector2D&lt;T&gt; &amp;first, const Vector2D&lt;T&gt; &amp;second) { return !(first == second); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T02:59:33.427", "Id": "505762", "Score": "0", "body": "Seems an almost trivial extension to make this a templated N-dimensional vector." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T07:04:35.257", "Id": "505775", "Score": "1", "body": "Your `Normal` function has a bug. If `Magnitude` returns zero you will crash with a divide by zero error. I would also argue that division is slow and instead you should pre-calculate the length to instead use inverse multiplication: `const auto length = Magnitude(); if(length > T{0}) { const auto inv_length = T{1} / length; return {X * inv_length, Y * inv_length} } return {};`" } ]
[ { "body": "<h2>Overview</h2>\n<p>Your code as written is perfectly fine (apart from the one bug in subtraction). Anything mentioned here is mainly to help future readers.</p>\n<p>You overcomplicated the design by adding constructors to <code>Vector2D</code>.<br />\nThe default constructors work perfectly and as expected in this type of situation.</p>\n<p>There is an argument to make operators members of the class rather than free standing functions. But either work.</p>\n<p>Your use of reference marker <code>&amp;</code> is very C like. You put it next to the variable rather than next to the type. This is very subjective style thing (usually dictated by your style guide). But C++ guides skew one way while C guides skew the other.</p>\n<pre><code> void doStuff(C const&amp; param)\n ^^^^^^^^ param has a type: C const&amp;\n\n void doStuff(C&amp; param)\n ^^ param has a type: C&amp;\n</code></pre>\n<p>This has happened because in C++ types are much more significant and important. So we pay much more attention to type things in C++.</p>\n<h2>Code Review</h2>\n<p>I am going to have to take your word that this is how concepts work. I look forward to this becoming available more consistently.</p>\n<pre><code> template&lt;typename T&gt;\n concept Arithmetic = std::is_arithmetic_v&lt;T&gt;;\n\n template&lt;Arithmetic T&gt;\n struct Vector2D\n {\n</code></pre>\n<hr />\n<p>Sure but not needed if you don't define other constructors (see below).</p>\n<pre><code> Vector2D() = default;\n</code></pre>\n<p>Sure but not needed as the brace initializers works and does this for you:</p>\n<pre><code> Vector2D(T x, T y);\n</code></pre>\n<p>Sure: But not needed the default copy constructor should work here.</p>\n<pre><code> Vector2D(const Vector2D&lt;T&gt; &amp;other);\n</code></pre>\n<p>Don't need to declare these <code>inline</code> here. It has no effect. You put the inline next to the method definition to make sure that the compiler does not give you multiple definition warnings.</p>\n<pre><code> inline T Magnitude() const;\n inline Vector2D&lt;T&gt; Normal() const;\n };\n</code></pre>\n<p>I would note that the <code>inline</code> keyword has nothing to do with in-lining the code. The compiler decides that without any help from the engineer (because it is better at than you).</p>\n<p>I would have simplified that to:</p>\n<pre><code> template&lt;Arithmetic T&gt;\n struct Vector2D\n {\n T x;\n T y;\n\n T Magnitude() const;\n Vector2D&lt;T&gt; Normal() const;\n };\n</code></pre>\n<hr />\n<h3>Arithmetic Operators:</h3>\n<p>There is a debate about if these should be members or free standing functions. Either is fine. I will not ding you for doing it one way when I would have done it another.</p>\n<p>There is an argument for making them free standing functions. But this is usually based around symmetry when using the operators.</p>\n<pre><code> R = X + Y;\n</code></pre>\n<p><strong>If you use methods:</strong></p>\n<p>If X is <code>Vector2D</code> and Y is not then the compiler can potentially convert Y into <code>Vector2D</code> and still apply the operation. But if it is the other way around: Y is <code>Vector2D</code> and X is not then the compiler can not convert X to a <code>Vector2D</code>.</p>\n<p><strong>If you use free standing functions:</strong></p>\n<p>Then if one parameter is <code>Vector2D</code> then the other can be converted to <code>Vector2D</code> and the function applied. This you have symmetrical conversions.</p>\n<p>This is fine if the types are &quot;Arithmetic&quot; in nature and can easily convert from anything into your type; this is not the case here with <code>Vector2D</code>. So this argument does not stand. I would also argue that this applies to most types; you have to have a very good argument that your type should allow auto conversion (most types don't and use <code>explicit</code> on one argument constructors to prevent this).</p>\n<p>Thus here you can use either technique and both are fine.</p>\n<p>I personally would have made them members of the class (the sole reason is to add clarity so you can read the class and see all the things you can do to change them). You could argue you can have the same affect by adding all the declarations for arithmetic operations as friends to the class (or simply put the declarations directly under the class (and I could not argue against his).</p>\n<p>Whatever way you decide. I would put the declarations beside the class and away from the definition so it is easy to see all the possible operations that apply to the class.</p>\n<hr />\n<p>Normally we implement <code>operator+</code> in terms of <code>operator+=</code>.</p>\n<pre><code> template&lt;Arithmetic T&gt;\n inline Vector2D&lt;T&gt; operator+(const Vector2D&lt;T&gt; &amp;first, const Vector2D&lt;T&gt; &amp;second)\n {\n return Vector2D&lt;T&gt;(first.X + second.X, first.Y + second.Y);\n }\n</code></pre>\n<p>I would write like this:</p>\n<pre><code> template&lt;Arithmetic T&gt;\n inline Vector2D&lt;T&gt;&amp; operator+=(Vector2D&lt;T&gt;&amp; first, Vector2D&lt;T&gt; const&amp; second)\n {\n first.X += second.X;\n first.Y += second.Y;\n return first;\n }\n\n template&lt;Arithmetic T&gt;\n inline Vector2D&lt;T&gt; operator+(Vector2D&lt;T&gt; first, Vector2D&lt;T&gt; const&amp; second)\n {\n // Note Pass first by value.\n // This automatically gets us a new version of the object.\n // The compiler will be able to detect if we can use move/copy\n // automatically to get this move version.\n //\n // We can then do the += on this new copy.\n // and perfectly return this value as output.\n return first += second;\n }\n</code></pre>\n<hr />\n<p>This seems like a bug:</p>\n<pre><code> template&lt;Arithmetic T&gt;\n inline Vector2D&lt;T&gt; operator-(const Vector2D&lt;T&gt; &amp;first, const Vector2D&lt;T&gt; &amp;second)\n {\n // Should you not subtract here:\n return Vector2D&lt;T&gt;(first.X + second.X, first.Y + second.Y);\n }\n</code></pre>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T00:01:27.903", "Id": "505741", "Score": "1", "body": "Defining `operator +` that way is a bad habit. It doesn’t matter in this particular case, but `friend X operator +(X left, X const& right) { return left += right; }` copies or moves the left operand as appropriate, avoiding unnecessary copies in case it was an rvalue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T00:17:28.087", "Id": "505743", "Score": "0", "body": "@RomanOdaisky I fixed the + operator. Did I get the description correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T00:36:26.687", "Id": "505744", "Score": "0", "body": "Yes, though the function body could have used a `return`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T00:38:41.380", "Id": "505745", "Score": "0", "body": "By the way, C++20 does fix the symmetry problems with operators defined as member functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:07:26.640", "Id": "505749", "Score": "0", "body": "“By the way, C++20 does fix the symmetry problems with operators defined as member functions.” As far as I know, that’s only for equality/relational operators. And it applies both to member and non-member versions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:20:04.890", "Id": "505752", "Score": "0", "body": "@indi I stand corrected. It seems non-relational operators are still best defined as friends." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T05:24:37.707", "Id": "505766", "Score": "0", "body": "@indi Do you have a link?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T18:26:12.513", "Id": "505829", "Score": "0", "body": "@MartinYork To something that says reordering *doesn’t* occur for non-equality/relational ops? No, I’d never heard the claim that it *does* before now. I do have links that describe reordering for `==` and `<=>` (and *only* those; other rel ops get *rewritten* to those, and *then* reordered)… that notably don’t mention it happening for any other ops. For example, [cppreference](https://en.cppreference.com/w/cpp/language/operators); note the first “since C++20” block under the table mentions rewriting… *only* for the eq/rel ops." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T18:26:23.063", "Id": "505830", "Score": "0", "body": "But if you think about it, reordering/rewriting generally doesn’t make sense. Consider `operator/(vec2d, double)`, a scaling operation. How could that be rewritten? Or even just consider `operator+(A, B)`… reordering would work for numeric types… but not strings. `==` is *always* commutative (assuming it’s doing something sensible), so reordering the operands makes sense. Similarly rewriting `a > b` with `b < a` (via `<=>`) also makes sense, generally." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T18:26:31.327", "Id": "505831", "Score": "0", "body": "[Barry Revzin has a nice long article describing `==`/`<=>` reordering/rewriting in minute detail](https://brevzin.github.io/c++/2019/07/28/comparisons-cpp20/), but again, he doesn’t explicitly say that *only* equality/relational ops get rewritten/reordered… though he strongly implies it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T20:18:19.340", "Id": "505840", "Score": "0", "body": "@indi The issue as I understand it isn’t about reordering. X::operator @(X) is asymmetric because when X is implicitly constructible from A, x@a works but a@x doesn’t. Also https://wg21.link/n4474 could come in handy to solve both this and std::forward(*this)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T20:59:57.650", "Id": "505841", "Score": "0", "body": "@RomanOdaisky Ah, my bad. I misunderstood what you meant by “symmetry”." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T19:10:55.047", "Id": "256199", "ParentId": "256193", "Score": "9" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/users/507/martin-york\">Martin York</a> provided a <a href=\"https://codereview.stackexchange.com/a/256199/177460\">great, in-depth answer</a>. I agree with all of their points.</p>\n<p>I want to mention a C++20 feature you may not be aware of, which is the new compiler-provided comparison operators. <a href=\"https://brevzin.github.io/c++/2019/07/28/comparisons-cpp20/\" rel=\"nofollow noreferrer\">This blog post</a> goes pretty in-depth on the details, but the highlights are:</p>\n<ul>\n<li>Comparison operators in C++20 can be inferred by the compiler for a given type, based on <code>operator==</code> and <code>operator&lt;=&gt;</code> (the new &quot;spaceship&quot; operator).\n<ul>\n<li>Defining <code>operator==</code> for a type allows inequality (!=) to be inferred for that type.</li>\n<li>Defining <code>operator&lt;=&gt;</code> for a type allows all comparison operators (&lt;, &lt;=, &gt;, &gt;=, ==, !=) to be inferred for that type.</li>\n</ul>\n</li>\n<li>The compiler-inferred definitions are both <code>constexpr</code> and <code>noexcept</code>!</li>\n<li>Parameter ordering is also inferred (so if you define <code>Foo::operator==(int)</code>, you get <code>Foo == int</code>, <code>int == Foo</code>, <code>Foo != int</code>, and <code>int != Foo</code> all in one).</li>\n<li>Both of these operators can be <code>default</code>ed. The default version will perform comparison on all class members in order of definition.</li>\n</ul>\n<p>What does this mean for you? In your <code>Vector2D</code> type, you can declare <code>bool operator==(const Vector2D&lt;T&gt;&amp;) const = default;</code> and the compiler will automatically generate both <code>operator==</code> and <code>operator!=</code>.\n<br/>\n<em>(Obviously, this only works if you can safely rely on the default comparison operators for your class members. In this case, your <code>operator==</code> and <code>operator!=</code> are already using default comparison on the class members, so this is not an issue for you.)</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T22:21:38.263", "Id": "505734", "Score": "1", "body": "I am aware about the operator<=>. From my understanding(haven't actually used it before) i would get all comparison operators including <, >, <=, >= from it. Since some of them don't make much sense for a Vector2 class i decided to not use it. Feel free to correct me if im wrong or if there is a way to supress unwanted operators." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:09:26.823", "Id": "505750", "Score": "2", "body": "Yes, if you default `operator<=>`, you’d get all equality and comparison operators. But as @cariehl describes, you can just define `operator==` to get all variations of (in)equality and *only* (in)equality. If you don’t want relational ops, just don’t define `operator<=>`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T21:03:28.730", "Id": "256203", "ParentId": "256193", "Score": "4" } }, { "body": "<ol>\n<li><p>Get rid of all constructors, the default ones do exactly the same, and given that C++20 includes <a href=\"https://wg21.link/p0960\" rel=\"nofollow noreferrer\">P0960</a>, you can initialize structs with parentheses.</p>\n</li>\n<li><p>Fix the return type of operator == and default it.</p>\n</li>\n<li><p>Get rid of operator !=, it’s generated automatically.</p>\n</li>\n<li><p>std::hypot is a thing.</p>\n</li>\n<li><p>If the return type isn’t auto, you can skip it in the return statement: <code>return {-X, -Y};</code></p>\n</li>\n<li><p>Express operators in terms of other operators where possible to minimize errors. Use @= to define @, use Vector * T to define T * Vector etc.</p>\n</li>\n<li><p>In particular, use the <code>X operator @(X left, X const&amp; right) { return left @= right; }</code> idiom, as it automatically uses the correct constructor, copy or move, for the left operand, as appropriate.</p>\n</li>\n<li><p>Consider limiting the type T to floating point or you’ll get funny magnitudes and normed values.</p>\n</li>\n<li><p>Finally, write some tests, they would have caught the <code>operator -</code> error, for example.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T00:27:04.697", "Id": "256209", "ParentId": "256193", "Score": "3" } } ]
{ "AcceptedAnswerId": "256199", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T15:01:36.610", "Id": "256193", "Score": "10", "Tags": [ "c++", "template", "c++20" ], "Title": "C++20 Vector2D Template" }
256193
<p>I have a program that alternates between 2 phases: <code>REST</code> and <code>REG</code>. During each phase, 2 <strong>positive</strong> quantities are computed <code>a</code> and <code>d</code>. By the end of a <code>REG</code> phase, I compute a score based on the previous <code>REG</code> and <code>REST</code> phases. This computation is very clumsy, and I would like a better, faster implementation (especially, I would like to get rid of the for loop).</p> <p><strong>Generate sample data:</strong></p> <pre><code>#%% Imports from scipy.interpolate import InterpolatedUnivariateSpline import numpy as np from matplotlib import pyplot as plt #%% Generate random data timestamps_REST = np.linspace(0, 10, 30, endpoint=True) a_REST = np.random.rand(30) d_REST = np.random.rand(30) timestamps_REG = np.linspace(11, 45, 80, endpoint=True) a_REG = np.random.rand(80) d_REG = np.random.rand(80) #%% Spline interpolation a_REST_spline = InterpolatedUnivariateSpline(timestamps_REST, a_REST, k=1) a_REG_spline = InterpolatedUnivariateSpline(timestamps_REG, a_REG, k=1) d_REST_spline = InterpolatedUnivariateSpline(timestamps_REST, d_REST, k=1) d_REG_spline = InterpolatedUnivariateSpline(timestamps_REG, d_REG, k=1) </code></pre> <p>In the sample data generated below, the quantities <code>a</code> and <code>d</code> are estimated at:</p> <ul> <li>30 points equally spaced for the <code>REST</code> phase</li> <li>80 points equally spaced for the <code>REG</code> phase</li> </ul> <p>The <code>REST</code> and <code>REG</code> phase duration/length are different, <code>0 to 10</code> for the <code>REST</code> phase and <code>11 to 45</code> for the REG phase.</p> <p>In practice, both the sampling rate and the duration are not constant. This is why I decided to use an interpolated spline to compute the integral of each signal later on.</p> <p><strong>Visualize/Plots</strong></p> <p>To visualize the data, you can use the snippet below:</p> <pre><code>#%% Plot f, ax = plt.subplots(2, 2, figsize=(10, 5)) ax[0, 0].set_title('REST', fontsize=20) ax[0, 1].set_title('REG', fontsize=20) for a in ax.flatten(): a.set_yticks([]) ax[0, 0].set_ylabel('a', fontsize=20) ax[1, 0].set_ylabel('d', fontsize=20) # Spline x-axis plot_spline_REST_timestamps = np.linspace(0, 10, 2000, endpoint=True) plot_spline_REG_timestamps = np.linspace(11, 45, 6800, endpoint=True) # a REST ax[0, 0].plot(timestamps_REST, a_REST, 'ro', ms=5) ax[0, 0].plot(plot_spline_REST_timestamps, a_REST_spline(plot_spline_REST_timestamps), 'b', lw=2) ax[0, 0].fill_between(plot_spline_REST_timestamps, a_REST_spline(plot_spline_REST_timestamps), color='b', alpha=0.3) # d Rest ax[1, 0].plot(timestamps_REST, d_REST, 'ro', ms=5) ax[1, 0].plot(plot_spline_REST_timestamps, d_REST_spline(plot_spline_REST_timestamps), 'teal', lw=2) ax[1, 0].fill_between(plot_spline_REST_timestamps, d_REST_spline(plot_spline_REST_timestamps), color='teal', alpha=0.3) # a REG ax[0, 1].plot(timestamps_REG, a_REG, 'ro', ms=5) ax[0, 1].plot(plot_spline_REG_timestamps, a_REG_spline(plot_spline_REG_timestamps), 'b', lw=2) ax[0, 1].fill_between(plot_spline_REG_timestamps, a_REG_spline(plot_spline_REG_timestamps), color='b', alpha=0.3) # d REG ax[1, 1].plot(timestamps_REG, d_REG, 'ro', ms=5) ax[1, 1].plot(plot_spline_REG_timestamps, d_REG_spline(plot_spline_REG_timestamps), 'teal', lw=2) ax[1, 1].fill_between(plot_spline_REG_timestamps, d_REG_spline(plot_spline_REG_timestamps), color='teal', alpha=0.3) </code></pre> <p><a href="https://i.stack.imgur.com/PkkCY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PkkCY.png" alt="sample data" /></a></p> <p><strong>Score computation: code to optimize</strong></p> <p>As said, I compute a score based on the integrals. The idea is to compute the score as:</p> <pre><code>max(0, Area(a_REG) - Area(a_REST)) + max(0, Area(d_REST) - Area(d_REG)) </code></pre> <p>where Area represents the colored area in the plot above, i.e. the area between the curve and 0, i.e. the integral. In simpler terms, the score increases if:</p> <ul> <li>the area in <em>blue</em> in the <code>REG</code> phase is larger than the area in <em>blue</em> in the <code>REST</code> phase</li> <li>the area in <em>teal</em> in the <code>REG</code> phase is smaller than the area in <em>teal</em> in the <code>REG</code> phase</li> </ul> <p><em>N.B: The integral computation can be changed to another method if need be.</em></p> <p>Now, instead of considering the entire duration at once, I want to compute this score by chunk, and to increase the score at the end of each chunk. Moreover, the baseline, which previously was the area during the <code>REST</code> phase is now computed by taking the median of the chunks area during the <code>REST</code> phase.</p> <p>The chunk version, below, needs some optimization..</p> <pre><code>#%% Score score = 0 # compute baseline for REST phase rest_chunks = np.linspace(timestamps_REST[0], timestamps_REST[-1], num=11, endpoint=True) rest_baselines = [[], []] for k, _ in enumerate(rest_chunks): if k == 0: continue rest_baselines[0].append(a_REST_spline.integral(rest_chunks[k-1], rest_chunks[k]) / (rest_chunks[k] - rest_chunks[k-1])) rest_baselines[1].append(d_REST_spline.integral(rest_chunks[k-1], rest_chunks[k]) / (rest_chunks[k] - rest_chunks[k-1])) rest_baseline = (np.median(rest_baselines[0]), np.median(rest_baselines[1])) # Score per chunks reg_chunks = np.linspace(timestamps_REG[0], timestamps_REG[-1], num=21, endpoint=True) for k, _ in enumerate(reg_chunks): if k == 0: continue # alpha score += np.max((a_REG_spline.integral(reg_chunks[k-1], reg_chunks[k]) / (reg_chunks[k] - reg_chunks[k-1])) - rest_baseline[0], 0) * 50 * 10**13 # delta score += np.max(rest_baseline[0] - (d_REG_spline.integral(reg_chunks[k-1], reg_chunks[k]) / (reg_chunks[k] - reg_chunks[k-1])), 0) * 50 * 10**13 </code></pre> <p>Finally, you can notice above that the chunk size depends on the phase duration and on the <code>num</code> parameter in the <code>np.linspace()</code> function. Instead, I would much prefer to define a setting <code>chunk_size</code>, and then if the duration is larger than the <code>chunk_size</code> the algorithms cut the signal in chunks of size <code>chunk_size</code>; with possibly the last chunk being shorter. As this is not really an optimization aspect, let's call this a bonus to this problem.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T15:15:56.050", "Id": "256194", "Score": "0", "Tags": [ "python", "performance" ], "Title": "Compute integral of spline by chunk more efficiently" }
256194
<p>I need to read a vector of e.g. integers from a stream, usually from stdin but sometimes also from a file. The input is always less than a megabyte, and is sometimes separated by commas and sometimes by newlines.</p> <p>I'm calling the code directly from my main function, so I'm more concerned with returning a human readable error rather than something that can be caught and recovered from programmatically, hence I'm using <code>String</code> as the error type.</p> <pre class="lang-rust prettyprint-override"><code>pub fn parse_vector&lt;T: BufRead, S: FromStr&gt;(buf: T, sep: u8) -&gt; Result&lt;Vec&lt;S&gt;, String&gt; { buf.split(sep) .enumerate() .filter_map(|(i, entry)| { let entry_nr = i + 1; let entry = match entry.map(String::from_utf8) { Err(e) =&gt; return Err(format!(&quot;Cannot read entry {}, {}.&quot;, entry_nr, e)).into(), Ok(Err(e)) =&gt; return Err(format!(&quot;Cannot read entry {}, {}.&quot;, entry_nr, e)).into(), Ok(Ok(v)) =&gt; v, }; let trimmed = entry.trim(); if trimmed.is_empty() { None } else { Some( trimmed .parse::&lt;S&gt;() .map_err(|_| format!(&quot;Cannot parse entry {}: '{}'&quot;, entry_nr, entry)), ) } }) .collect() } </code></pre> <p>The above code works as far as I can tell, but I'm wondering if there's a nicer way to deal with the mess in the <code>match</code> expression. The functions <code>from_utf8</code> and <code>split</code> return different error types, but both implement <code>Display</code> so maybe there's some elegant way to eliminate some code duplication there that I don't know about (I'm new to rust, coming from c++).</p> <ul> <li>What are my options to make this code more readable?</li> <li>Is it considered bad practice to return <code>String</code> as an error type?</li> </ul>
[]
[ { "body": "<blockquote>\n<p>I'm calling the code directly from my main function, so I'm more\nconcerned with returning a human readable error rather than something\nthat can be caught and recovered from programmatically, hence I'm\nusing <code>String</code> as the error type.</p>\n<p>[...]</p>\n<ul>\n<li>Is it considered bad practice to return <code>String</code> as an error type?</li>\n</ul>\n</blockquote>\n<p>Yes, it is generally considered bad practice to return <code>Result&lt;_, String&gt;</code> when the error returned is formatted from other errors. The recommended approach is to define an <code>enum</code> and implement <code>From</code>, <code>Display</code>, and <code>Error</code>: (using the <a href=\"https://docs.rs/thiserror/1.0.24/thiserror/\" rel=\"nofollow noreferrer\"><code>thiserror</code></a> crate for simplicity)</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use thiserror::Error;\n\n#[derive(Debug, Error)]\npub enum Error {\n #[error(&quot;cannot read entry {entry_no}&quot;)]\n Io { entry_no: usize, source: std::io::Error },\n #[error(&quot;cannot read entry {entry_no}&quot;)]\n Encoding { entry_no: usize, source: std::string::FromUtf8Error },\n // ...\n}\n</code></pre>\n<blockquote>\n<p>The above code works as far as I can tell, but I'm wondering if\nthere's a nicer way to deal with the mess in the <code>match</code> expression. The\nfunctions <code>from_utf8</code> and <code>split</code> return different error types, but\nboth implement <code>Display</code> so maybe there's some elegant way to\neliminate some code duplication there that I don't know about (I'm new\nto rust, coming from C++).</p>\n</blockquote>\n<p>Your options include:</p>\n<ul>\n<li><p>methods on <code>Option</code> and <code>Result</code>, like <a href=\"https://doc.rust-lang.org/std/result/enum.Result.html#method.and_then\" rel=\"nofollow noreferrer\"><code>Result::and_then</code></a> and <a href=\"https://doc.rust-lang.org/std/option/enum.Option.html#method.ok_or_else\" rel=\"nofollow noreferrer\"><code>Option::ok_or_else</code></a>;</p>\n</li>\n<li><p>the <a href=\"https://doc.rust-lang.org/stable/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator\" rel=\"nofollow noreferrer\"><code>?</code> operator</a>; and</p>\n</li>\n<li><p>using <code>.zip(1..)</code> instead of <code>.enumerate()</code> to get rid of that <code>+ 1</code>,</p>\n</li>\n</ul>\n<p>plus potentially other things that didn't immediately come to mind.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T12:13:00.257", "Id": "256333", "ParentId": "256196", "Score": "3" } } ]
{ "AcceptedAnswerId": "256333", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T16:46:04.627", "Id": "256196", "Score": "4", "Tags": [ "error-handling", "rust" ], "Title": "Parsing a u8 separated vector of FromStr from a BufRead" }
256196
<pre><code>def MinimumSwaps(Queue): MinSwaps = 0 for i in range(len(Queue) - 1): if Queue[i] != i+1: for j in range(i+1,len(Queue)): if Queue[j] == i+1: Queue[i], Queue[j] = Queue[j], Queue[i] MinSwaps += 1 break else: continue return MinSwaps def main(): Result = MinimumSwaps([7, 1, 3, 2, 4, 5, 6]) print(Result) if __name__ == &quot;__main__&quot;: main() </code></pre> <p><strong>The question</strong>: You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.</p> <p>The issue is that what I have provided is inefficient and fails on very large arrays, however Ive tried to optimise it as much as I can and im not aware of another technique to use. This question is likely related to a particular sorting algorithm but is there any way to modify the above code to make it faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T17:14:14.463", "Id": "505694", "Score": "0", "body": "how large is n?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T17:30:18.003", "Id": "505697", "Score": "0", "body": "100,000 is the max." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T17:34:38.920", "Id": "505698", "Score": "0", "body": "Unordered array of consecutives..?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T17:40:42.100", "Id": "505700", "Score": "0", "body": "Yes, just consider it a randomised array of integers that were originally consecutive. But it was described as I posted in the question. An example is given in the main() function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T06:16:57.720", "Id": "505769", "Score": "0", "body": "Is the input a Queue?" } ]
[ { "body": "<p>Instead of <em>searching</em> for the value that belongs at <code>Queue[i]</code> to swap it there, just swap the value that <em>is</em> there to where that belongs:</p>\n<pre><code>def MinimumSwaps(Queue):\n MinSwaps = 0\n for i in range(len(Queue) - 1):\n while Queue[i] != i + 1:\n j = Queue[i] - 1\n Queue[i], Queue[j] = Queue[j], Queue[i]\n MinSwaps += 1\n return MinSwaps\n</code></pre>\n<p>This improves the performance to <span class=\"math-container\">\\$O(1)\\$</span> for using a value instead of the <span class=\"math-container\">\\$O(n)\\$</span> for searching. And thus total performance to <span class=\"math-container\">\\$O(n)\\$</span> instead of your original <span class=\"math-container\">\\$O(n^2)\\$</span>. Still using only O(1) extra space.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T20:16:02.677", "Id": "256201", "ParentId": "256197", "Score": "6" } }, { "body": "<p>Your code is <span class=\"math-container\">\\$O(n^2)\\$</span> because of the inner loop.</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>for j in range(i+1,len(Queue)):\n if Queue[j] == i+1:\n # inner\n</code></pre>\n</blockquote>\n<p>We can change this to be <span class=\"math-container\">\\$O(1)\\$</span> by making a lookup table of where <span class=\"math-container\">\\$i\\$</span>'s location is.\nWe can build a dictionary to store these lookups.</p>\n<pre class=\"lang-py prettyprint-override\"><code>indexes = {value: index for index, value in enumerate(Queue)\n</code></pre>\n<p>We can then just swap these indexes with your existing inner code to get <span class=\"math-container\">\\$O(n)\\$</span> performance.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def MinimumSwaps(Queue):\n indexes = {value: index for index, value in enumerate(Queue)}\n MinSwaps = 0\n for i in range(len(Queue) - 1):\n i_value = Queue[i]\n if i_value != i+1:\n j = indexes[i+1]\n j_value = Queue[j]\n Queue[i], Queue[j] = Queue[j], Queue[i]\n indexes[i_value], indexes[j_value] = indexes[j_value], indexes[i_value]\n MinSwaps += 1\n else:\n continue\n return MinSwaps\n</code></pre>\n<p>There is potentially performance on the table by using a dictionary as a lookup table rather than a list. Whilst both have the same algorithmic complexity. To address this we can just build <code>indexes</code> as a list.</p>\n<pre class=\"lang-py prettyprint-override\"><code>indexes = [None] * len(Queue)\nfor index, value in enumerate(Queue):\n indexes[value] = index\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T06:21:36.157", "Id": "505771", "Score": "0", "body": "Why this answer get downvoted? It may not be the best idea. But it at least works (boost the performance by reducing the big-O time complexity of original code)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T12:07:03.993", "Id": "505791", "Score": "0", "body": "@tsh Another user has taken a quite unhealthy dislike to me. So downvoted straight after seeing who posted the answer. The second, IDK. As you say the answer answered the question by improving the performance of the code, could my answer be poorly worded or something? IDK. Speculating probably isn't a good idea unless I get a couple more downvotes. So in the mean time I'll just assume [Tim lost his keys again](https://meta.stackexchange.com/a/215397)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T13:16:18.970", "Id": "505794", "Score": "0", "body": "@tsh I see the OP's way as going in the wrong direction (solving *towards* the current list spot instead of the simpler and faster *away* from the current list spot) and thus this solution as *running* in the wrong direction, with even *more complicated* code and less space-efficiency. Plus just recently they [made a fuss](https://codereview.stackexchange.com/questions/255575/determine-the-longest-segment-of-integers-within-an-inclusive-range-that-doesnt/255580#comment504340_255580) about set operations being O(n) instead of O(1), which they then should've done here for the dict as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T13:17:18.003", "Id": "505795", "Score": "0", "body": "@superbrain \"which they then should've done here\" I did, look at the bottom of the post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T13:18:02.283", "Id": "505796", "Score": "0", "body": "Where? You even explicitly say \"We can change this to be O(1)\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T13:18:29.323", "Id": "505797", "Score": "0", "body": "\"There is potentially performance on the table by using a dictionary as a lookup table rather than a list.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T13:19:44.700", "Id": "505798", "Score": "0", "body": "You must've forgotten your \"Whilst both have the same algorithmic complexity\" directly following that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T13:22:45.890", "Id": "505799", "Score": "0", "body": "@superbrain No, I've not forgotten that. To many they do have the same algorithmic complexity, and my answer is targeted to the level of the asker where they do. It's like when a teacher teaches that \"there are three states of matter\" when _that's obviously a lie_. A large part of teaching is not being 100% right it's about expanding the capabilities of the student without overwhelming them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T13:29:15.160", "Id": "505800", "Score": "0", "body": "It shows that that \"performance on the table\" refers to the constant factor that one would expect between dict and list, so you can't seriously consider that pointing out the O(n) vs O(1) thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T13:34:38.020", "Id": "505802", "Score": "0", "body": "@superbrain Yeah, there is, as you've said, more than one reason that a list would be superior to a dictionary here. When I talk about \"performance\" there it arguably doesn't have much to do with Big-O. I'm pretty sure you know that performance and Big-O are very different in Python. I recall you got an \\$O(n^2)\\$ algorithm to be faster than an \\$O(n)\\$ one with `.index` or something. There are many reasons list is better than dict." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T01:16:30.263", "Id": "505854", "Score": "0", "body": "@superbrain I would agree that there are better ways to archive the task. But... The upvote button suggests \"this answer is useful\" and downvote button suggests \"this answer is not useful\". Since OP tagged this question with [tag:time-limit-exceeded], and this post does boost the performance by reducing running time from \\$O(n^2)\\$ into \\$O(n)\\$. This answer may solve TLE issue. So it is definitely useful. It would be fair to upvote another answer (which is better) but not this one. But I don't think it is the reason to downvote this one. That's what I meant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T01:45:51.510", "Id": "505855", "Score": "0", "body": "@tsh I appreciate your comment. I personally am fine with being downvoted for whatever reason superb rain has. \"[It's normally recommended to vote on the quality of the post, not the user. And so some may disagree with your opinion if you change it because of the user. But these users have their own vote buttons that they can use.](https://codereview.meta.stackexchange.com/a/9178)\" - me from almost two years ago :)" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T21:16:06.853", "Id": "256204", "ParentId": "256197", "Score": "1" } } ]
{ "AcceptedAnswerId": "256201", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T17:03:09.340", "Id": "256197", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "time-limit-exceeded" ], "Title": "Sorting Algorithms Optimisation Python" }
256197
<p>Compiler is g++ 4.2. I'm new to C++, but I've done a lot of data science, web scraping, and some socketing stuff in Python. This code generates the nth Fibonacci number, either with a naive implementation or with caching.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;unordered_map&gt; #define BIG unsigned long long int std::unordered_map&lt;int, BIG&gt; umap; int fib(int n) { if (n &lt; 2) { return n; } return fib(n-1) + fib(n-2); } BIG fib_with_memo(int n) { if (umap.find(n) == umap.end()) { // if F_n not in cache, calculate, cache, and return it BIG val = fib_with_memo(n-1) + fib_with_memo(n-2); umap[n] = val; return val; } return umap[n]; // otherwise return the cached value } int main(int argc, char** argv) { umap[0] = 0; umap[1] = 1; int input = std::stoi( std::string(argv[1]) ); std::cout &lt;&lt; fib_with_memo(input) &lt;&lt; std::endl; return 0; } </code></pre> <p>I used a <code>std::unordered_map</code> (hash table) because its lookup/insertion times are <span class="math-container">\$O(1)\$</span> (compared to the <code>std::map</code>, which has <span class="math-container">\$O(log(n))\$</span> for both.)</p>
[]
[ { "body": "<blockquote>\n<p>Compiler is g++ 4.2.</p>\n</blockquote>\n<p>Yikes. That compiler is <em>ancient</em>. I’ve met competitive programmers younger than that compiler. If you’re planning to do any serious C++ programming, you really should look into upgrading your toolchain, if possible.</p>\n<pre><code>#define BIG unsigned long long int\n</code></pre>\n<p>This is absolutely the wrong way to create a new type.</p>\n<p>First, there is a trend in C++ to avoid the preprocessor completely. So, no <code>#define</code>s, no <code>#if</code>s, and so on. It is <em>ALMOST</em> completely unnecessary in the most recent version (C++20), but even in C++11 it is almost completely avoidable.</p>\n<p>Rather than a <code>#define</code>, you should use a type alias:</p>\n<pre><code>using BIG = unsigned long long int;\n</code></pre>\n<p>But there’s one more problem. By convention, <code>ALL_CAPS</code> variable names are reserved for preprocessor macros… which basically means you should never use them. That means you should do:</p>\n<pre><code>using big = unsigned long long int;\n</code></pre>\n<p>Or, even better, choose a more descriptive name, like:</p>\n<pre><code>using big_uint = unsigned long long int;\n</code></pre>\n<p>But even better still would be to create your own namespace, and put everything—this type alias and all the Fibonacci functions—in there:</p>\n<pre><code>namespace your_ns {\n\nusing big_t = unsigned long long int;\n\nint fib(int n) {\n // ... etc. ...\n\n} // your_ns\n</code></pre>\n<p>Now I know your focus is on the memoized version of the Fibonacci algorithm, but the non-memoized one is really problematic:</p>\n<pre><code>int fib(int n) {\n if (n &lt; 2) {\n return n;\n }\n return fib(n-1) + fib(n-2);\n}\n</code></pre>\n<p>Imagine what happens if you call <code>fib(5)</code>. Internally, that results in two calls to <code>fib(4)</code> and <code>fib(3)</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>fib(5)\n ↓\nfib(4) + fib(3)\n</code></pre>\n<p>Except… <code>fib(4)</code> <em>also</em> degrades to <code>fib(3)</code> and <code>fib(2)</code>, while <code>fib(3)</code> degrades to <code>fib(2)</code> and <code>fib(1)</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>fib(5)\n ↓\nfib(4) + fib(3)*\n ↓\nfib(3)* + fib(2) + fib(2) + fib(1)\n</code></pre>\n<p>As you can see, <code>fib(3)</code> is called <em>twice</em>. And it gets even worse, because <code>fib(3)</code> degrades to <code>fib(2)</code> and <code>fib(1)</code>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>fib(5)\n ↓\nfib(4) + fib(3)\n ↓\nfib(3) + fib(2)* + fib(2)* + fib(1)\n ↓\nfib(2)* + fib(1) + fib(1) + fib(0) + fib(1) + fib(0) + 1\n</code></pre>\n<p>Now you can see <code>fib(2)</code> is called <em>three</em> times. Each one of those times becomes <code>fib(1)</code> and <code>fib(0)</code>.</p>\n<pre class=\"lang-none prettyprint-override\"><code>fib(5)\n ↓\nfib(4) + fib(3)\n ↓\nfib(3) + fib(2) + fib(2) + fib(1)\n ↓\nfib(2) + fib(1) + fib(1) + fib(0) + fib(1) + fib(0) + 1\n ↓\nfib(1) + fib(0) + 1 + 1 + 1 + 1 + 1 + 1\n</code></pre>\n<p>So the net result of a single call to <code>fib(5)</code> is:</p>\n<ul>\n<li>1 call to <code>fib(4)</code></li>\n<li>2 calls to <code>fib(3)</code></li>\n<li>3 calls to <code>fib(2)</code></li>\n<li>5 calls to <code>fib(1)</code></li>\n<li>3 calls to <code>fib(0)</code></li>\n</ul>\n<p>And that’s just <code>fib(5)</code>. Imagine how many repeated calls you’ll get with <code>fib(50)</code>.</p>\n<p>(This is obviously not such a big problem with the memoized version… but it’s still a problem!)</p>\n<p>What you really want to look into is the <strong>tail-recursive Fibonacci algorithm</strong>. I’m not going to work it out for you, but I’ll give you the interface:</p>\n<pre><code>auto fib_impl(int n, big_t a, big_t b)\n{\n // ...\n}\n\nauto fib(int n)\n{\n // are you sure you don't want to check for negative numbers?\n if (n &lt; 2)\n return big_t(n); // note: this line won't compile if you used BIG; this is why the preprocessor sucks\n\n return fib_impl(n, 0, 1);\n}\n</code></pre>\n<p>Now you don’t say what version of C++ you’re working with, but if it’s one of the more recent versions, then you can make all of this <code>constexpr</code>. That means that, when possible, the function may be computed at compile time, meaning it will have (effectively) <em>zero</em> run-time cost.</p>\n<pre><code>BIG fib_with_memo(int n) {\n if (umap.find(n) == umap.end()) { // if F_n not in cache, calculate, cache, and return it\n BIG val = fib_with_memo(n-1) + fib_with_memo(n-2);\n umap[n] = val;\n return val;\n }\n return umap[n]; // otherwise return the cached value\n}\n</code></pre>\n<p>Now, since <code>umap</code> has no purpose outside of this function, it makes more sense to hide it within the function as a static variable. If you don’t know what function static variables are, they’re basically global variables, but only visible within the function.</p>\n<p>While you’re at it, you might as well replace:</p>\n<pre><code>umap[0] = 0;\numap[1] = 1;\n</code></pre>\n<p>with:</p>\n<pre><code>umap = std::unordered_map&lt;int, big_t&gt;{{0, 0}, {1, 1}};\n</code></pre>\n<p>Why? Because this will be <em>MUCH</em> more efficient. The first way means that each line first searches the map for the key, then creates the new pair. The second way doesn’t bother with the search, but rather just creates the two pairs directly.</p>\n<p>So now your <code>fib_with_memo()</code> could look like this:</p>\n<pre><code>auto fib_with_memo(int n) {\n // umap is constructed only once, the first time the function is called,\n // and initialized with {0, 0} and {1, 1}.\n static auto umap = std::unordered_map&lt;int, big_t&gt;{{0, 0}, {1, 1}};\n\n // note everything else is exactly the same (except I replaced the BIG\n // with auto)\n\n if (umap.find(n) == umap.end()) { // if F_n not in cache, calculate, cache, and return it\n auto val = fib_with_memo(n-1) + fib_with_memo(n-2);\n umap[n] = val;\n return val;\n }\n return umap[n]; // otherwise return the cached value\n}\n</code></pre>\n<p>Another small fix is that once you’re in that <code>if</code> block, you know for a fact that <code>n</code> isn’t in the map. So rather than doing <code>umap[n]</code>, you can emplace the new pair directly:</p>\n<pre><code> if (umap.find(n) == umap.end()) {\n auto val = fib_with_memo(n-1) + fib_with_memo(n-2);\n umap.emplace(n, val);\n return val;\n }\n</code></pre>\n<p>Depending on your implementation, that might be more efficient.</p>\n<p>Another possibly major optimization comes from the fact that you use <code>find()</code>… and then just discard the result. Why not use it?</p>\n<pre><code> if (auto p = umap.find(n); p == umap.end())\n {\n // we didn't find n\n auto val = fib_with_memo(n-1) + fib_with_memo(n-2);\n umap.emplace(n, val);\n return val;\n }\n else\n {\n // we found n\n return p-&gt;second;\n }\n</code></pre>\n<p>So this is about where we’re at right now:</p>\n<pre><code>auto fib_with_memo(int n) {\n static auto umap = std::unordered_map&lt;int, big_t&gt;{{0, 0}, {1, 1}};\n\n if (auto p = umap.find(n); p == umap.end())\n auto val = fib_with_memo(n-1) + fib_with_memo(n-2);\n umap.emplace(n, val);\n return val;\n }\n else\n {\n // we found n\n return p-&gt;second;\n }\n}\n</code></pre>\n<p>Now we get to the <em>real</em> problem: the same issue as with the non-memoized version, where you’re calling the same function over and over and over. The fix is the same as with the non-memoized version: refactor:</p>\n<pre><code>auto fib_with_memo_impl(int n, big_t a, big_t b) {\n static auto umap = std::unordered_map&lt;int, big_t&gt;{{0, 0}, {1, 1}};\n\n if (auto p = umap.find(n); p == umap.end())\n auto val = // actual algorithm to calculate fib here\n umap.emplace(n, val);\n return val;\n }\n else\n {\n // we found n\n return p-&gt;second;\n }\n}\n\nauto fib_with_memo(int n) {\n // are you sure you don't want to check for n &lt; 0?\n\n // trivial solutions, don't even bother diving into the calculation\n if (n &lt; 2)\n return big_t(n);\n\n return fib_with_memo_impl(n, 0, 1);\n}\n</code></pre>\n<p>It’s up to you to implement the actual Fibonacci calculation there (you have <code>a</code> and <code>b</code> to work with). But otherwise, that should be a drop-in replacement for your current design, except orders of magnitude faster.</p>\n<h1>An alternative design</h1>\n<p>As you said:</p>\n<blockquote>\n<p>I used a <code>std::unordered_map</code> (hash table) because its lookup/insertion times are <span class=\"math-container\">\\$O(1)\\$</span> (compared to the <code>std::map</code>, which has <span class=\"math-container\">\\$O(log(n))\\$</span> for both.)</p>\n</blockquote>\n<p>Unfortunately, this thinking is misguided.</p>\n<p>It turns out that due to the way modern processors work—particularly with caching—that big-O notation can be <em>WILDLY</em> misleading. I recall that the inventor of C++ himself was floored when someone showed him that a <code>std::list</code>, which has <span class=\"math-container\">\\$O(1)\\$</span> insertion in the middle, is <em>slower</em> than a <code>std::vector</code>, which has <span class=\"math-container\">\\$O(n)\\$</span> insertion in the middle, even for <em>huge</em> numbers of elements.</p>\n<p>Forget all that theory crap, and instead take a step back and consider your actual problem. Imagine that you’ve called <code>fib_with_memo(10)</code>. Okay, now what would you expect to see in the memo-map?</p>\n<p>It would be this, right?:</p>\n<pre><code>0 → 0\n1 → 1\n2 → 1\n3 → 2\n4 → 3\n5 → 5\n6 → 8\n7 → 13\n8 → 21\n9 → 34\n10 → 55\n</code></pre>\n<p>Now look at the keys. It’s just 0 to 10, right? In order, with no holes. Just like an index.</p>\n<p>So… why do you need a map? You’re just “mapping” an index to a value. That’s just what a basic array, or a vector, does.</p>\n<p>Let’s imagine that we’re using a vector for the memoizing, with the “key” just being the index. That means after memoizing <code>fib_with_memo(10)</code>, the vector would contain:</p>\n<pre><code>[index 0 ] → 0\n[index 1 ] → 1\n[index 2 ] → 1\n[index 3 ] → 2\n[index 4 ] → 3\n[index 5 ] → 5\n[index 6 ] → 8\n[index 7 ] → 13\n[index 8 ] → 21\n[index 9 ] → 34\n[index 10] → 55\n</code></pre>\n<p>So, after <code>fib_with_memo(10)</code>, the vector contains 11 elements, and the element at index <code>n</code>—or, <code>vec[n]</code>—is the nth Fibonacci number.</p>\n<p>Simple, right?</p>\n<p>So how do you tell whether a number is already memoized? Again, simple, just check the vector’s size. If we call <code>fib_with_memo(13)</code>, the vector must have <em>at least</em> 14 elements in it for <code>vec[13]</code> to be valid. So:</p>\n<pre><code>if (vec.size() &gt; n)\n return vec[n];\nelse\n // calculate the nth fibonacci number\n</code></pre>\n<p>In fact, the implementation becomes trivial, too. That’s because if the function is called with an unmemoized <code>n</code>, all you need to do is resize the vector to <code>n + 1</code>, and fill in all the numbers between the old size and the new size. Something like:</p>\n<pre><code>auto fib_with_memo(int n) {\n // are you sure you don't want to check for n &lt; 0?\n\n // trivial solutions, don't even bother diving into the calculation\n if (n &lt; 2)\n return big_t(n);\n\n static auto vec = std::vector&lt;big_t&gt;{0, 1}; // start with fib(0) and fib(1)\n\n // note that if you really want, you could start with more than just\n // 0 and 1 - after testing your real-world use case, you could determine\n // that you will need, say, up to fib(8), so you could precompute that\n // much and put it in the vector initializer list above\n //\n // if you make the non-memoized fib function constexpr, then you could\n // even be *really* clever, and do something like:\n // static auto vec = std::vector{fib(0), fib(1), fib(2), fib(3), ...\n // for as many precomputed values as you like.\n //\n // and then you could be *REALLY* clever (if you’re using a more modern\n // version of c++), and do something like:\n // static auto vec = [](auto initial_size) {\n // auto v = std::vector&lt;big_t&gt;(std::min(2, initial_size + 1));\n // v[0] = 0;\n // v[1] = 1;\n //\n // for (auto p = std::next(v.begin(), 2); p != v.end(); ++p)\n // *p = *(p - 1) + *(p - 2);\n //\n // return v;\n // }(4); // 4 to calculate fib(0) though fib(4), but you can use any number\n // but that's getting *really* fancy.\n\n // memoized, so use cached value\n if (vec.size() &gt; n)\n return vec[n];\n\n // not memoized, so calculate all the values between what's been cached,\n // and what's desired\n\n auto old_size = vec.size();\n vec.resize(n + 1);\n\n // now fill in everything from vec[old_size] to vec[n] inclusive,\n // where vec[i] = vec[i - 1] + vec[i - 2]\n\n return vec[n];\n}\n</code></pre>\n<p>Obviously I haven’t profiled this design, but I’d bet it is hundreds, if not <em>thousands</em> of times faster than a similar design using a hash map.</p>\n<h1>Questions</h1>\n<h2>Difference between a macro and a type alias</h2>\n<p>When you do:</p>\n<pre><code>#define type long double\n</code></pre>\n<p>you’re talking to the <em>preprocessor</em> here… not the compiler.</p>\n<p>The preprocessor is stupid (as in, unintelligent), it doesn’t understand C++ (often the same preprocessor is used for C, C++, and sometimes even other languages, like Objective-C, and sometimes Fortran, etc.). It just deals with meaningless tokens. In this case, it just does a blind textual substitution. Everywhere <code>type</code> appears in the code, it just gets literally replaced with <code>long double</code>—literally as if you manually did copy-paste—with no regard as to whether that makes sense.</p>\n<p>To see where that causes problems, consider the following code:</p>\n<pre><code>struct thing\n{\n std::string name;\n std::string type;\n};\n\ntype value =\n type(0);\n</code></pre>\n<p>Everywhere <code>type</code> appears gets replaced with <code>long double</code>, so…:</p>\n<pre><code>struct thing\n{\n std::string name;\n std::string long double; // compile error\n};\n\nlong double value =\n long double(0); // compile error\n</code></pre>\n<p>Note that it didn’t just replace <code>type</code> when it is actually naming a type—which can still cause syntax errors, as it does for the second error above—it also replaced <code>type</code> when it was the name of a variable in the class. That’s why the preprocessor is so dangerous. It’s dumb. It’s indiscriminate. It blindly replaces <em>everything</em>, even when it makes no sense.</p>\n<p>Now, when you do:</p>\n<pre><code>using type = long double;\n</code></pre>\n<p>you’re talking to the <em>compiler</em> here, not the preprocessor, and that makes all the difference.</p>\n<p>This creates a type alias that the compiler understands. The compiler understands C++. The compiler doesn’t just blindly replace text, it knows when <code>type</code> is actually naming a type (and it’s not a variable name, for example), and even knows <em>which</em> type it’s naming (because <code>namespace_1::type</code> may not be the same as <code>namesapce_2::type</code>), and it does the replacement intelligently.</p>\n<p>So when the compiler sees the original code:</p>\n<pre><code>struct thing\n{\n std::string name;\n std::string type;\n};\n\ntype value =\n type(0);\n</code></pre>\n<p>it will <em>not</em> replace the <code>type</code> in class <code>thing</code>, because that’s not a type, it’s a variable name. And it <em>will</em> replace the <code>type</code> in the last two lines… <em>but</em> not simply by literally replacing the text (which would break the cast on the last line). Instead, it will do the replacement intelligently. <code>value</code> will be a <code>long double</code>, and the last line is casting a <code>0</code> (an <code>int</code>) to a <code>long double</code>… everything just works.</p>\n<p>In summary, the preprocessor is dumb. It just does blind text replacement, with no regard for what that text actually <em>means</em>… which often results in breaking code. By contrast, the compiler actually understands C++, so it knows when something is actually a type and when it’s not—and even <em>which</em> type it is—so it can do type substitutions intelligently, and not break code.</p>\n<h2>Refactored code</h2>\n<p>The standard on CodeReview is not to re-review code in the same question, but rather to post a new review request with the new code. So I can’t re-review your refactored code here. BUT! What I can do is give you suggestions to help you in your refactoring, and in general.</p>\n<p>The number one most important thing you can do when coding, not just in this case, but <em>always</em>, is <strong>WRITE TESTS</strong>. This is the absolute most important skill as a programmer you could ever develop. If I were hiring, and I had two candidates, and one wrote tests and the other didn’t… I wouldn’t even look at the second, I wouldn’t even give them a shot, regardless of how “good” a coder they might be. A coder that doesn’t write tests would be worse than useless to me… yes <em>worse</em> than useless, because they’d actually be a net maintenance <em>burden</em>. I’d literally rather hire nobody than hire someone who doesn’t write tests.</p>\n<p>Even if you’re just doing hobby programming, you should get in the habit of writing tests. I swear it will change your life. It makes everything <em>so much easier</em>. And you no longer have to wonder “does my code work?” You’ll just <em>know</em>. And if someone points out a bug you missed… no problem, just add a new test case that catches the bug, then fix it, and now you’re even <em>more</em> sure your code works.</p>\n<p>Testing is <em>so</em> important, that I even recommend writing the tests <em>before</em> you write the first line of “real” code.</p>\n<p>The first thing you should do is look into a proper testing system. I use Boost.Test but… it’s <em>extremely</em> heavyweight. (I mean, it’s awesome—by <em>far</em> the most powerful testing system—but, yeah, it’s not trivial to set up.) You might like <a href=\"https://github.com/catchorg/Catch2\" rel=\"nofollow noreferrer\">Catch2</a>. GoogleTest is another option but… meh.</p>\n<p>The easiest way to set up Catch2 (other than using your system package manager, if you’re on Linux) is to download the two files mentioned at <a href=\"https://github.com/catchorg/Catch2/blob/devel/docs/tutorial.md#getting-catch2\" rel=\"nofollow noreferrer\">the start of the tutorial</a>—<code>catch_amalgamated.hpp</code> and <code>catch_amalgamated.cpp</code>—and just put them in the same directory as your project. In that directory you should have (at least) <code>fibonacci.hpp</code>, <code>fibonacci.cpp</code>, <code>fibonacci.test.cpp</code>, <code>catch_amalgamated.hpp</code>, and <code>catch_amalgamated.cpp</code>:</p>\n<ul>\n<li><code>fibonacci.hpp</code>: your header</li>\n<li><code>fibonacci.cpp</code>: your implementation</li>\n<li><code>fibonacci.test.cpp</code>: your tests</li>\n<li><code>catch_amalgamated.hpp</code>: the Catch2 header</li>\n<li><code>catch_amalgamated.cpp</code>: the Catch2 code</li>\n</ul>\n<p>and when you compile, you need to make sure to also compile the Catch2 code:</p>\n<pre class=\"lang-shell prettyprint-override\"><code># only need to do this one time, which is good, because it will be slow\n$ g++ --std=c++17 --pedantic -Wall -Wextra -c catch_amalgamated.cpp\n\n# should do these every time\n$ g++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.test.cpp\n$ g++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.cpp\n$ g++ --std=c++17 --pedantic -Wall -Wextra -o fibonacci.test fibonacci.test.o fibonacci.o catch_amalgamated.o\n$ ./fibonacci.test\n</code></pre>\n<p>Or, better yet, put all those commands in a shell script or makefile. Also, you could use <code>--std=c++11</code> or <code>--std=c++14</code> or even <code>--std=c++20</code>, depending on what version of C++ you want to use.</p>\n<p>Here’s a simple build script you could use:</p>\n<pre class=\"lang-shell prettyprint-override\"><code>#!/bin/sh\n\n# Stop immediately if something fails.\nset -e\n\n# Only recompile Catch2 if we have to.\nif [ ! -f catch_amalgamated.o ]\nthen\n printf '%s\\n' 'g++ --std=c++17 --pedantic -Wall -Wextra -c catch_amalgamated.cpp'\n g++ --std=c++17 --pedantic -Wall -Wextra -c catch_amalgamated.cpp\nfi\n\n# Compile everything else.\nprintf '%s\\n' 'g++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.test.cpp'\ng++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.test.cpp\n\nprintf '%s\\n' 'g++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.cpp'\ng++ --std=c++17 --pedantic -Wall -Wextra -c fibonacci.cpp\n\n# Link.\nprintf '%s\\n' 'g++ --std=c++17 --pedantic -Wall -Wextra -o fibonacci.test fibonacci.test.o fibonacci.o catch_amalgamated.o'\ng++ --std=c++17 --pedantic -Wall -Wextra -o fibonacci.test fibonacci.test.o fibonacci.o catch_amalgamated.o\n</code></pre>\n<p>Put that in <code>build.sh</code>, make it executable, and you can just do:</p>\n<pre class=\"lang-shell prettyprint-override\"><code>$ ./build.sh\n$ ./fibonacci.test\n</code></pre>\n<p>That will speed up your workflow, and anything that speeds up your workflow is a good thing. (Even better than a build script would be a proper makefile, but that’s too complicated for here.)</p>\n<p>The test file doesn’t need to be complex:</p>\n<pre><code>// fibonacci.test.cpp\n\n#define CATCH_CONFIG_MAIN\n#include &quot;catch_amalgamated.hpp&quot;\n\n#include &lt;random&gt;\n\n#include &quot;fibonacci.hpp&quot;\n\n// You should always test important edge cases:\n\nTEST_CASE(&quot;Fibonacci(0) memoized is 0&quot;)\n{\n CHECK(your_ns::fib_with_memo(0) == 0);\n}\n\nTEST_CASE(&quot;Fibonacci(1) memoized is 1&quot;)\n{\n CHECK(your_ns::fib_with_memo(1) == 1);\n}\n\n// Doesn't hurt to test a few random cases:\n\nTEST_CASE(&quot;Fibonacci(10) memoized is 55&quot;)\n{\n CHECK(your_ns::fib_with_memo(10) == 55);\n}\n\nTEST_CASE(&quot;Fibonacci(20) memoized is 6765&quot;)\n{\n CHECK(your_ns::fib_with_memo(20) == 6765);\n}\n\n// Test the *property* of Fibonacci numbers:\n\nTEST_CASE(&quot;Fibonacci(n) memoized is Fibonacci(n - 1) + Fibonacci(n - 2)&quot;)\n{\n constexpr auto lower_limit = 5;\n constexpr auto upper_limit = 50; // or maybe as high as 90-ish, if you like\n\n constexpr auto number_of_trials = 3;\n\n auto rng = std::mt19937{std::random_device{}()};\n auto dist = std::uniform_int_distribution&lt;int&gt;{lower_limit, upper_limit};\n\n for (auto trial = 1; trial &lt;= number_of_trials; ++trial)\n {\n // random number between lower and upper limit, inclusive\n auto const n = dist(rng);\n\n DYNAMIC_SECTION(&quot;n = &quot; &lt;&lt; n)\n {\n auto const fib_n = your_ns::fib_with_memo(n);\n auto const fib_n_minus_1 = your_ns::fib_with_memo(n - 1);\n auto const fib_n_minus_2 = your_ns::fib_with_memo(n - 2);\n\n INFO(&quot;fib(n) = &quot; &lt;&lt; fib_n);\n INFO(&quot;fib(n - 1) = &quot; &lt;&lt; fib_n_minus_1);\n INFO(&quot;fib(n - 2) = &quot; &lt;&lt; fib_n_minus_2);\n\n CHECK(fib_n == (fib_n_minus_1 + fib_n_minus_2));\n }\n }\n}\n</code></pre>\n<p>Test cases should be as simple as possible. Indeed, the last case is pretty complex for a test case in my opinion, but most of it is just generating random values for <code>n</code> and recording the intermediate results so you can see exactly where things went wrong.</p>\n<p>At first this shouldn’t compile, because <code>fib_with_memo()</code> shouldn’t exist yet (assuming you’re writing the tests first, which you normally should). So you just write some placeholders:</p>\n<pre><code>// fibonacci.hpp\n\n#ifndef INCLUDE_GUARD_fibonacci\n#define INCLUDE_GUARD_fibonacci\n\nnamespace your_ns {\n\nusing big_t = unsigned long long int;\n\nbig_t fib_with_memo(int);\n\n} // namespace your_ns\n\n#endif // include guard\n</code></pre>\n<pre><code>// fibonacci.cpp\n\n#include &quot;fibonacci.hpp&quot;\n\nnamespace your_ns {\n\nbig_t fib_with_memo(int)\n{\n return {};\n}\n\n} // namespace your_ns\n</code></pre>\n<p>Now it should compile and run… and generate a bunch of test case failures. But that’s good! A failing test case means that at least <em>something</em> is being checked, and it probably means that a bug was found.</p>\n<p>I got 2 cases passed, and 3 failures. The 2 passes are because <code>fib_with_memo(0)</code> returns <code>0</code>… which by fluke happens to be correct, and because since <code>fib_with_memo(anything)</code> returns <code>0</code>, that means <code>fib_with_memo(anything) == fib_with_memo(anything - 1) + fib_with_memo(anything - 2)</code> is always true. This happens sometimes as you’re developing; broken code <em>happens</em> to return the “right” answer… or at least an answer that “works”. Other tests should catch that problem, though.</p>\n<p>So now you start to develop your Fibonacci algorithm. Let’s say as a first step, you do:</p>\n<pre><code>big_t fib_with_memo(int n)\n{\n if (n &lt; 2)\n return n;\n\n return {};\n}\n</code></pre>\n<p>Compile and run… now <em>3</em> tests pass, and 2 fail. Progress!</p>\n<p>This is how you do it. Take tiny steps, and check as you go. It may sound tedious, but once you get in the habit, it becomes automatic.</p>\n<p>So the next thing I’ve done is just copy-pasted your refactored code into <code>fib_with_memo()</code> (I also needed to <code>#include &lt;vector&gt;</code>, and I needed to rename <code>big</code> to <code>big_t</code> because I didn’t notice I’d got the name wrong), and…</p>\n<p><strong>ALL TESTS PASSED!</strong></p>\n<p>Congratulations! Check it in!</p>\n<p>So your refactored code <em>works</em>… but… can it be <em>improved</em>? Well, that’s a question for another code review. <a href=\"https://github.com/catchorg/Catch2/blob/devel/docs/benchmarks.md\" rel=\"nofollow noreferrer\">Catch2 also supports benchmarking</a>, so you can even do performance checks in your testing code, and as you make changes, you can see if things speed up or not.</p>\n<p>But the point is, if you adopt this style of development—testing, testing, testing, testing—you will write better code, quicker, <em>and</em> when it comes time to refactor, you can do so with confidence because if you “break” anything, the tests will catch it immediately. It’s <em>such</em> a nice way of coding that once you get in the habit, you can’t quit; you feel naked and unsteady when you’re trying to code without tests.</p>\n<p>Some other tips:</p>\n<ul>\n<li><p>I suggested putting the memo map (or vector) in the function as a <code>static</code> variable, and that’s definitely what you should do for the final code. <em>However</em>, while developing, you could pull it out and make it a global, so you can inspect what’s in the map/vector directly, and make sure that it’s working properly. It’s okay to break stuff while you’re working on it, once you remember to put things back in order when developing/testing is done.</p>\n</li>\n<li><p>If you do pull the memo map/vector out and make it a global (for development only), then you can observe its capacity to make sure it’s not wasting space. You can also use a tracing allocator to track allocations, and see if you’re losing efficiency there.</p>\n<p>A simple tracing allocator is:</p>\n</li>\n</ul>\n<pre><code>template &lt;typename T&gt;\nclass tracing_allocator\n{\npublic:\n using value_type = T;\n\n // not needed in C++17\n using propagate_on_container_move_assignment = std::true_type;\n\n auto allocate(std::size_t n)\n {\n std::cout &lt;&lt; &quot;allocating &quot; &lt;&lt; n &lt;&lt; &quot; bytes\\n&quot;;\n return std::allocator&lt;T&gt;{}.allocate(n);\n }\n\n auto deallocate(T* p, std::size_t n)\n {\n std::cout &lt;&lt; &quot;deallocating address &quot; &lt;&lt; static_cast&lt;void*&gt;(p) &lt;&lt; &quot;, which is &quot; &lt;&lt; n &lt;&lt; &quot; bytes\\n&quot;;\n return std::allocator&lt;T&gt;{}.deallocate(p, n);\n }\n};\n\ntemplate &lt;typename T1, typename T2&gt;\nconstexpr auto operator==(tracing_allocator&lt;T1&gt; const&amp;, tracing_allocator&lt;T2&gt; const&amp;) noexcept\n{\n return true;\n}\n\n// not needed in C++20\ntemplate &lt;typename T1, typename T2&gt;\nconstexpr auto operator!=(tracing_allocator&lt;T1&gt; const&amp;, tracing_allocator&lt;T2&gt; const&amp;) noexcept\n{\n return false;\n}\n</code></pre>\n<p>And you’d use it by declaring your vector as:</p>\n<pre><code>static std::vector&lt;big, tracing_allocator&lt;big&gt;&gt; mem = {0, 1};\n</code></pre>\n<p>And now you will get trace statements printed to standard output, for every allocation (and deallocation). This will help you observe how your memo map/vector is growing, and whether there are unnecessary/overlarge allocations happening.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T18:50:57.883", "Id": "505833", "Score": "0", "body": "Wow, thank you. That's all very helpful. I briefly considered using a std::vector, but for whatever reason decided not to implement it that way. I'm obviously very new to C++— is there a significant difference between a preprocessor macro and a typedef, and why is the former better? I think I'll refactor with std::vector and constexpr as you said." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T19:17:58.777", "Id": "505835", "Score": "0", "body": "Here's my refactored code: https://pastebin.com/WfvTV3va. I do like (and understand) your \"extra-cached\" solution. (Of course, if I were using this in the real world, I wouldn't use the recursive definition!) Instead of vec.size(), I keep a static int variable around to record the length— since for every recursive function call I'll only be appending one fibonacci value, I just increment it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T22:30:20.547", "Id": "505847", "Score": "0", "body": "I’ll extend the answer to include answers to the above questions, since it’s hard to answer them in a comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T04:40:59.383", "Id": "505863", "Score": "0", "body": "Awesome, thank you so much. I've mostly just written personal-use scripts and Jupyter notebooks in the past, but I'm creating an API (Python) for something right now, and tests are something I definitely feel would be helpful. I'll take all your advice into account for C++ and beyond." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T05:13:43.233", "Id": "256220", "ParentId": "256202", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T20:27:42.897", "Id": "256202", "Score": "2", "Tags": [ "c++", "beginner", "recursion", "fibonacci-sequence", "memoization" ], "Title": "C++17 Recursive Fibonacci calculation with memoization" }
256202
<p>I am making an RPG game using python. At the moment, I have programmed choosing your character and saving it.</p> <p>However, today I previously asked a question <a href="https://stackoverflow.com/q/66261027/1575353"><code>NameError: name 'character' is not defined</code></a> on stackoverflow. Whilst I got my question answered and my program is now working, I received a comment on my question (from a person with 15k reputation so I am guessing they can be trusted) stating:</p> <blockquote> <p>#BTW: Once you have it fixed, take your code to codereview.stackexchange.com, there are a few very bad practices in there</p> </blockquote> <p>I'm guessing the person was referring to my code, so i have come over here to get some feedback.</p> <p>Whilst I am a <code>beginner</code> and I am unsure how to improve on any bad practices I have made, I know that criticism is only a good thing and I can learn from my mistakes. I was wondering if someone could point out anything/give me some tips on what I could do better with my program. Thanks.</p> <p><strong>My full code:</strong></p> <pre><code>from os import system from ascii_art_functions import mountain_range from ascii_art_functions import character_selection_horse_and_knight from ascii_art_functions import screen_line import random import math import time import datetime import pickle import sys import os #miscellaneous functions + procedures def w(t): time.sleep(t) def version_counter(filename=&quot;adventure_colussus_version_counter.dat&quot;): with open(filename, &quot;a+&quot;) as f: f.seek(0) val = int(f.read() or 0) + 1 f.seek(0) f.truncate() f.write(str(val)) return val counter = version_counter() def t(text): for char in text: sys.stdout.write(char) sys.stdout.flush() time.sleep(0.021) def save_character(save_name, character): save_name_pickle = save_name + '.pickle' t('&gt; saving character') w(1) with open(save_name_pickle, 'wb') as f: pickle.dump(character, f) t('&gt; character saved successfully') def load_character(load_name): load_name_pickle = load_name + '.pickle' t(' &gt; loading character...') w(1) pickle_in = open(load_name_pickle,&quot;rb&quot;) character = pickle.load(pickle_in) t(' &gt; character loaded successfully\n') t('\n&gt; welcome back ') t(character['name']) t('!!!\n') w(0.5) t('\n&gt; here are your stats from last time: \n') print(' &gt;',character) def character_generator(): t('\n &gt; we have reached the first crucial part of your journey: we must choose the path that you will take! the decision\n') w(0.5) t(' &gt; is up to you my friend! Whether you choose to be a bloodthisty warrior or a cunning and strategic fighter,\n') w(0.8) t(' &gt; the choice is yours!\n') w(0.5) t('\n &gt; now then, lets get right into it!') w(0.8) t(' are you more of a tanky player[1] or a strategic player[2]?') player_t_choice_1 = input('\n &gt; ') if player_t_choice_1 == '1': health = 100 damage = 75 elif player_t_choice_1 == '2': health = 75 damage = 50 t('\n &gt; so, we have that out of the way, lets carry on!') w(0.8) t(' oh of course! sorry to forget! another quick question: ') w(0.5) t('do you like \n') t(' &gt; to use magic from great distances[1] or run in to the thick of battle weilding a deadly blade[2]? ') player_t_choice_2 = input('\n &gt; ') if player_t_choice_2 == '1': shield = 50 magic = 75 elif player_t_choice_2 == '2': shield = 75 magic = 45 t('\n &gt; good good! we have decided your play style and your preffered ways of attacking the enemy!\n') w(0.5) t(' &gt; now, we must see what luck we are able to bestow upon you. be warned: it is entirely random!\n') w(0.8) random_luck = input('\n &gt; press enter to roll a dice...') w(0.3) t(' &gt; rolling dice...\n') luck = random.randint(0,10) w(1) print(' &gt; your hero has',luck,'luck out of 10!') w(0.8) t('\n &gt; we have reached the most important part of creating your character! The naming!\n') t(' &gt; choose wisely. your hero will be named this for the rest of their lives...\n') w(1) t('\n &gt; what should your hero be named?\n ') name = input('&gt; ') w(1) t('\n &gt; welcome mighty hero! you shall be named: ') t(name) t(' !!!\n') t(' &gt; a fine choice') t('\n') t(' \n &gt; now then. i guess you be on your way! you have a journey to start and a belly to fill!\n') t(' &gt; i have to say, i have rather enjoyed your company! feel free to come by at any time!\n ') t('&gt; goodbye and god speed!') w(1) print('\n') t(' &gt; your final stats are as follows: \n') w(0.3) print(' &gt;', '[', 'health:', health, ', damage:', damage, ', shield:', shield, ', magic:', magic, ', luck:', luck, ', name:', name, ']') t('\n &gt; we should now save your character if you want to come back to it later:\n ') character = {'health': health, 'damage': damage, 'shield': shield, 'magic': magic, 'luck': luck, 'name': name} character_file_name = input('&gt; ') save_character(character_file_name, character) # main game w(0.5) e = datetime.datetime.now() screen_line() print('\n &lt;Adventure Colussus&gt; version: v',counter,'| current date: ',e, '| date of creation: 9.2.2021') screen_line() w(0.5) mountain_range() screen_line() print('\n &gt; [1] create new game') print(' &gt; [2] load existing game') print(' &gt; [3] end game') print(' &gt; [4] credits') choice = input(&quot;\n &gt; &quot;) if choice == '1': t(&quot;\n &gt; you have chosen to create a new game: redirecting...&quot;) w(0.75) system('cls') screen_line() print(' \n we will begin with creating your character: quick tip: choose wisely') screen_line() w(0.5) character_selection_horse_and_knight() screen_line() w(0.3) character_generator() elif choice == '2': t(&quot;\n &gt; you have chosen to load an existing game: redirecting...&quot;) w(0.75) system('cls') w(0.5) screen_line() print(' \n we will begin with choosing an existing character: quick tip: make sure it exists!') screen_line() w(0.5) character_selection_horse_and_knight() screen_line() character_file_name = input('\n &gt; character file name: ') load_character(character_file_name) elif choice == '3': t(' &gt; ending session...') w(0.5) t(' &gt; session ended successfully') w(1) sys.exit() elif choice == '4': pass else: t('incorrect response. please try again') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T22:10:22.410", "Id": "505733", "Score": "2", "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](https://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](https://meta.codereview.stackexchange.com/q/2436)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T22:31:26.097", "Id": "505735", "Score": "2", "body": "well i have edited it now a little! i hope that helps!" } ]
[ { "body": "<h1>Naming</h1>\n<p>I would make the following changes</p>\n<pre><code>w() -&gt; remove\nt() -&gt; print_text()\n</code></pre>\n<p>Since <code>w()</code> is just <code>time.sleep</code>, it isn't necessary. And someone looking at your code would understand <code>time.sleep</code> a lot after than seeing <code>w(0.08)</code>, and having to look to where <code>w</code> is defined.</p>\n<p><code>print_text</code> is a lot more descriptive than just <code>t</code>.</p>\n<h1>Docstrings</h1>\n<p>Adding a simple doctoring inside each function can help immensely when you need a quick reminder of what a function does. For example,</p>\n<pre><code>def version_counter() -&gt; int:\n &quot;&quot;&quot;\n Determines the version of the last played game, either in the {VERSION_FILENAME}\n file, or generating a new file if none is found.\n &quot;&quot;&quot;\n</code></pre>\n<h1>Type Hints</h1>\n<p>You can add type hints to display what types of parameters are accepted, and what types are returned, if any. For example,</p>\n<pre><code>from typing import Dict, Any\ndef save_character(save_name: str, character: Dict[str, Any]) -&gt; None:\n &quot;&quot;&quot;\n Saves the current character to a pickle database.\n &quot;&quot;&quot;\n</code></pre>\n<p>Before, seeing just <code>character</code>, one might assume it's just a string representing the characters name. Now, it's clearly represented as a dictionary with string keys and values that can be any type.</p>\n<p>The most important distinction here is making sure someone reading your code knows the types accepted by your function, and the types returned. Since this function doesn't &quot;return&quot; a value, you use <code>None</code>.</p>\n<h1>Imports</h1>\n<p>You don't need <code>import os</code>, because in your program you only use the <code>system</code> function you imported a few lines above. You also don't need <code>math</code>.</p>\n<h1>Less Code</h1>\n<p>I notice you <code>time.sleep</code> after almost every time you print to the console. Instead, I would recommend passing that value to the (now named <code>print_text</code> function), and do the time.sleep in there. For example,</p>\n<pre><code>def print_text(text: str, sleep_time: float=0.0) -&gt; None:\n &quot;&quot;&quot;\n Prints the text to the console character by character. RPG style.\n &quot;&quot;&quot;\n for char in text:\n sys.stdout.write(char)\n sys.stdout.flush()\n time.sleep(0.021)\n if sleep_time != 0.0:\n time.sleep(sleep_time)\n</code></pre>\n<p>Then you use it as such:</p>\n<pre><code>print_text('&gt; saving character', 1)\n</code></pre>\n<p>And if you don't want to wait after, since <code>sleep_time</code> is a default parameter, just</p>\n<pre><code>print_text('&gt; saving character')\n</code></pre>\n<h1>Error Checking</h1>\n<p>I'm playing your game, reach the character generator function, and accidentally press <code>3</code> for the first question! Now your code silently fails, my <code>health</code> and <code>damage</code> aren't set, and I don't know what's wrong later on. I would recommend something like this:</p>\n<pre><code>def get_input(string: str, valid_options: List[str]) -&gt; str:\n while True:\n user_input = input(string)\n if user_input in valid_options:\n return user_input\n</code></pre>\n<p>Then used like this:</p>\n<pre><code>print('\\n &gt; [1] create new game')\nprint(' &gt; [2] load existing game')\nprint(' &gt; [3] end game')\nprint(' &gt; [4] credits')\nchoice = get_input(&quot;\\n &gt; &quot;, ['1', '2', '3', '4'])\n</code></pre>\n<h1>Consistent Spacing</h1>\n<p>In some spaces in your code, there's one space between <code>if/else</code> statements, and other places there's 3 or 4 spaces. Being consistent can help organize your code (my recommendation would be to stick with less spaces between statements)</p>\n<h1>Obligatory <code>f&quot;&quot;</code></h1>\n<p>Using <code>f-strings</code> allows you to directly include variables in your strings. For example, the below line</p>\n<pre><code>print(' &gt;', '[', 'health:', health, ', damage:', damage, ', shield:', shield, ', magic:', magic, ', luck:', luck, ', name:', name, ']')\n</code></pre>\n<p>can be condensed to</p>\n<pre><code>print(f&quot; &gt; [ health: {health}, damage: {damage}, shield: {shield}, magic: {magic}, luck: {luck}, name: {name} ]&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T09:00:09.640", "Id": "505781", "Score": "0", "body": "Thanks a ton! It looks like you have put a lot of effort into your answer and you have pointed out several things, which i will definetly improve on. Thanks again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T08:52:32.413", "Id": "256224", "ParentId": "256205", "Score": "3" } } ]
{ "AcceptedAnswerId": "256224", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-18T21:48:01.527", "Id": "256205", "Score": "4", "Tags": [ "python", "beginner", "console" ], "Title": "text-based RPG game in python- character selection" }
256205
<p>How to choose the dark mode properly?</p> <pre><code> {isDarkMode ? &lt;ImageBackground source={require('../Images/bgndDark/bgGradient.png')} style={styles.container}&gt; &lt;Charter isDarkMode /&gt; &lt;/ImageBackground &gt; : &lt;Charter isDarkMode={false} /&gt; } </code></pre> <p>Just feels wrong to duplicate &quot;Charter&quot;?</p>
[]
[ { "body": "<p>You can store <code>Charter</code> and use that instead.</p>\n<pre><code>const children = () =&gt; &lt;Charter isDarkMode /&gt;;\n\nif (isDarkMode)\n return (\n &lt;ImageBackground\n {...{ children }}\n source={require(&quot;../Images/bgndDark/bgGradient.png&quot;)}\n style={styles.container}\n /&gt;\n );\nreturn children;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T15:57:30.423", "Id": "530664", "Score": "0", "body": "If this helps please accept the answer. So we can close this question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-08T19:33:40.050", "Id": "268789", "ParentId": "256211", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T00:44:00.153", "Id": "256211", "Score": "-1", "Tags": [ "react-native" ], "Title": "JS react manage dark mode ternary" }
256211
<p>So I'm making a strlen function and I thought I would use SIMD instructions for it. It runs fine but when comparing it to std::strlen(), it falls a lot behind. Any ideas on how to make it faster would be much appreciated.</p> <pre><code>inline size_t strlen(const char* data) { const __m128i terminationCharacters = _mm_setzero_si128(); const __m128i* pointer = (const __m128i*)data; size_t length = 0; const int compareMode = _SIDD_UBYTE_OPS | _SIDD_LEAST_SIGNIFICANT | _SIDD_CMP_EQUAL_EACH; for (;; length += 16, ++pointer) { const __m128i comparingData = _mm_loadu_si128(pointer); size_t index = _mm_cmpistri(terminationCharacters, comparingData, compareMode); if (index &lt; 16) return length + index; } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T16:51:56.043", "Id": "505825", "Score": "0", "body": "Have you read any of the other implementations of `strlen()` (e.g. the GNU one), or do you have a need to do a \"clean room\" implementation?" } ]
[ { "body": "<h1><code>pcmpistri</code></h1>\n<p>This seems like the obvious choice searching withing a string. However, while <code>pcmpistri</code> is very general/powerful, it is also not very fast. On typical Intel processors it consists of 3 µops that all go to execution port p0 (therefore limiting this loop to at best running one iteration every 3 cycles), on AMD Zen(1/2) it's slightly less bad coming in at 2 µops and executing once every 2 cycles.</p>\n<p>There is an in way more primitive way (just using SSE2) based on <code>pcmpeqb</code> and <code>pmovmskb</code>. That leaves you with a mask instead of an index, but for most of the loop that doesn't matter (all that matters is whether the mask is zero or not), and in the final iteration you can use <code>tzcnt</code> (or similar) to find the actual index of the zero byte within the vector.</p>\n<p>That technique also scales to AVX2, which <code>pcmpistri</code> does not. Additionally, you could use some unrolling: <code>pminub</code> some successive blocks of 16 bytes together to go through the string quicker at first, at the cost of a more tricky final iteration and a more complex pre-loop setup (see the next point).</p>\n<h1>A bug</h1>\n<p>While an aligned load that contain at least one byte of the string is safe even if the load pulls in some data that is outside the bounds of the string (an aligned load cannot cross a page boundary), that trick is unsafe for unaligned loads. A string that ends near a page boundary could cause this function to fetch into the next page, and possibly trigger an access violation.</p>\n<p>There are different ways to fix it. The obvious one is using the usual byte-by-byte loop until a sufficiently aligned address is reached. A more advanced trick is rounding the address <em>down</em> to a multiple of 16 (32 for AVX2) and doing an aligned load. There are bytes in it that aren't from the string, maybe including a zero. Therefore those bytes must be explicitly ignored, for example by shifting the mask that <code>pmovmskb</code> returned to the right by <code>data &amp; 15</code>. If you decide to add unrolling, then the address for the main loop should be even more aligned, to guarantee that <em>all</em> the loads in the main loop body are safe.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:46:45.817", "Id": "256214", "ParentId": "256212", "Score": "6" } } ]
{ "AcceptedAnswerId": "256214", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T01:03:06.363", "Id": "256212", "Score": "3", "Tags": [ "c++", "performance", "strings", "simd" ], "Title": "Strlen function optimization" }
256212
<p>I am working with <code>System.Array</code> and I am trying to convert <code>System.Array</code> objects to array of specific type (such as <code>int[]</code>) in C#. A series of array downcasting methods is designed as follows.</p> <p><strong>The experimental implementation</strong></p> <p>The experimental implementation of array downcasters are as below.</p> <pre><code>class ArrayDowncasters { public static int[] ToIntArray1(Array input) { Type elementType = input.GetType().GetElementType(); if (input.Rank != 1) { throw new System.InvalidOperationException(); } if (!elementType.Equals(typeof(int))) { throw new System.InvalidOperationException(); } var output = new int[input.GetLength(0)]; for (int i = 0; i &lt; input.GetLength(0); i++) { output[i] = (int)input.GetValue(i); } return output; } public static sbyte[] ToSbyteArray1(Array input) { Type elementType = input.GetType().GetElementType(); if (input.Rank != 1) { throw new System.InvalidOperationException(); } if (!elementType.Equals(typeof(sbyte))) { throw new System.InvalidOperationException(); } var output = new sbyte[input.GetLength(0)]; for (int i = 0; i &lt; input.GetLength(0); i++) { output[i] = (sbyte)input.GetValue(i); } return output; } public static byte[] ToByteArray1(Array input) { Type elementType = input.GetType().GetElementType(); if (input.Rank != 1) { throw new System.InvalidOperationException(); } if (!elementType.Equals(typeof(byte))) { throw new System.InvalidOperationException(); } var output = new byte[input.GetLength(0)]; for (int i = 0; i &lt; input.GetLength(0); i++) { output[i] = (byte)input.GetValue(i); } return output; } public static short[] ToShortArray1(Array input) { Type elementType = input.GetType().GetElementType(); if (input.Rank != 1) { throw new System.InvalidOperationException(); } if (!elementType.Equals(typeof(short))) { throw new System.InvalidOperationException(); } var output = new short[input.GetLength(0)]; for (int i = 0; i &lt; input.GetLength(0); i++) { output[i] = (short)input.GetValue(i); } return output; } public static ushort[] ToUshortArray1(Array input) { Type elementType = input.GetType().GetElementType(); if (input.Rank != 1) { throw new System.InvalidOperationException(); } if (!elementType.Equals(typeof(ushort))) { throw new System.InvalidOperationException(); } var output = new ushort[input.GetLength(0)]; for (int i = 0; i &lt; input.GetLength(0); i++) { output[i] = (ushort)input.GetValue(i); } return output; } public static char[] ToCharArray1(Array input) { Type elementType = input.GetType().GetElementType(); if (input.Rank != 1) { throw new System.InvalidOperationException(); } if (!elementType.Equals(typeof(char))) { throw new System.InvalidOperationException(); } var output = new char[input.GetLength(0)]; for (int i = 0; i &lt; input.GetLength(0); i++) { output[i] = (char)input.GetValue(i); } return output; } public static float[] ToFloatArray1(Array input) { Type elementType = input.GetType().GetElementType(); if (input.Rank != 1) { throw new System.InvalidOperationException(); } if (!elementType.Equals(typeof(float))) { throw new System.InvalidOperationException(); } var output = new float[input.GetLength(0)]; for (int i = 0; i &lt; input.GetLength(0); i++) { output[i] = (float)input.GetValue(i); } return output; } public static double[] ToDoubleArray1(Array input) { Type elementType = input.GetType().GetElementType(); if (input.Rank != 1) { throw new System.InvalidOperationException(); } if (!elementType.Equals(typeof(double))) { throw new System.InvalidOperationException(); } var output = new double[input.GetLength(0)]; for (int i = 0; i &lt; input.GetLength(0); i++) { output[i] = (double)input.GetValue(i); } return output; } public static string[] ToStringArray1(Array input) { Type elementType = input.GetType().GetElementType(); if (input.Rank != 1) { throw new System.InvalidOperationException(); } if (!elementType.Equals(typeof(string))) { throw new System.InvalidOperationException(); } var output = new string[input.GetLength(0)]; for (int i = 0; i &lt; input.GetLength(0); i++) { output[i] = (string)input.GetValue(i); } return output; } } </code></pre> <p><strong>Test cases</strong></p> <p>The Test cases for <code>ToIntArray1</code> and <code>ToDoubleArray1</code> methods are as below.</p> <pre><code>// One Dimensional Array with int element convert to int[] var array1 = Array.CreateInstance(typeof(int), 10); for (int i = 0; i &lt; array1.Length; i++) { array1.SetValue(3, i); } var intArray = ArrayDowncasters.ToIntArray1(array1); for (int i = 0; i &lt; intArray.Length; i++) { Console.WriteLine(intArray[i]); } // One Dimensional Array with double element convert to double[] var array2 = Array.CreateInstance(typeof(double), 10); for (int i = 0; i &lt; array2.Length; i++) { array2.SetValue(3.1, i); } var doubleArray = ArrayDowncasters.ToDoubleArray1(array2); for (int i = 0; i &lt; doubleArray.Length; i++) { Console.WriteLine(doubleArray[i]); } </code></pre> <p>All suggestions are welcome.</p> <p>If there is any possible improvement about:</p> <ul> <li>Potential drawback or unnecessary overhead</li> <li>Error handling</li> </ul> <p>please let me know.</p>
[]
[ { "body": "<p>After reading the code in question it seems every method is doing exactly the same hence I will focus only on one method and tell you what I would change:</p>\n<blockquote>\n<pre><code>public static int[] ToIntArray1(Array input)\n{\n Type elementType = input.GetType().GetElementType();\n if (input.Rank != 1)\n {\n throw new System.InvalidOperationException();\n }\n\n if (!elementType.Equals(typeof(int)))\n {\n throw new System.InvalidOperationException();\n }\n\n var output = new int[input.GetLength(0)];\n for (int i = 0; i &lt; input.GetLength(0); i++)\n {\n output[i] = (int)input.GetValue(i);\n }\n return output;\n}\n</code></pre>\n</blockquote>\n<p>If this method is called and this would result in an <code>InvalidOperationException</code> one wouldn't know the exact cause of that exception because it could either be that the passed <code>Array</code> hasn't a <code>Rank==1</code> or the type of the elements doesn't match the expected type.<br />\nWhat I would change here is to have the <code>InvalidException</code> being created using a message indicating what went wrong.</p>\n<p>The line</p>\n<pre><code>Type elementType = input.GetType().GetElementType(); \n</code></pre>\n<p>should be placed after the check for <code>Rank</code> because its nearer to its usage and would be superflous if e.g <code>Rank == 2</code>.</p>\n<p>Usually I would suggest to introduce another variable to hold the value of <code>input.GetLength(0)</code> because you are calling this method twice, but because we know at this point that the array isn't multidimensional we can just use the <code>Length</code> property of the array.</p>\n<p>This would sum up to look like so</p>\n<pre><code>public static int[] ToIntArray1(Array input)\n{\n \n if (input.Rank != 1)\n {\n throw new System.InvalidOperationException(&quot;Only one-dimensional array allowed&quot;);\n }\n\n Type elementType = input.GetType().GetElementType();\n if (!elementType.Equals(typeof(int)))\n {\n throw new System.InvalidOperationException(&quot;Wrong type&quot;);\n }\n\n var output = new int[input.Length];\n for (int i = 0; i &lt; input.Length; i++)\n {\n output[i] = (int)input.GetValue(i);\n }\n return output;\n}\n</code></pre>\n<p>Because all the methods are doing the same, you could just make one generic method like so</p>\n<pre><code>public static T[] ToArray&lt;T&gt;(Array input)\n{\n\n if (input.Rank != 1)\n {\n throw new System.InvalidOperationException(&quot;Only one-dimensional array allowed&quot;);\n }\n\n Type elementType = input.GetType().GetElementType();\n if (!elementType.Equals(typeof(T)))\n {\n throw new System.InvalidOperationException(&quot;Wrong type&quot;);\n }\n\n var output = new T[input.Length];\n for (var i = 0; i &lt; input.Length; i++)\n {\n output[i] = (T)input.GetValue(i);\n }\n return output;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T07:55:56.087", "Id": "256222", "ParentId": "256221", "Score": "3" } }, { "body": "<p>There are a few alternative solutions which might work</p>\n<p><strong>LINQ</strong> </p>\n<p>It is possible to use <em>Enumerable.Cast&lt;T&gt;()</em> to achieve the same results (at least for a 1D array)</p>\n<pre><code>[TestMethod]\npublic void CheckConversion()\n{\n // One Dimensional Array with int element convert to int[]\n var array1 = Array.CreateInstance(typeof(int), 10);\n for (int i = 0; i &lt; array1.Length; i++)\n {\n array1.SetValue(3, i);\n }\n\n var intArray1 = ArrayDowncasters.ToIntArray1(array1);\n var intArray2 = array1.Cast&lt;int&gt;().ToArray();\n CollectionAssert.AreEqual(intArray1, intArray2);\n\n // One Dimensional Array with double element convert to double[]\n var array2 = Array.CreateInstance(typeof(double), 10);\n for (int i = 0; i &lt; array2.Length; i++)\n {\n array2.SetValue(3.1, i);\n }\n\n var doubleArray1 = ArrayDowncasters.ToDoubleArray1(array2);\n var doubleArray2 = array2.Cast&lt;double&gt;().ToArray();\n CollectionAssert.AreEqual(doubleArray1, doubleArray2);\n\n}\n</code></pre>\n<p><strong>Generics</strong> </p>\n<p>The naming of the functions e.g. ToDoubleArray<strong>1</strong>() indicates that there might be 2 or 3 or n dimensional versions to be added. I don't know if a LINQ solution can be made to work for these but the current code can be re-written as a single generic function</p>\n<pre><code>public static T[] Convert&lt;T&gt;(Array input)\n{\n Type elementType = input.GetType().GetElementType();\n if (input.Rank != 1)\n {\n throw new System.InvalidOperationException();\n }\n\n if (!elementType.Equals(typeof(T)))\n {\n throw new System.InvalidOperationException();\n }\n\n var output = new T[input.GetLength(0)];\n for (int i = 0; i &lt; input.GetLength(0); i++)\n {\n output[i] = (T)input.GetValue(i);\n }\n return output;\n}\n</code></pre>\n<p>which means that a single generic function per dimension may suffice</p>\n<pre><code>[TestMethod]\npublic void CheckConversionGeneric()\n{\n // One Dimensional Array with int element convert to int[]\n var array1 = Array.CreateInstance(typeof(int), 10);\n for (int i = 0; i &lt; array1.Length; i++)\n {\n array1.SetValue(3, i);\n }\n\n var intArray1 = ArrayDowncasters.ToIntArray1(array1);\n var intArray2 = ArrayDowncasters.Convert&lt;int&gt;(array1);\n CollectionAssert.AreEqual(intArray1, intArray2);\n\n // One Dimensional Array with double element convert to double[]\n var array2 = Array.CreateInstance(typeof(double), 10);\n for (int i = 0; i &lt; array2.Length; i++)\n {\n array2.SetValue(3.1, i);\n }\n\n var doubleArray1 = ArrayDowncasters.ToDoubleArray1(array2);\n var doubleArray2 = ArrayDowncasters.Convert&lt;double&gt;(array2);\n CollectionAssert.AreEqual(doubleArray1, doubleArray2);\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T08:41:42.047", "Id": "505780", "Score": "0", "body": "Thank you for the answer. I am wondering if it is possible to deduce `T` as `elementType` automatically so that `ArrayDowncasters.Convert(array2);` can be used directly and the type check `if (!elementType.Equals(typeof(T)))...` isn't needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T09:19:56.997", "Id": "505783", "Score": "1", "body": "If I understand the question correctly, the problem will be on the left hand side. *var* is just a way of telling the compiler, 'you determine the type based upon the rest of the code' which means we need something in the code at compile time to tell it the target type. Take the original test code. The compiler knows that *doubleArray* is of type double[] because that is the return type of *ToDoubleArray1()* is a double[]. In the generic version, the Convert<**double**>() tells us it is a double[]. The elementType of the array is a runtime characteristic and no use to the compiler." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T07:56:37.557", "Id": "256223", "ParentId": "256221", "Score": "3" } }, { "body": "<p>Just use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array.convertall\" rel=\"nofollow noreferrer\"><code>Array.ConvertAll</code></a> that is already exist.</p>\n<p>For instance, you want to convert array from <code>string[]</code> to <code>int[]</code> you can do this :</p>\n<pre><code>var converted = Array.ConvertAll(array , item =&gt; int.TryParse(item?.ToString() , out int result) ? result : 0);\n</code></pre>\n<p>Another point is, if you only targeting one-dimension array, then you don't need to use the abstract class <code>Array</code>, instead use one-dimension array types such as <code>int[]</code>.</p>\n<p>So, if you for instance use <code>int[]</code> as an argument then you will not need these lines :</p>\n<pre><code> Type elementType = input.GetType().GetElementType();\nif (input.Rank != 1)\n{\n throw new System.InvalidOperationException();\n}\n\nif (!elementType.Equals(typeof(int)))\n{\n throw new System.InvalidOperationException();\n}\n</code></pre>\n<p>Note, you are missing <code>null</code> validation, you need to always check for nulls input whenever possible.</p>\n<p>finally, if you don't need to use <code>Array.ConvertAll</code> directly, or you need to reduce the repetition of some converting logic, you could create a method and include your application business logic, then use <code>Array.ConvertAll</code> in the method.</p>\n<p>For instance :</p>\n<pre><code>public static class ArrayDowncasters\n{\n private static readonly Type[] _acceptableTypes =\n {\n typeof(int),\n typeof(sbyte),\n typeof(byte),\n typeof(short),\n typeof(ushort),\n typeof(char)\n };\n\n public static TOutput[] Convert&lt;TInput, TOutput&gt;(TInput[] array, Converter&lt;TInput , TOutput&gt; converter)\n {\n if(array == null)\n { return null; }\n\n var type = typeof(TOutput);\n\n if(!_acceptableTypes.Contains(type))\n {\n throw new NotSupportedException($&quot;{type.Name}&quot;);\n }\n\n return Array.ConvertAll&lt;TInput, TOutput&gt;(array , converter);\n }\n}\n</code></pre>\n<p>In the example above, It made things easy to control by restricting the types using <code>_acceptableTypes</code>. if there is a requirement for a new type, it's possible to only add the type to the <code>_acceptableTypes</code>, and adjust the method to that new type if necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T12:31:57.440", "Id": "256226", "ParentId": "256221", "Score": "3" } } ]
{ "AcceptedAnswerId": "256223", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T07:07:40.863", "Id": "256221", "Score": "2", "Tags": [ "c#", "array", "error-handling", "converting", "casting" ], "Title": "ArrayDowncasters Implementation for Downcasting from System.Array to Array of Specific Type in C#" }
256221
<p>I have a list of points (<code>System.Drawing.Point</code>) obtained from an edge finder function that scanned a bitmap for objects. Each point is guaranteed to be a part of an edge line. I need to split the list into a collection of lines so additional math can be performed on them.</p> <p>This is how I originally split the list:</p> <pre><code>public static List&lt;List&lt;Point&gt;&gt; Split(this List&lt;Point&gt; EdgesCoordinateList) { if (EdgesCoordinateList is null) { throw new ArgumentNullException(nameof(EdgesCoordinateList), NullParameterErrorMessage); } if (EdgesCoordinateList.Count &lt;= 1) { return null; } // Link the line coordinates together into lines. // Start by creating a new line with the first coordinate to act as a seed. List&lt;List&lt;Point&gt;&gt; Results = new List&lt;List&lt;Point&gt;&gt; { new List&lt;Point&gt; { EdgesCoordinateList[0] } }; EdgesCoordinateList.RemoveAt(0); // Iterate through the coordinates and assign each one to a line. foreach (Point TestPoint in EdgesCoordinateList) { // Look through each previously found lines and see if the coordinate under test belongs to one of them. // If coordinate under test is adjacent to one of the coordinates in the line under test, it belongs to that line. bool FoundLine = false; foreach (List&lt;Point&gt; LineList in Results.Where(LineList =&gt; LineList.FindLastIndex(i =&gt; Math.Abs(TestPoint.X - i.X) &lt;= 1 &amp;&amp; Math.Abs(TestPoint.Y - i.Y) &lt;= 1) &gt; -1)) { // Add the coordinate to the line it belongs to, then break the line search. Results[Results.IndexOf(LineList)].Add(TestPoint); FoundLine = true; break; } // If line is not a part of preexisting lines then its the start of a new one. if (!FoundLine) { Results.Add(new List&lt;Point&gt; { TestPoint }); } } return Results; } </code></pre> <p>It was great because it was fairly quick and worked well, except it messed up on lines that were relatively horizontal.</p> <p>This is my second attempt to try to fix the issue:</p> <pre><code>public static List&lt;List&lt;Point&gt;&gt; Split(this List&lt;Point&gt; EdgesCoordinateList) { if (EdgesCoordinateList is null) { throw new ArgumentNullException(nameof(EdgesCoordinateList), NullParameterErrorMessage); } if (EdgesCoordinateList.Count &lt;= 1) { return null; } // Link the line coordinates together into lines. // Start by creating a new line with the first coordinate to act as a seed. List&lt;List&lt;Point&gt;&gt; Results = new List&lt;List&lt;Point&gt;&gt; { new List&lt;Point&gt; { EdgesCoordinateList[0] } }; EdgesCoordinateList.RemoveAt(0); do { // Copy the currently found lines into a list for iterating. // Outer list is a list of lines. Inner list is a list of the points in each line. List&lt;List&lt;Point&gt;&gt; FoundLines = Results.ConvertAll(item =&gt; new List&lt;Point&gt;(item)); bool NoMoreMatches = true; // Iterate through the list of lines. for (int i = 0; i &lt; FoundLines.Count; i++) { // Iterate through each point in the current line. foreach (Point TestPoint in FoundLines[i]) { // Find all of the points in the master list that are adjacent to the current test point. List&lt;Point&gt; FoundCoords = EdgesCoordinateList.FindAll(i =&gt; Math.Abs(TestPoint.X - i.X) &lt;= 1 &amp;&amp; (Math.Abs(TestPoint.Y - i.Y) &lt;= 1)); if (FoundCoords.Count &gt; 0) { // Add all of the adjacent points to the current line. Results[i].AddRange(FoundCoords); // Then remove them from the master list. foreach (Point Coord in FoundCoords) { _ = EdgesCoordinateList.Remove(Coord); } NoMoreMatches = false; } } } // When there are no more adjacent points to any of the points in the current line, make another line. if (NoMoreMatches) { Results.Add(new List&lt;Point&gt; { EdgesCoordinateList[0] }); EdgesCoordinateList.RemoveAt(0); } // Continue until there are no more points left in the master list. } while (EdgesCoordinateList.Count &gt; 0); return Results; } </code></pre> <p>The new solution solved the horizontal issue, but runs way too slow. (It went from less than a second to several minutes.)</p> <p>How can I refactor this to speed it up? I would prefer it to work at least at a similar speed as the first method if possible.</p> <hr /> <p><strong>Edit:</strong> The following is a test method which will generate a list of coordinates. When run through the split method, it will split the list into four lists of lines. The actual data comes from 2-4K bitmaps, the lines of which can vary in thickness. I am not sure how to provide an equivalent test method without it being convoluted.</p> <p><code>List&lt;List&lt;Point&gt;&gt; SourceData</code> The outer list is a list of lines. The inner list contains the points assigned to each line.</p> <pre><code>private List&lt;Point&gt; GenerateSourceData() { List&lt;Point&gt; SourceData = new List&lt;Point&gt;(); SourceData.AddRange(AddPoints(5000, 5050, 0, 30)); SourceData.AddRange(AddPoints(5050, 5100, 30, 60)); SourceData.AddRange(AddPoints(5100, 5150, 60, 90)); SourceData.AddRange(AddPoints(5150, 5200, 90, 120)); SourceData.AddRange(AddPoints(6000, 6050, 0, 30)); SourceData.AddRange(AddPoints(6050, 6100, 30, 60)); SourceData.AddRange(AddPoints(6100, 6150, 60, 90)); SourceData.AddRange(AddPoints(6150, 6200, 90, 120)); SourceData.AddRange(AddPoints(7100, 7130, 0, 30)); SourceData.AddRange(AddPoints(7130, 7140, 30, 60)); SourceData.AddRange(AddPoints(8100, 8120, 60, 90)); SourceData.AddRange(AddPoints(8120, 8130, 90, 120)); return SourceData; } private List&lt;Point&gt; AddPoints(int XStart, int XEnd, int YStart, int YEnd) { List&lt;Point&gt; Data = new List&lt;Point&gt;(); for (int Y = YStart; Y &lt; YEnd; Y++) { for (int X = XStart; X &lt; XEnd; X++) { Data.Add(new Point(X, Y)); } } return Data; } </code></pre> <hr /> <p><strong>Edit 2:</strong> I have found a way to reduce the time to approximately 30 seconds by slicing up the lists at various stages and using <code>Parallel.ForEach</code> to run all iterations of each stage simultaneously. I am not posting the code here however because the basic operation is essentially the same.</p> <p>I have tried using a couple methods I thought might work that do not involve deleting points from the source, but both introduced additional problems, including creating duplicates of most coordinates. And although the parallel processing method is a major improvement, 30 seconds is still way too long. Thus, I still seek help in exploring alternative routes in refactoring.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T14:37:12.683", "Id": "505807", "Score": "0", "body": "Have you used any sort of profiling tool like [CodeTrack](https://www.getcodetrack.com/) to find the bottleneck?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T20:01:05.657", "Id": "505839", "Score": "1", "body": "Just finished running CodeTrack, and as I suspected, most of the time is spent in FindAll, which is tucked away in 2 layers of loops. This is what I am trying to refactor, as an hour plus is an unacceptable run time. Still valuable though as this was the first time I have used one of these tools." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T03:02:54.917", "Id": "505860", "Score": "1", "body": "why are you modifying the source `EdgesCoordinateList` and also returning a new list at the same time ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T23:02:11.550", "Id": "505917", "Score": "1", "body": "A lack of reproducible example. I have no idea how to test it, thus there's no way to make changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T13:49:41.993", "Id": "506057", "Score": "0", "body": "The reason for removing points from `EdgesCoordinateList` was to avoid possible duplicates and to avoid the possibility of iterating through data that had already been taken care of on previous cycles. I know that you would typically not want to modify source data, but I could not think of another method of doing this." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T13:13:02.430", "Id": "256227", "Score": "2", "Tags": [ "c#" ], "Title": "Split a list of points into a list of lines in C#" }
256227
<p>I have been solving the problem from UVA 101. In this problem, there will be at most <code>24</code> position in a row at beginning, and this array is zero-indexed, and for each position <code>i</code> there will be a single block also numbered <code>i</code>. The input will give you a number <code>n</code> which means how many command will follow. There are four kinds of commands:</p> <p>Say A, B are block number.</p> <ol> <li>Move A onto B: put all blocks above A, B to their initial positions, i.e. block <code>i</code> will back to pos <code>i</code>, then move A onto B.</li> <li>Move A over B: put all blocks above A to their ... (the same as 1.).</li> <li>Pile A onto B: put all blocks above B to their initial positions, then move the entire pile start from A onto B.</li> <li>Pile A over B: move the entire pile start from A to the pile contains B.</li> </ol> <p>Execute those <code>n</code> commands from input and print the result of all pos', each stack is printed from bottom to top.</p> <p>Can you please review it and provide me with feedback? Those I marked <code>&lt;&lt;&lt;&lt;&lt;...&lt;&lt;&lt; ?[123]</code> are the parts I think could be optimized.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdbool.h&gt; #define COMMAND_BUFFER 5 #define ADJ_BUFFER 5 #define N_MAX 25 #define STRING_EQUAL(a, b) (strcmp((a), (b))==0) // string compare. int table[N_MAX][N_MAX]; int atPos[N_MAX]; int size[N_MAX]; void array_init(); void put_back_all_above(int above); void pile_from_block_to_pos(int above, int toPos); void move_top_from_pos_to_pos(int fromPos, int toPos); int get_top_from_pos(int pos); int main() { array_init(); int n; if (scanf(&quot;%d&quot;, &amp;n) != 1) // To suppress warning on Visual Studio &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; ?1 return 1; int from, to; const char command[COMMAND_BUFFER] = { 0 }, adj[ADJ_BUFFER] = { 0 }; while (scanf(&quot; %[a-z]&quot;, command) != EOF &amp;&amp; !STRING_EQUAL(command, &quot;quit&quot;) &amp;&amp; scanf(&quot;%d%s%d&quot;, &amp;from, adj, &amp;to) == 3) { // will return the success # of read. // printf(&quot;%s %d %s %d\n&quot;, command, from, adj, to); if (from == to || atPos[from] == atPos[to]) continue ; if (STRING_EQUAL(command, &quot;move&quot;) &amp;&amp; STRING_EQUAL(adj, &quot;onto&quot;)) { put_back_all_above(from); put_back_all_above(to); move_top_from_pos_to_pos(atPos[from], atPos[to]) ; } else if (STRING_EQUAL(command, &quot;move&quot;) &amp;&amp; STRING_EQUAL(adj, &quot;over&quot;)) { put_back_all_above(from); move_top_from_pos_to_pos(atPos[from], atPos[to]) ; } else if (STRING_EQUAL(command, &quot;pile&quot;) &amp;&amp; STRING_EQUAL(adj, &quot;onto&quot;)) { put_back_all_above(to); pile_from_block_to_pos(from, atPos[to]) ; } else if (STRING_EQUAL(command, &quot;pile&quot;) &amp;&amp; STRING_EQUAL(adj, &quot;over&quot;)) { pile_from_block_to_pos(from, atPos[to]); } } for (int pos = 0; pos &lt; n; ++pos) { // print result &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;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; ?2 printf(&quot;%d:&quot;, pos); for (int j = 0; j &lt; size[pos]; ++j) printf(&quot; %d&quot;, table[atPos[pos]][j]); printf(&quot;\n&quot;); } return 0; } void array_init() { for (int i = 0; i &lt; N_MAX; ++i) { table[i][0] = i; atPos[i] = i; size[i] = 1; } } void put_back_all_above(int newTop) { int currentPos = atPos[newTop]; while (get_top_from_pos(currentPos) != newTop) move_top_from_pos_to_pos(currentPos, get_top_from_pos(currentPos)) ; } void pile_from_block_to_pos(int block, int toPos) { int blockIndex = -1; int blockOldPos = atPos[block]; for (int i = 0; i &lt; size[blockOldPos]; ++i) if (table[blockOldPos][i] == block) { blockIndex = i; break; } int pileSize = size[blockOldPos] - blockIndex; // Compute the size of pile to be moved. size[blockOldPos] -= pileSize; for (int i = 0; i &lt; pileSize; ++i) { int movedBlock = table[blockOldPos][size[blockOldPos]+i]; table[toPos][size[toPos]++] = movedBlock; atPos[movedBlock] = toPos; } } void move_top_from_pos_to_pos(int fromPos, int toPos) { table[toPos][size[toPos]++] = table[fromPos][--size[fromPos]]; // &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;&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; ?3 atPos[get_top_from_pos(toPos)] = toPos; } int get_top_from_pos(int pos) { return table[pos][size[pos]-1]; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T17:41:42.307", "Id": "505828", "Score": "0", "body": "That would probably be simpler with a [lexer](https://re2c.org/)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T14:23:06.793", "Id": "256230", "Score": "0", "Tags": [ "algorithm", "c", "programming-challenge", "stack" ], "Title": "UVA 101 - \"The Blocks Problem\"" }
256230
<p>I have been testing a number of kernel builds and I decide to have a go at writing some Python code. The idea is to select which kernel to boot on the next reboot. I could have done it in Bash but fancied a new experience, hence I had a go at Python.</p> <p>I've been testing under bash under Linux(Debian)</p> <p>Would love some feedback:</p> <p>Summary:</p> <ul> <li>Read the <code>/boot/grub/grub.cfg</code> file</li> <li>Extract the kernel names</li> <li>Present a simple menu</li> <li>Select the kernel</li> <li>Exit, printing the <code>grub-reboot</code> command (not executed)</li> </ul> <pre><code>#!/usr/bin/env python # # Read a grub.cfg file and parse the entries import re from simple_term_menu import TerminalMenu # Get current kernels from grub.cfg in correct format def get_kernels(menu_items): majorcount=0 mincount=0 with open('/boot/grub/grub.cfg',mode='r') as file: for line in file: # Check if line will contains either the string 'menu' or 'submenu' if re.match(r'^menu',line) or re.match(r'^submenu',line): try: # Find the menu string between single quotes entry = re.search('\'(.+?)\'', line).group(1) menu_items.append('{} - {}'.format(majorcount,entry)) majorcount += 1 except: continue # Check to see if the line begins with &lt;TAB&gt;menu if so looks like a submenu entry elif re.match(r'\tmenu',line): entry = re.search('\'(.+?)\'', line).group(1) menu_items.append('{}&gt;{} - {}'.format(majorcount,mincount,entry)) mincount +=1 # # Before we return add an Exit to the end of the menu majorcount += 1 menu_items.append('{} - Exit'.format(majorcount)) return ######### # # Print a simple Menu on the screen def print_menu(menu_items): cli_menu_title=' Grub Kernel Selection \n' cli_menu=TerminalMenu(menu_items,title=cli_menu_title,clear_screen=True, clear_menu_on_exit=False) menu_index=cli_menu.show() return menu_index ######### def main(): menu_items=[] get_kernels(menu_items) index=print_menu(menu_items) # # Now extract the string to pass to 'grub-reboot'. If 'Exit' choosen then just end # As 'Exit' will be the last entry if the index == the length of menu_items then assume 'Exit' # NB index starts at zero so will never match the length of menu_items, so increment it first if (index + 1) != len(menu_items): print(' grub-reboot {}'.format(re.match(&quot;(.*?) &quot;,menu_items[index]).group())) else: print('Exiting not kernel selected..') ######### if __name__ == '__main__': main() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T15:01:30.207", "Id": "256232", "Score": "4", "Tags": [ "python", "kernel" ], "Title": "Choose a kernel for next system boot" }
256232
<p>I wanted to build a <strong>Inverse Document Frequency</strong> function, because in my opinion was not easy to do with scikit and I wanted also to show how it works for educational reasons.</p> <p><a href="https://stackoverflow.com/questions/48431173/is-there-a-way-to-get-only-the-idf-values-of-words-using-scikit-or-any-other-pyt?rq=1">Also reading this question on stack.</a></p> <p>So I build this function. It works, not sure about the efficency of my solution.</p> <p>Let me know what do you think.</p> <pre><code>def idf(corpora,term=&quot;None&quot;): &quot;&quot;&quot;A function for calculating IDF, it takes a list of list as corpora, a term &quot;t&quot; and returns the relative IDF&quot;&quot;&quot; occurences=sum([ 1 for sublist in test for x in sublist if term in x]) tot_doc=len(corpora) if occurences==0: print(&quot;Error&quot;) else: idf=round(1+np.log(tot_doc/occurences),3) return idf test=[['I like beer'],['I like craft beers'],['I like ALE craft beers'], ['If I have to choose a craft beer, I will take the IPA craft beer']] beer=idf(corpora=test,term='beer') craft_beer=idf(corpora=test,term='craft') ipa=idf(corpora=test,term='IPA') print(beer) print(craft_beer) print(ipa) </code></pre> <p>Output:</p> <pre><code> 1.0 1.288 2.386 </code></pre>
[]
[ { "body": "<ul>\n<li>Use of global variable<br />\nIn your function, you use <code>test</code> from the global scope in the comprehension which can lead to nasty side effects.</li>\n<li>Type hints and formatting<br />\nType hints and proper formatting help future readers understand the code easier. Modern code editors and static code analysis tools can also use them.</li>\n<li>Docstring<br />\nA function docstring also helps future users to understand the code.</li>\n<li>Raise <code>ValueError</code> if no match<br />\nPrinting <code>Error</code> is not a good way to notify users of this function that something went wrong. What is the problem? Also if you dont return anything in this case, the function returns <code>None</code> with no errors, which can lead to other, harder to find errors later.</li>\n<li>Use generator in counting sum<br />\nYou dont need to create a list to count the occurences, you can just use a generator expression inside the <code>sum</code>.</li>\n<li>No need for list of lists<br />\nMaybe you have a reason for this, but you dont need the list of lists data structure for your example.</li>\n<li>Use python builtins<br />\nYou dont need numpy for this task, using python builtins is enough. This way, you dont have to install numpy if you only want to use this function.</li>\n</ul>\n<p>Putting it all together, my reviewed version looks like this.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import math\nfrom typing import List\n\ndef inverse_document_frequency(corpora: List[str], term: str) -&gt; float:\n &quot;&quot;&quot;\n Calculates Inverse Document Frequency.\n\n Arguments:\n corpora (List[str]): List of strings to check for term 'term'\n term (str): Term to count in 'corpora'\n\n Returns:\n float: Inverse document frequency, defined as\n 1 + log(length of corpora / occurrences of term)\n Rounded to 3 decimal places.\n &quot;&quot;&quot;\n\n occurences = sum(1 for string in corpora if term in string)\n if occurences == 0:\n raise ValueError(f&quot;No occurrences of term '{term}' in 'corpora'.&quot;)\n else:\n return round(1 + math.log(len(corpora) / occurences), 3)\n\ntest = [\n &quot;I like beer&quot;,\n &quot;I like craft beers&quot;,\n &quot;I like ALE craft beers&quot;,\n &quot;If I have to choose a craft beer, I will take the IPA craft beer&quot;,\n]\n\nbeer = inverse_document_frequency(corpora=test, term=&quot;beer&quot;)\ncraft_beer = inverse_document_frequency(corpora=test, term=&quot;craft&quot;)\nipa = inverse_document_frequency(corpora=test, term=&quot;IPA&quot;)\nprint(beer)\nprint(craft_beer)\nprint(ipa)\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T13:45:13.090", "Id": "505876", "Score": "0", "body": "Thank you for the feedback they are very useful. The list of list is because in the code for other reasons I use `gensim` and it takes as input for `TfidfModel` a list of list, so I tried to be consistent with this way to pass input documents from a `corpora`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T17:50:25.483", "Id": "256237", "ParentId": "256233", "Score": "2" } } ]
{ "AcceptedAnswerId": "256237", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T15:05:01.940", "Id": "256233", "Score": "1", "Tags": [ "python", "numpy", "natural-language-processing" ], "Title": "IDF Function with a list of list" }
256233
<p><strong>Overview of the Question</strong></p> <p>I would like to ask for performance/scalability feedback on an <code>R</code> function that I recently wrote. I have a large 4-column dataframe (the <code>lookup_dataframe</code>; i.e., output of a simulation study). The first column contains an integer value and the other three columns parameter values that correspond to that integer value.</p> <p>I have a second dataframe (<code>data</code>), that contains a column of <code>input</code> values. For each input value, I want to look up (from the <code>lookup_dataframe</code>) a possible combination of parameters that led to that input value.</p> <p><strong>Create some sample data</strong></p> <pre class="lang-r prettyprint-override"><code># Load packages library(furrr) #&gt; Loading required package: future library(tidyverse) # Set amount of cores plan(multisession, workers = 4) # Set seed set.seed(123) # Create `data` data &lt;- data.frame(input = raster::sampleInt(n = 800, size = 1000, replace = TRUE)) %&gt;% mutate(status = sample(0:1, n(), replace = TRUE), factor = sample(c(&quot;A&quot;, &quot;B&quot;), n(), replace = TRUE)) # Create `lookup_dataframe` lookup_dataframe &lt;- data.frame(value = rep(1:800, each = 2500), param_A = rnorm(n = 2e6), param_B = rnorm(n = 2e6), param_C = rnorm(n = 2e6)) </code></pre> <p><strong>Write function to look up data</strong></p> <p>I wrote a function that takes an input value, filters the <code>lookup_dataframe</code> on that value and randomly selects a row. The row then contains the value + the three parameters.</p> <pre class="lang-r prettyprint-override"><code>func_input_to_param &lt;- function(input){ lookup_dataframe %&gt;% filter(input == value) %&gt;% select(-value) %&gt;% sample_n(size = 1, replace = TRUE) %&gt;% flatten_dbl() } </code></pre> <p><strong>Map function to input data</strong></p> <p>Finally, I map the function to the input data, stitch both dataframes together, and the job is done! Note, I am using the <code>furrr</code> package with the <code>future_map</code> function to perform the mapping in parallel.</p> <pre class="lang-r prettyprint-override"><code>param_dataframe &lt;- future_map(.x = data$input, .f = func_input_to_param, .progress = TRUE, .options = furrr_options(seed = TRUE)) param_dataframe &lt;- do.call(rbind, param_dataframe) %&gt;% as_tibble(.name_repair = ~ c(&quot;param_A&quot;, &quot;param_B&quot;, &quot;param_C&quot;)) %&gt;% cbind(data, .) head(param_dataframe, 5) #&gt; input status factor param_A param_B param_C #&gt; 1 231 0 A 0.4533840 -0.4965135 -0.3215218 #&gt; 2 631 1 A 1.1109426 0.8285732 -0.6635507 #&gt; 3 328 1 A 0.9866890 -1.5464006 0.9079893 #&gt; 4 707 0 B -1.8231198 -1.2731512 1.1951422 #&gt; 5 753 1 B -0.5865885 -0.6276842 1.3558658 </code></pre> <p><strong>Feedback request</strong></p> <p>First of all, I really appreciate any feedback you can provide (of course, also not performance-related)! But I wanted to ask specifically for feedback on the code's performance and scalability. For example, if the <code>input data</code> has a <code>size=1000</code> the code is fast enough. However, input <code>size=10e6</code> takes forever to run. How am I able to speed up this code?</p> <p>It feels like a straightforward problem, so I was wondering if there are smarter ways to approach this problem?</p> <p><sup>Created in 2021 by the <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex package</a> (v1.0.0)</sup></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T16:14:51.590", "Id": "256235", "Score": "1", "Tags": [ "performance", "r" ], "Title": "Search rows in dataframe corresponding to a value in R - Performance & Scalability" }
256235
<p>I run into a performance bottleneck in a program. I have to generate all permutations for a given sequence with size up to <code>n=11</code>.</p> <p>My code:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;chrono&gt; #include &lt;iostream&gt; #include &lt;numeric&gt; #include &lt;vector&gt; int factorial(int n) { if (n == 0) { return 1; } return n * factorial(n - 1); } std::vector&lt;std::vector&lt;int&gt;&gt; generatePermutations(int size) { std::vector&lt;int&gt; sequence(size); std::iota(sequence.begin(), sequence.end(), 1); std::vector&lt;std::vector&lt;int&gt;&gt; permutations; permutations.reserve(factorial(sequence.size())); do { permutations.emplace_back(sequence); } while (std::next_permutation(sequence.begin(), sequence.end())); return permutations; } int main() { for (int i = 2; i &lt;= 11; ++i) { auto t1 = std::chrono::high_resolution_clock::now(); auto permutations = generatePermutations(i); auto t2 = std::chrono::high_resolution_clock::now(); std::cout &lt;&lt; &quot;i:\t&quot; &lt;&lt; i &lt;&lt; &quot;\tpermutation count:\t&quot; &lt;&lt; permutations.size() &lt;&lt; &quot;\ttime ms:\t&quot; &lt;&lt; std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(t2 - t1).count() &lt;&lt; '\n'; } } </code></pre> <p>The Output:</p> <pre><code>i: 2 permutation count: 2 time ms: 0 i: 3 permutation count: 6 time ms: 0 i: 4 permutation count: 24 time ms: 0 i: 5 permutation count: 120 time ms: 0 i: 6 permutation count: 720 time ms: 0 i: 7 permutation count: 5040 time ms: 1 i: 8 permutation count: 40320 time ms: 10 i: 9 permutation count: 362880 time ms: 94 i: 10 permutation count: 3628800 time ms: 944 i: 11 permutation count: 39916800 time ms: 10569 </code></pre> <p>As you can see the permutations count gets big very fast because the permutation count is <code>array.size!</code>, e.g. <code>1*2*3*4*5*6*7*8*9*10*11 for n=11</code></p> <p>I need to be a lot faster than 10s for n = 11.</p> <p>I wonder is there a faster way than using <code>std::next_permutation</code>? Or is there an faster approach with threading?</p> <p>edit:</p> <p>Since the requirements were stated as not clear for performance optimizations I want to summarize them here:</p> <p>-generate all permutations of a given sequence.</p> <p>-generated permutations don't need to be in a specific order. Currently I use <code>std::next_permuation</code> which generates them in order. Is there an algorithm which does it faster in not specific order?</p> <p>-generated permutations must be possible to traverse over. In my code I used a <code>std::vector&lt;int&gt;</code> to store each permutation. Any other container is fine too if it is faster.</p> <p>-generated permutations need to be read but never modified or deleted.</p> <p>-generation needs to be very fast because the count of permutations gets very high (~40mio permutations for n=11)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T19:09:10.010", "Id": "505834", "Score": "4", "body": "What is the challenge actually demanding? Sounds a bit like an XY problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T21:00:47.813", "Id": "505842", "Score": "1", "body": "i added the missing code for the output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T14:17:53.010", "Id": "505877", "Score": "4", "body": "For anyone in the Close Vote Queue. The code works and this is a performance question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T08:49:17.680", "Id": "505946", "Score": "2", "body": "If the requirement was to put out permutation count and some measure of time, you'd just need to compute factorials and some values increasing impressively slowly. Guessing there's more to it: Pray [present enough context to give helpful reviews](https://codereview.stackexchange.com/help/how-to-ask) - what, in your project, will the result of `generatePermutations()` be used for? Otherwise, have a look at *stdlib*'s implementation and, say, [Python's \"on-demand\" one](https://docs.python.org/3/library/itertools.html#itertools.permutations), and guess how much room for improvement is left." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T20:08:00.153", "Id": "505995", "Score": "0", "body": "I edited the question and tried to give more context. If you are interested the permutation generation is part of a program which solves the NxN Skyscraper problem on Codewars: `https://www.codewars.com/kata/5f7f023834659f0015581df1`. I monitored my whole program and found out the permutation part is the slowest. Since all the unit tests on codewars have to past in <12 seconds I cannot pass." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T10:45:15.050", "Id": "506551", "Score": "1", "body": "So, you don't actually need all the permutations at once, you just need them one at a time? Or do you just need the number of permutations, as you show in your `main`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T16:46:44.683", "Id": "506577", "Score": "1", "body": "I need to store all permutations in a container. Then I inspect them after certain criterias and sort out certain permutations. I think I will ask annother question showing the whole program (If it is not to long with 1400 lines)." } ]
[ { "body": "<p>The problem here isn't with generating the permutations, it is with memory management. One way to visually see this is to replace the <code>\\n</code> at the end of your output with <code>std::endl</code> so you see the results of each iteration at the end of the loop. The delay between the output of the last line and the program ending is all due to freeing memory.</p>\n<p>One way to address this is to allocate one big block of memory to hold all the permutations, rather than a bunch of small vectors. Create a class to hold and store all your permutations and handle accessing the results.</p>\n<p>Here's a basic implementation of what such a class could look like:</p>\n<pre><code>class Permutations {\npublic:\n Permutations(std::size_t sz);\n /*see below*/operator[](std::size_t elem) const;\n std::size_t size() const { return num_perms; }\n\nprivate:\n std::size_t num_e; // number of elements we're permuting\n std::size_t num_perms; // total number of permutations\n std::vector&lt;int&gt; permutations;\n};\n\nPermutations::Permutations(std::size_t sz): num_e(sz) {\n std::vector&lt;int&gt; sequence(num_e);\n std::iota(sequence.begin(), sequence.end(), 1);\n\n auto f = factorial(sequence.size());\n num_perms = f;\n permutations.reserve(f * num_e);\n int *p = &amp;permutations[0];\n\n do {\n std::copy(sequence.begin(), sequence.end(), p);\n p += num_e;\n } while (std::next_permutation(sequence.begin(), sequence.end()));\n};\n</code></pre>\n<p>In your main, you'd replace <code>auto permutations = generatePermutations(i);</code> with</p>\n<pre><code>Permutations permutations(i);\n</code></pre>\n<p>then access it as you do with the nested vectors. This generates the permutations in much less time.</p>\n<p>To access the individual permutations, the <code>operator[]</code> could return a <code>std::vector&lt;int&gt;</code> and copy in the corresponding elements. Other possibilities exist.</p>\n<p>To support iterator functionality (like in a range-based for loop), you can create an iterator class and add <code>begin</code> and <code>end</code> members to <code>Permutations</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T21:10:30.353", "Id": "505844", "Score": "1", "body": "So if I understand correctly the one `vector<int>` holds all the permutations one after each other? And because we have one continuous space instead of many small ones its faster since only one reallocation happens and not like 40mio with n=11...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T21:22:33.597", "Id": "505845", "Score": "1", "body": "@Sandro4912 That's correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T22:11:23.103", "Id": "505846", "Score": "0", "body": "since I want to read the permutations a lot but never modify them I guess I should return a `const std::vector<int>&` with operator []" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T00:47:10.423", "Id": "505852", "Score": "1", "body": "@Sandro4912 No, because you're constructing the vector to return the permutation, you need to return a complete vector, not a reference (which would be dangling, unless you add a member to the class to hold the constructed vector and avoid the repeated memory allocation costs). Alternatively you could return a pointer to the combination that is stored if you have some other way (or returned value) to know how long it is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T11:13:20.667", "Id": "505868", "Score": "0", "body": "I tried your approach but it still takes 6 seconds to generate all permuations for size n=11. Is there a way to reduce the time further?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T12:40:05.127", "Id": "505875", "Score": "0", "body": "@Sandro4912 That means the code almost doubled in speed, that's very good already. Perhaps the problem is with the algorithm, not the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T15:22:23.323", "Id": "505880", "Score": "0", "body": "@Sandro4912 In my tests, the n=11 case takes less than 20% of the time as your original code (a bit over half a second vs. just over 3 seconds). Do you have optimizations enabled?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T15:23:21.433", "Id": "505881", "Score": "0", "body": "i just compiled it with the basic `g++ test.cpp`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T23:15:25.870", "Id": "505920", "Score": "0", "body": "im thinking about using heaps algorithm to speed up further: https://en.wikipedia.org/wiki/Heap%27s_algorithm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T10:26:25.083", "Id": "505948", "Score": "0", "body": "@Sandro4912 Performance profiling on unoptimized builds is not going to give you the speediest results, naturally. Consider running `g++ -O3 -Wall test.cpp` instead for better performance and more warnings, and read-up on [compiler options](https://bytes.usc.edu/cs104/wiki/gcc/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T20:57:30.557", "Id": "506000", "Score": "0", "body": "op[] should really return a C++20 `std::span`, respectively a backport for C++17 like `gsl::span` or `boost::span`, just to avoid allocations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T06:13:17.527", "Id": "506019", "Score": "0", "body": "since the code is for codewars Im limited to c++17 with no additional librariers. But I guess I could add a simple span type myself which has `ptr + size`" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T18:51:51.003", "Id": "256239", "ParentId": "256236", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T17:40:25.110", "Id": "256236", "Score": "-1", "Tags": [ "c++", "performance", "time-limit-exceeded", "c++17", "combinatorics" ], "Title": "Generating permutations fast" }
256236
<p>Since Easter holidays are close, I have decided to develop my Android skills by writing an Android app that calculate that date for the Western and Easter calendars.</p> <p>The formulas were gotten from the Internet. It is a simple app where, you enter the year and you get the dates for both calendars in a <code>TextView</code>, I've used <code>EditText</code> as labels and made them unclickable, they appear when the dates are visible and get hidden when the dates are not show.</p> <p>I do not have any professional or internship experience whatsoever. Any input would help. It was built and compiled on Android Studio 4.1.2 and ran on my device.</p> <p>Here is the code for the XML.</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot;&gt; &lt;TextView android:id=&quot;@+id/textView&quot; android:layout_width=&quot;459dp&quot; android:layout_height=&quot;56dp&quot; android:layout_marginTop=&quot;8dp&quot; android:layout_marginBottom=&quot;8dp&quot; android:text=&quot;@string/welcome&quot; android:textSize=&quot;22sp&quot; app:layout_constraintBottom_toTopOf=&quot;@+id/editTextDate&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintHorizontal_bias=&quot;0.5&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; android:gravity=&quot;center&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt; &lt;EditText android:id=&quot;@+id/editTextDate&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;46dp&quot; android:layout_marginTop=&quot;16dp&quot; android:ems=&quot;10&quot; android:gravity=&quot;center&quot; android:maxLength=&quot;4&quot; android:digits=&quot;0123456789&quot; android:inputType=&quot;date&quot; android:textSize=&quot;22sp&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintHorizontal_bias=&quot;0.5&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/textView&quot; /&gt; &lt;TextView android:id=&quot;@+id/textViewWestern&quot; android:layout_width=&quot;150dp&quot; android:layout_height=&quot;48dp&quot; android:layout_marginTop=&quot;60dp&quot; android:gravity=&quot;center&quot; android:text=&quot;&quot; android:textSize=&quot;22sp&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintHorizontal_bias=&quot;0.045&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/editTextDate&quot; /&gt; &lt;TextView android:id=&quot;@+id/textViewEastern&quot; android:layout_width=&quot;150dp&quot; android:layout_height=&quot;48dp&quot; android:layout_marginTop=&quot;60dp&quot; android:gravity=&quot;center&quot; android:text=&quot;&quot; android:textSize=&quot;22sp&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintHorizontal_bias=&quot;0.969&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/editTextDate&quot; /&gt; &lt;EditText android:id=&quot;@+id/western&quot; android:layout_width=&quot;150dp&quot; android:layout_height=&quot;44dp&quot; android:layout_marginStart=&quot;12dp&quot; android:layout_marginTop=&quot;16dp&quot; android:ems=&quot;10&quot; android:focusable=&quot;false&quot; android:focusableInTouchMode=&quot;false&quot; android:gravity=&quot;center&quot; android:inputType=&quot;textPersonName&quot; android:background=&quot;@android:color/transparent&quot; android:text=&quot;Western&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/editTextDate&quot; /&gt; &lt;EditText android:id=&quot;@+id/eastern&quot; android:layout_width=&quot;150dp&quot; android:layout_height=&quot;44dp&quot; android:layout_marginTop=&quot;16dp&quot; android:ems=&quot;10&quot; android:focusable=&quot;false&quot; android:focusableInTouchMode=&quot;false&quot; android:inputType=&quot;textPersonName&quot; android:text=&quot;Eastern&quot; android:background=&quot;@android:color/transparent&quot; android:gravity=&quot;center&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintHorizontal_bias=&quot;0.969&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toBottomOf=&quot;@+id/editTextDate&quot; /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; </code></pre> <p>The <code>MainActivity.java</code> code.</p> <pre><code>package com.example.easterdate; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditText Edit = findViewById(R.id.editTextDate); final TextView text = findViewById(R.id.textViewWestern); final TextView textEastern = findViewById(R.id.textViewEastern); final EditText eastern = findViewById(R.id.eastern); final EditText western = findViewById(R.id.western); eastern.setVisibility(View.INVISIBLE); western.setVisibility(View.INVISIBLE); Edit.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.toString().trim().length() == 0 || Integer.parseInt(s.toString()) &lt; 1800) { text.setText(&quot;&quot;); textEastern.setText(&quot;&quot;); eastern.setVisibility(View.INVISIBLE); western.setVisibility(View.INVISIBLE); return; } EditText Edit = findViewById(R.id.editTextDate); int AN = Integer.parseInt(Edit.getText().toString()); int G = AN % 19; int C = AN / 100; int H = (C - C / 4 - (8 * C + 13) / 25 + 19 * G + 15) % 30; int I = H - (H / 28) * (1 - (H / 28) * (29 / (H + 1)) * ((21 - G) / 11)); int J = (AN + AN / 4 + I + 2 - C + C / 4) % 7; int L = I - J; int MP = 3 + (L + 40) / 44; int JP = L + 28 - 31 * (MP / 4); int mon, day; int A = AN % 19; int b = AN % 7; int ce = AN % 4; int d = (19 * A + 16) % 30; int e = (2 * ce + 4 * b + 6 * d) % 7; int f = (19 * A + 16) % 30; int key = f + e + 3; if (key &gt; 30) mon = 5; else mon = 4; if (key &gt; 30) day = key - 30; else day = key; String[] month = {&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;, &quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;}; eastern.setVisibility(View.VISIBLE); western.setVisibility(View.VISIBLE); text.setText(&quot;Sunday &quot; + JP + &quot; &quot; + month[MP - 1]); textEastern.setText(&quot;Sunday &quot; + day + &quot; &quot; + month[mon - 1]); } @Override public void afterTextChanged(Editable s) { } }); } } </code></pre> <p>How professional is this code? should I have used functions instead of imperative programming? The <code>TextWatcher</code> is used to prevent the app from crashing and to have the dates display on input, any better solution?</p>
[]
[ { "body": "<p>Small review</p>\n<blockquote>\n<p>How professional is this code?</p>\n</blockquote>\n<p><strong>Scant documentation</strong></p>\n<p>Dates of Easter are not easy to discern and rely on some arcane calculations. &quot;The formulas were gotten from the Internet.&quot; is insufficient documentation. Consider a programmer after you having to fix or extend this code. Better to include, in code, more details - at least a URL or citation to the source algorithm. <a href=\"https://codereview.stackexchange.com/q/217528/29485\">Example</a> below.\nI am not sure of OP's source.</p>\n<pre><code>Anonymous Gregorian algorithm: Meeus/Jones/Butcher\nDates of Easter\nAstronomical Algorithms 1991\nJean Meeus\nhttps://en.wikipedia.org/wiki/Computus#Anonymous_Gregorian_algorithm\n\nMeeus's Julian algorithm\nhttps://en.wikipedia.org/wiki/Computus#Meeus's_Julian_algorithm\n</code></pre>\n<p><strong>Range</strong></p>\n<p>Code deserves to document the range of years in which it is valid.</p>\n<p><strong>Precision in description</strong></p>\n<p>&quot;... calculate that date for the Western and Easter calendars.&quot;</p>\n<p>By &quot;Western&quot;, I suspect you mean <a href=\"https://en.wikipedia.org/wiki/Gregorian_calendar\" rel=\"nofollow noreferrer\">Gregorian calendar</a>.</p>\n<p>By &quot;Easter&quot;, I suspect you mean &quot;Eastern&quot; or <a href=\"https://en.wikipedia.org/wiki/Julian_calendar\" rel=\"nofollow noreferrer\">Julian calendar</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T15:56:31.637", "Id": "505883", "Score": "0", "body": "Anything else about code itself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T17:47:28.703", "Id": "505893", "Score": "0", "body": "Nothing more to add except to emphasize the need for more documentation in the code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T20:24:15.420", "Id": "256243", "ParentId": "256241", "Score": "1" } } ]
{ "AcceptedAnswerId": "256243", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T19:57:10.607", "Id": "256241", "Score": "2", "Tags": [ "beginner", "android" ], "Title": "Easter date calculator Android application" }
256241
<p>I have built a machine that juggles. An Arduino sends signals to stepper motor drivers that drive NEMA 23 size stepper motors.</p> <p><a href="https://i.stack.imgur.com/uiL93.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uiL93.gif" alt="juggling machine" /></a></p> <p>Video of the machine: <a href="https://youtu.be/-9zD_8erkck" rel="nofollow noreferrer">https://youtu.be/-9zD_8erkck</a></p> <p>Currently, each arm makes one revolution and then pauses while the other arm makes one revolution. One arm starts before the other arm comes to a complete stop, the amount of overlap is captured by the variable <code>stepover</code>.</p> <p>I would like to make the machine more consistent and run quieter with less vibration. How can I make it run smoother? Is there a way to do this where the hands will never come to a complete stop?</p> <p>The stepper motors are running at 800 steps per revolution. I have tried to using more steps/rev for smoother operation, but the <code>accelstepper</code> library will not run the motors fast enough.</p> <p>I have tried altering the values <code>max_acceleration</code>, <code>max_speed</code>, and <code>stepover</code>. I have not found a way to optimize these values.</p> <pre><code>#include &lt;AccelStepper.h&gt; AccelStepper stepper1(AccelStepper::DRIVER, 9, 8); AccelStepper stepper2(AccelStepper::DRIVER, 4, 3); int start = 0; int side = 0; int max_speed = 6000; int max_acceleration = 12000; int stepover = 300; int step_distance = 800; void setup() { stepper1.setMaxSpeed(max_speed); stepper2.setMaxSpeed(max_speed); stepper1.setAcceleration(1234); stepper2.setAcceleration(1234); stepper1.moveTo(600); stepper2.moveTo(-200); } void loop() { // This code gets the arms in the right place before startup if (start == 0) { while (abs(stepper1.distanceToGo()) != 0) { stepper1.run(); } while (abs(stepper2.distanceToGo()) != 0) { stepper2.run(); } start = 1; stepper1.setAcceleration(max_acceleration); stepper2.setAcceleration(max_acceleration); delay(500); } // This code moves the left arm if (abs(stepper1.distanceToGo()) == 0 and abs(stepper2.distanceToGo()) &lt; stepover and side == 0) { stepper1.moveTo(step_distance + stepper1.currentPosition()); side = 1; } // This code moves the right arm if (abs(stepper2.distanceToGo()) == 0 and abs(stepper1.distanceToGo()) &lt; stepover and side == 1) { stepper2.setCurrentPosition(0); stepper2.moveTo(step_distance); side = 0; } if (start == 1) { stepper2.run(); stepper1.run(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T09:11:12.447", "Id": "513795", "Score": "1", "body": "How many steps are available on the motor? Some datasheets I found seem to indicate 200 steps / revolution. Do you have a model with 800 steps? If it fits in memory, you could create an array, defining the desired speed for each step position. Your current logic would be something like `uint8_t speed[800] = {255, 255, 255, ... 255, 0, 0, 0, 0, ...., 0};`, either full speed or full stop. You could try to find the correct profile, and modify the values so that the motors is never completely stopping." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T15:00:46.713", "Id": "513808", "Score": "0", "body": "I am using stepper motors drivers that are capable of between 200 and 6400 steps per revolution. Computing the speeds and accelerations was too difficult for me, so I used the accelstepper library as a workaround." } ]
[ { "body": "<p>Inside <code>loop</code>, you're checking if some code should be run before startup. You could simply move the corresponding code to <code>setup</code>, and be sure it's only run once:</p>\n<pre><code>#include &lt;AccelStepper.h&gt;\nAccelStepper stepper1(AccelStepper::DRIVER, 9, 8);\nAccelStepper stepper2(AccelStepper::DRIVER, 4, 3);\n\nint side = 0;\nint max_speed = 6000;\nint max_acceleration = 12000;\nint stepover = 300;\nint step_distance = 800;\n\nvoid setup() {\n stepper1.setMaxSpeed(max_speed);\n stepper2.setMaxSpeed(max_speed);\n stepper1.setAcceleration(1234);\n stepper2.setAcceleration(1234);\n stepper1.moveTo(600);\n stepper2.moveTo(-200);\n\n while (abs(stepper1.distanceToGo()) &gt; 0) {\n stepper1.run();\n }\n while (abs(stepper2.distanceToGo()) &gt; 0) {\n stepper2.run();\n }\n stepper1.setAcceleration(max_acceleration);\n stepper2.setAcceleration(max_acceleration);\n delay(500);\n}\n\nvoid loop() {\n // This code moves the left arm\n if (abs(stepper1.distanceToGo()) == 0 and abs(stepper2.distanceToGo()) &lt; stepover and side == 0) {\n stepper1.moveTo(step_distance + stepper1.currentPosition());\n side = 1;\n }\n\n // This code moves the right arm\n if (abs(stepper2.distanceToGo()) == 0 and abs(stepper1.distanceToGo()) &lt; stepover and side == 1) {\n stepper2.setCurrentPosition(0);\n stepper2.moveTo(step_distance);\n side = 0;\n }\n\n stepper2.run();\n stepper1.run();\n}\n</code></pre>\n<ul>\n<li><code>abs</code> cannot be negative, so it might be clearer to replace <code>abs(...) != 0</code> by <code>abs(...) &gt; 0</code></li>\n<li><code>AccelStepper::move(long relative)</code> is defined as <code>moveTo(_currentPos + relative);</code> so you can probably replace your <code>moveTo</code> by <code>move</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-03T09:00:38.713", "Id": "260289", "ParentId": "256245", "Score": "2" } } ]
{ "AcceptedAnswerId": "260289", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-19T22:12:05.453", "Id": "256245", "Score": "4", "Tags": [ "c++", "arduino" ], "Title": "Arduino Code for Juggling Machine (Stepper Motors)" }
256245
<p>I have tried to remove the duplicate elements from the array using c language, here I am using 3 <code>for</code> loops to remove the duplicate elements.</p> <p>How can this optimize the code?</p> <p>Are there any other simple methods to remove the duplicate elements?</p> <p>Please help.</p> <pre><code>#include &lt;stdio.h&gt; #define MAX_SIZE 100 // Maximum size of the array int main() { int arr[MAX_SIZE]; int size; int i, j, k; printf(&quot;Enter size of the array : &quot;); scanf(&quot;%d&quot;, &amp;size); printf(&quot;Enter elements in array : &quot;); for(i=0; i&lt;size; i++) { scanf(&quot;%d&quot;, &amp;arr[i]); } for(i=0; i&lt;size; i++) { for(j=i+1; j&lt;size; j++) { if(arr[i] == arr[j]) { for(k=j; k&lt;size; k++) { arr[k] = arr[k + 1]; } size--; j--; } } } printf(&quot;\nArray elements after deleting duplicates : &quot;); for(i=0; i&lt;size; i++) { printf(&quot;%d\t&quot;, arr[i]); } return 0; } </code></pre>
[]
[ { "body": "<p>The code looks reasonably short and clear, that's good.</p>\n<p>It's obvious that you are a beginner though since your code layout is inconsistent in a few places. Formatting the code consistently is mostly a boring task, that's why several people wrote programs to perform this formatting automatically. There are many different formatting styles, try one that fits your own liking and use that style consistently.</p>\n<p>One of these programs is <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"nofollow noreferrer\">ClangFormat</a>.</p>\n<p>The result of formatting your code with the default settings is:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n\n#define MAX_SIZE 100 // Maximum size of the array\n\nint main() {\n\n int arr[MAX_SIZE];\n int size;\n int i, j, k;\n\n printf(&quot;Enter size of the array : &quot;);\n scanf(&quot;%d&quot;, &amp;size);\n\n printf(&quot;Enter elements in array : &quot;);\n for (i = 0; i &lt; size; i++) {\n scanf(&quot;%d&quot;, &amp;arr[i]);\n }\n\n for (i = 0; i &lt; size; i++) {\n for (j = i + 1; j &lt; size; j++) {\n\n if (arr[i] == arr[j]) {\n\n for (k = j; k &lt; size; k++) {\n arr[k] = arr[k + 1];\n }\n\n size--;\n\n j--;\n }\n }\n }\n\n printf(&quot;\\nArray elements after deleting duplicates : &quot;);\n for (i = 0; i &lt; size; i++) {\n printf(&quot;%d\\t&quot;, arr[i]);\n }\n\n return 0;\n}\n</code></pre>\n<p>In this version, the indentation of each line tells the reader which pieces of the code belong together. In your original version, this was not easy to see.</p>\n<p>To advanced programmers, the consistently formatted version looks calm and ordered, just like code should look like. Your original version instead looks chaotic. So far for the first impression.</p>\n<hr />\n<p>At your current stage of learning to program, you probably didn't learn how to define functions yet. Functions are an important way to structure your code, so that you can highlight the interesting parts of the code. In this case, the most interesting function of the code would be &quot;remove duplicate elements from an array, given by the first element and the size of the array&quot;. In C, this is written like this:</p>\n<pre class=\"lang-c prettyprint-override\"><code>// Removes duplicates, returns the new size of the array.\n// Keeps the order of the original elements, removing the duplicates that occur later.\nstatic int\nremove_duplicates_from_int_array(int *arr, int arr_size)\n{\n // TODO: actually implement this function\n}\n</code></pre>\n<p>Separating the code that removes the duplicates from the rest of the code makes it possible to test and analyze this part of the code on its own. For example you can write a standard test case:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;assert.h&gt;\n\n...\n\n size = 3;\n arr[0] = 1;\n arr[1] = 3;\n arr[2] = 1;\n\n size = remove_duplicates_from_int_array(arr, size);\n\n assert(size == 2);\n assert(arr[0] == 1);\n assert(arr[1] == 3);\n</code></pre>\n<p>With this code, you don't have to enter the size and the elements yourself anymore, which is a huge time-saver.</p>\n<p>Even better would be to extract this test code into its own function:</p>\n<pre class=\"lang-c prettyprint-override\"><code>static void\ntest_remove_duplicates_from_int_array(void) {\n // the code from above\n}\n</code></pre>\n<p>This allows you to quickly run this test code at the start of the program, to ensure that the code still works for the basic test cases, before you even start entering your own test cases manually. Again, this saves a lot of time.</p>\n<hr />\n<p>When you carefully inspect your code and &quot;run&quot; it with pen and paper, you will notice that the code reads data from outside of the array. This bug needs to be fixed before you should think about performance. Having fast and wrong code is usually worse than slow and correct code.</p>\n<p>This bug is not easy to find when you only look at the input and output, since everything seems to work fine. The tricky thing is that reading from outside of an array <em>invokes undefined behavior</em>, and this means that nothing at all is guaranteed when running this program. To really run into this undefined behavior, you have to enter the array size as 100 and actually enter exactly 100 array elements, something you probably never did since it is quite an effort. Therefore, for simpler testing, you should reduce MAX_SIZE to around 5. This allows you to test the edge cases more quickly.</p>\n<p>Except for this bug, the code looks reasonable. After you have fixed this bug, you can start thinking about making the code run faster. That's the tricky part though. As long as the array is short, your current approach is simple and easy to understand. Only if your arrays grow larger you need to get concerned about the algorithm's complexity, which is currently <span class=\"math-container\">\\$\\mathcal O(\\mathrm{size} \\cdot \\mathrm{size} \\cdot \\mathrm{size})\\$</span>. That is, for an array with 1000 elements, you would need a billion steps.</p>\n<p>To design a more efficient algorithm, print out a sheet of paper with 1000 random numbers and remove the duplicates manually, asking yourself what you do in each step and why. One idea may be to sort the numbers, after which it is much easier to remove the duplicates. But then you lose the original order of the numbers, which may or may not be acceptable.</p>\n<p>So far for a few ideas, I'm not going to solve everything for you. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T12:11:37.047", "Id": "256256", "ParentId": "256249", "Score": "1" } }, { "body": "<p>You already have a good answer from Roland, but I'll add a few small points.</p>\n<p>It's good practice to make every function declaration a <em>prototype</em> - specify the number and type of the arguments it accepts. So instead of <code>int main()</code>, we write <code>int main(void)</code> to indicated that it can only be called with no arguments.</p>\n<p>We can reduce <em>scope</em> of the index variables <code>i</code>, <code>j</code> and <code>k</code>. For example, <code>for (int i = 0; i &lt; size; ++i)</code>. There's no longer a gap between declaring <code>i</code> and assigning its first value of <code>0</code>, which reduces opportunities for error.</p>\n<p>When we call <code>scanf()</code>, it returns the number of values successfully converted. That may be less than the number of values we asked for. It's important not to use values that weren't successfully written:</p>\n<pre><code>if (scanf(&quot;%d&quot;, &amp;size) != 1) {\n fputs(&quot;format error&quot;, stderr);\n return 1;\n}\n</code></pre>\n<p>This test also handles the case where there is an error reading from the stream, in which case <code>scanf()</code> returns <code>EOF</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T16:33:09.340", "Id": "256265", "ParentId": "256249", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T04:12:31.943", "Id": "256249", "Score": "0", "Tags": [ "performance", "c", "array" ], "Title": "duplicate element removal" }
256249
<p>I just completed Pset 2 about the Hangman game that was issued from <a href="https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/assignments/" rel="nofollow noreferrer">OCW MIT</a>. The Pset has no available solution so that any comment regarding code writing best practices would be greatly appreciated (especially about defining functions and linking them to each other). Thank you and have a nice weekend y'all.</p> <pre><code># Hangman Game # ----------------------------------- import random import string WORDLIST_FILENAME = &quot;words.txt&quot; def load_words(): &quot;&quot;&quot; Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. &quot;&quot;&quot; print(&quot;Loading word list from file...&quot;) # inFile: file inFile = open(WORDLIST_FILENAME, 'r') # line: string line = inFile.readline() # wordlist: list of strings wordlist = line.split() print(&quot; &quot;, len(wordlist), &quot;words loaded.&quot;) return wordlist def choose_word(wordlist): &quot;&quot;&quot; wordlist (list): list of words (strings) Returns a word from wordlist at random &quot;&quot;&quot; return random.choice(wordlist) # end of helper code # ----------------------------------- # Load the list of words into the variable wordlist # so that it can be accessed from anywhere in the program wordlist = load_words() def is_word_guessed(secret_word, letters_guessed): ''' secret_word: string, the word the user is guessing; assumes all letters are lowercase letters_guessed: list (of letters), which letters have been guessed so far; assumes that all letters are lowercase returns: boolean, True if all the letters of secret_word are in letters_guessed; False otherwise ''' # FILL IN YOUR CODE HERE AND DELETE &quot;pass&quot; guess = str() for char in secret_word: for letter in letters_guessed: if char == letter: guess += char else: continue if guess == secret_word: return True else: return False def get_guessed_word(secret_word, letters_guessed): ''' secret_word: string, the word the user is guessing letters_guessed: list (of letters), which letters have been guessed so far returns: string, comprised of letters, underscores (_), and spaces that represents which letters in secret_word have been guessed so far. ''' # FILL IN YOUR CODE HERE AND DELETE &quot;pass&quot; showbox_list = list() for char in secret_word: showbox_list.append('_ ') for letter in letters_guessed: for count, char in enumerate(secret_word): if letter == char: showbox_list[count] = letter else: continue showbox_str = ''.join(showbox_list) return showbox_str def get_available_letters(letters_guessed): ''' letters_guessed: list (of letters), which letters have been guessed so far returns: string (of letters), comprised of letters that represents which letters have not yet been guessed. ''' # FILL IN YOUR CODE HERE AND DELETE &quot;pass&quot; english_letters = list(string.ascii_lowercase) for letter in letters_guessed: english_letters.remove(letter) english_letters_str = ''.join(english_letters) print('Available letters:', english_letters_str) return english_letters_str def hangman(secret_word): ''' secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secret_word contains and how many guesses s/he starts with. * The user should start with 6 guesses * Before each round, you should display to the user how many guesses s/he has left and the letters that the user has not yet guessed. * Ask the user to supply one guess per round. Remember to make sure that the user puts in a letter! * The user should receive feedback immediately after each guess about whether their guess appears in the computer's word. * After each guess, you should display to the user the partially guessed word so far. Follows the other limitations detailed in the problem write-up. ''' # FILL IN YOUR CODE HERE AND DELETE &quot;pass&quot; secret_word = choose_word(wordlist) letters_guessed = list() warnings_remaining = 3 guesses_remaining = 6 good_guess = 0 print(''' \n OOO-----------------------------------------------OOO \n Welcome to the Hangman!, I'm thinking of a word that is %d letters long. \n OOO-----------------------------------------------OOO \n ''' % len(secret_word)) while not is_word_guessed(secret_word, letters_guessed) and guesses_remaining &gt; 0: print(&quot;\nYou have %d guesses left.&quot; % guesses_remaining) get_available_letters(letters_guessed) letter = str.lower(input(&quot;Please guess a letter: &quot;)) if not letter or letter not in string.ascii_lowercase: if warnings_remaining != 0: warnings_remaining -= 1 print(&quot;That is not a valid letter. You have %d warning left.&quot; % warnings_remaining) else: print(&quot;That is not a valid letter. You have no warning left, so you lose one guess.&quot;) guesses_remaining -= 1 elif letter in letters_guessed: if warnings_remaining != 0: warnings_remaining -= 1 print(&quot;You've already guessed that letter. You have %d warning left.&quot; % warnings_remaining) else: print(&quot;You've already guessed that letter. You have no warning left, so you lose one guess.&quot;) guesses_remaining -= 1 else: letters_guessed.append(letter) if letter not in secret_word: print(&quot;That letter is not in my word.&quot;) if letter in 'aiueo': guesses_remaining -= 2 else: guesses_remaining -= 1 else: print(&quot;Good guess!&quot;) good_guess += 1 print(get_guessed_word(secret_word, letters_guessed)) print(&quot;\nOOO-----------------------------------------------------------------------OOO\n&quot;) if is_word_guessed(secret_word, letters_guessed): print(&quot;Congratulations, you won!&quot;) print(&quot;Your total score for this game is %d.&quot; % (good_guess * guesses_remaining)) if guesses_remaining == 0: print(&quot;Sorry, you ran out of guesses. The word was %s.&quot; % secret_word) # When you've completed your hangman function, scroll down to the bottom # of the file and uncomment the first two lines to test #(hint: you might want to pick your own # secret_word while you're doing your own testing) # ----------------------------------- def match_with_gaps(my_word, other_word): ''' my_word: string with _ characters, current guess of secret word other_word: string, regular English word returns: boolean, True if all the actual letters of my_word match the corresponding letters of other_word, or the letter is the special symbol _ , and my_word and other_word are of the same length; False otherwise: ''' # FILL IN YOUR CODE HERE AND DELETE &quot;pass&quot; my_word_stripped = my_word.replace(&quot; &quot;, &quot;&quot;) same_char = list() blank_stripped = list() if len(my_word_stripped) == len(other_word): for index, letter in enumerate(my_word_stripped): if letter in string.ascii_lowercase: same_char.append(index) else: blank_stripped.append(index) else: return False mws = '' ow = '' for index_same in same_char: for index_dif in blank_stripped: if other_word[index_dif] == other_word[index_same]: return False else: mws += my_word_stripped[index_same] ow += other_word[index_same] if mws == ow: return True else: return False def show_possible_matches(my_word): ''' my_word: string with _ characters, current guess of secret word returns: nothing, but should print out every word in wordlist that matches my_word Keep in mind that in hangman when a letter is guessed, all the positions at which that letter occurs in the secret word are revealed. Therefore, the hidden letter(_ ) cannot be one of the letters in the word that has already been revealed. ''' # FILL IN YOUR CODE HERE AND DELETE &quot;pass&quot; possible_matches = list() for i in wordlist: if match_with_gaps(my_word, i): possible_matches.append(i) spm = ' '.join(possible_matches) return spm def hangman_with_hints(secret_word): ''' secret_word: string, the secret word to guess. Starts up an interactive game of Hangman. * At the start of the game, let the user know how many letters the secret_word contains and how many guesses s/he starts with. * The user should start with 6 guesses * Before each round, you should display to the user how many guesses s/he has left and the letters that the user has not yet guessed. * Ask the user to supply one guess per round. Make sure to check that the user guesses a letter * The user should receive feedback immediately after each guess about whether their guess appears in the computer's word. * After each guess, you should display to the user the partially guessed word so far. * If the guess is the symbol *, print out all words in wordlist that matches the current guessed word. Follows the other limitations detailed in the problem write-up. ''' # FILL IN YOUR CODE HERE AND DELETE &quot;pass&quot; secret_word = choose_word(wordlist) letters_guessed = list() warnings_remaining = 3 guesses_remaining = 6 good_guess = 0 print(''' \n OOO-----------------------------------------------OOO \n Welcome to the Hangman+!, I'm thinking of a word that is %d letters long. \n OOO-----------------------------------------------OOO \n ''' % len(secret_word)) while not is_word_guessed(secret_word, letters_guessed) and guesses_remaining &gt; 0: print(&quot;\nYou have %d guesses left.&quot; % guesses_remaining) get_available_letters(letters_guessed) letter = str.lower(input(&quot;Please guess a letter: &quot;)) if letter == '*': print(&quot;Possible matches are:&quot;, show_possible_matches(get_guessed_word(secret_word, letters_guessed))) elif not letter or letter not in string.ascii_lowercase: if warnings_remaining != 0: warnings_remaining -= 1 print(&quot;That is not a valid letter. You have %d warning left.&quot; % warnings_remaining) else: print(&quot;That is not a valid letter. You have no warning left, so you lose one guess.&quot;) guesses_remaining -= 1 elif letter in letters_guessed: if warnings_remaining != 0: warnings_remaining -= 1 print(&quot;You've already guessed that letter. You have %d warning left.&quot; % warnings_remaining) else: print(&quot;You've already guessed that letter. You have no warning left, so you lose one guess.&quot;) guesses_remaining -= 1 else: letters_guessed.append(letter) if letter not in secret_word: print(&quot;That letter is not in my word.&quot;) if letter in 'aiueo': guesses_remaining -= 2 else: guesses_remaining -= 1 else: print(&quot;Good guess!&quot;) good_guess += 1 print(get_guessed_word(secret_word, letters_guessed)) print(&quot;\nOOO-----------------------------------------------------------------------OOO\n&quot;) if is_word_guessed(secret_word, letters_guessed): print(&quot;Congratulations, you won!&quot;) print(&quot;Your total score for this game is %d.&quot; % (good_guess * guesses_remaining)) if guesses_remaining == 0: print(&quot;Sorry, you ran out of guesses. The word was %s.&quot; % secret_word) # When you've completed your hangman_with_hint function, comment the two similar # lines above that were used to run the hangman function, and then uncomment # these two lines and run this file to test! # Hint: You might want to pick your own secret_word while you're testing. if __name__ == &quot;__main__&quot;: # pass # To test part 2, comment out the pass line above and # uncomment the following two lines. #secret_word = choose_word(wordlist) #hangman(secret_word) ############### # To test part 3 re-comment out the above lines and # uncomment the following two lines. secret_word = choose_word(wordlist) hangman_with_hints(secret_word) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T05:51:46.260", "Id": "505865", "Score": "1", "body": "Just changed it, thanks!" } ]
[ { "body": "<p>I'm going to go function by function and explain what I changed and why.</p>\n<p>Imports I used:</p>\n<pre><code>from typing import List\n</code></pre>\n<hr>\n<h1><code>load_words</code></h1>\n<pre><code>def load_words() -&gt; List[str]:\n &quot;&quot;&quot;\n Returns a list of valid words. Words are strings of lowercase letters.\n \n Depending on the size of the word list, this function may\n take a while to finish.\n &quot;&quot;&quot;\n with open(WORDLIST_FILENAME, 'r') as file:\n wordlist = [word.strip() for word in file.readlines()]\n return wordlist\n</code></pre>\n<p>I see that you have type hints above every variable. Luckily for you, you can do this inline with the exact same format.</p>\n<pre><code>variable: int = 10\n</code></pre>\n<p>Make sure you close files when you open them. If you don't want to worry about that, use a <code>with</code> statement, which will automatically close the file once you exit the context.</p>\n<p>You can also use type hints to display what types of parameters you accept, if any, and what types of values you return, if any.</p>\n<h1><code>choose_word</code></h1>\n<pre><code>def choose_word(wordlist: List[str]) -&gt; str:\n &quot;&quot;&quot;\n wordlist (list): list of words (strings)\n \n Returns a word from wordlist at random\n &quot;&quot;&quot;\n return random.choice(wordlist)\n</code></pre>\n<p>Only thing I changed here was adding type hints. Now it's clear <code>wordlist</code> is a List of string, and the function returns a string.</p>\n<h1><code>is_word_guessed</code></h1>\n<pre><code>def is_word_guessed(secret_word: str, letters_guessed: List[str]) -&gt; bool:\n '''\n secret_word: string, the word the user is guessing; assumes all letters are\n lowercase\n letters_guessed: list (of letters), which letters have been guessed so far;\n assumes that all letters are lowercase\n returns: boolean, True if all the letters of secret_word are in letters_guessed;\n False otherwise\n '''\n guess = &quot;&quot;\n for char in secret_word:\n for letter in letters_guessed:\n if char == letter:\n guess += char\n else:\n continue\n \n return guess == secret_word\n</code></pre>\n<p>Personally, I would just use <code>&quot;&quot;</code> when creating an empty string. Again, note the type hints.</p>\n<p>Instead of <code>return True else return False</code>, you can return the boolean condition that is being evaluated. It does the same exact thing, but it's shorter and looks a lot nicer.</p>\n<h1><code>get_guessed_word</code></h1>\n<pre><code>def get_guessed_word(secret_word: str, letters_guessed: List[str]) -&gt; str:\n '''\n secret_word: string, the word the user is guessing\n letters_guessed: list (of letters), which letters have been guessed so far\n returns: string, comprised of letters, underscores (_), and spaces that represents\n which letters in secret_word have been guessed so far.\n '''\n showbox_list = ['_ ' for _ in secret_word]\n for letter in letters_guessed:\n for count, char in enumerate(secret_word):\n if letter == char:\n showbox_list[count] = letter\n else:\n continue\n \n return ''.join(showbox_list)\n</code></pre>\n<p>Instead of using a traditional <code>for</code> loop, I would use list comprehension to construct your showbox list. The <code>_</code> variable just indicates that the variable used in the loop should be ignored. Instead of creating a variable, then returning that variable, just return the value you would have assigned to that variable. Again, type hints.</p>\n<h1><code>get_available_letters</code></h1>\n<pre><code>def get_available_letters(letters_guessed: List[str]) -&gt; str:\n '''\n letters_guessed: list (of letters), which letters have been guessed so far\n returns: string (of letters), comprised of letters that represents which letters have not\n yet been guessed.\n '''\n english_letters = [char for char in string.ascii_lowercase if char not in letters_guessed]\n \n english_letters_str = ''.join(english_letters)\n print('Available letters:', english_letters_str)\n \n return english_letters_str\n</code></pre>\n<p>Again, you can use list comprehension to construct your initial list. This adds every character in the <code>string.ascii_lowercase</code> list, but ONLY if the character is not in the <code>letters_guessed</code> list. Obligatory type hints point.</p>\n<h1><code>match_with_gaps</code></h1>\n<pre><code>def match_with_gaps(my_word: str, other_word: str) -&gt; bool:\n '''\n my_word: string with _ characters, current guess of secret word\n other_word: string, regular English word\n returns: boolean, True if all the actual letters of my_word match the \n corresponding letters of other_word, or the letter is the special symbol\n _ , and my_word and other_word are of the same length;\n False otherwise: \n '''\n my_word_stripped = my_word.replace(&quot; &quot;, &quot;&quot;)\n same_char = []\n blank_stripped = []\n if len(my_word_stripped) != len(other_word):\n return False\n for index, letter in enumerate(my_word_stripped):\n if letter in string.ascii_lowercase:\n same_char.append(index)\n else:\n blank_stripped.append(index)\n\n mws = ''\n ow = ''\n for index_same in same_char:\n for index_dif in blank_stripped:\n if other_word[index_dif] == other_word[index_same]:\n return False\n mws += my_word_stripped[index_same]\n ow += other_word[index_same]\n \n return mws == ow\n</code></pre>\n<p>The most important thing I want to stress here is <a href=\"https://wiki.c2.com/?GuardClause\" rel=\"nofollow noreferrer\">guard clauses</a>. These prevent you from having to indent into another context space. It makes your code look nicer, and is a good thing to practice.</p>\n<p>You don't need an <code>else</code> if the <code>if</code> returns from the function. Again, type hints and returning boolean expressions.</p>\n<h1><code>show_possible_matches</code></h1>\n<pre><code>def show_possible_matches(my_word: str) -&gt; str:\n '''\n my_word: string with _ characters, current guess of secret word\n returns: nothing, but should print out every word in wordlist that matches my_word\n Keep in mind that in hangman when a letter is guessed, all the positions\n at which that letter occurs in the secret word are revealed.\n Therefore, the hidden letter(_ ) cannot be one of the letters in the word\n that has already been revealed.\n\n '''\n possible_matches = [i for i in wordlist if match_with_gaps(my_word, i)]\n return ' '.join(possible_matches)\n</code></pre>\n<p>Using list comprehension reduces the need for the <code>for</code> loop, allowing you to accomplish the same task in one line. Again, type hints.</p>\n<hr>\n<p>One more thing I'd like to add. You said that you initially didn't want to post the entire program because &quot;it was too long&quot;. Most of the length of your program comes down to docstrings. Now, this isn't inherently a bad thing. Looking through them, this looks like a problem set, and these are instructions. Thats fine. But keep in mind that docstrings should really only display what the function does, what parameters it accepts (if any), and what it returns. I personally think the <code>hangman_with_hints</code> docstring goes a little over the top (25 lines!), but that's just me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T06:31:49.297", "Id": "256251", "ParentId": "256250", "Score": "3" } } ]
{ "AcceptedAnswerId": "256251", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T05:38:56.970", "Id": "256250", "Score": "3", "Tags": [ "beginner", "python-3.x", "hangman" ], "Title": "Hangman Game from OCW MIT 6.0001 Pset No. 2" }
256250
<p>Here's the code I am trying to refactor. The same Http client is being used in each nested try with resource. I don't understand the rationale behind nesting client.execute() calls.</p> <p>The code tries to Post data to an endpoint if resource is missing and retries to Post to a backup endpoint if earlier call fails</p> <pre><code>public void makeSeveralApiCalls() throws Exception { try (final CloseableHttpClient client = HttpClients.createDefault()) { try (final CloseableHttpResponse response = client.execute(httpGetUri())){ if (response.getStatusLine().getStatusCode() == 404) { // Resource not found, Post data to Microservice A try (final CloseableHttpResponse nestedResponse = client.execute(httpPostToMicroserviceA())) { if (resp.getStatusLine().getStatusCode() == 201) { LOGGER.info(&quot;Success&quot;); } else { // Microservice A could not consume data, log error response final String responseString = EntityUtils.toString(resp.getEntity()); LOGGER.debug(&quot;Error response: &quot; + responseString); // Try to Post to Microservice B try (final CloseableHttpResponse subResponse = client.execute(httpPostToMicroserviceB())) { if (resp.getStatusLine().getStatusCode() == 201) { LOGGER.info(&quot;Success&quot;); } else { // Is this exception propagated to the caller? throw new RuntimeException(&quot;Very bad unrecoverable state&quot;); } } } } } } </code></pre> <p>Is this a valid way to call multiple executes on the same HTTP client in a nested fashion. Is it better to separate out each <code>client.execute()</code> call?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T12:31:27.330", "Id": "505873", "Score": "0", "body": "Welcome to the Code Review Community. Generally we don't answer `How to` questions because `How to` indicates that the code is not working as expected and we only review code that is working as expected. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) and [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic). The title of the question should also be about what the code does, and not what your concerns about the code are." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T15:32:17.590", "Id": "505882", "Score": "0", "body": "Are you the author and/or maintainer of this code? The following statement makes me wonder: “_I don't understand the rationale behind nesting client.execute() calls._” Per the site rules: [“_For licensing, moral, and procedural reasons, we cannot review code written by other programmers. We expect you, as the author, to understand why the code is written the way that it is._”](https://codereview.stackexchange.com/help/on-topic)" } ]
[ { "body": "<p>First of all you should split up this method into smaller ones. The inline comment give you a perfect sign what should be extracted.</p>\n<p>Also *try with resource&quot; can handle more than one resource in a single statement.</p>\n<pre><code>public void makeSeveralApiCalls() throws Exception {\n try (final CloseableHttpClient client = HttpClients.createDefault();\n final CloseableHttpResponse response = client.execute(httpGetUri());\n ){\n if (response.getStatusLine().getStatusCode() == 404) {\n // Resource not found\n postDataToMicroserviceA(client, response); \n }\n }\n}\n\nprivate void postDataToMicroserviceA(CloseableHttpClient client, CloseableHttpResponse response){\n try (final CloseableHttpResponse nestedResponse = client.execute(httpPostToMicroserviceA())) {\n if (resp.getStatusLine().getStatusCode() == 201) {\n LOGGER.info(&quot;Success&quot;);\n } else {\n // Microservice A could not consume data, \n logErrorResponse(client, response); \n }\n }\n}\n\nprivate void logErrorResponse(CloseableHttpClient client, CloseableHttpResponse response)\n final String responseString = EntityUtils.toString(resp.getEntity());\n LOGGER.debug(&quot;Error response: &quot; + responseString);\n // Try to Post to Microservice B\n try (final CloseableHttpResponse subResponse = client.execute(httpPostToMicroserviceB())) {\n if (resp.getStatusLine().getStatusCode() == 201) {\n LOGGER.info(&quot;Success&quot;);\n } else {\n // Is this exception propagated to the caller?\n throw new RuntimeException(&quot;Very bad unrecoverable state&quot;);\n }\n}\n</code></pre>\n<p>Of cause this could be optimized a bit more if you find a more generalized solution to merge <code>postDataToMicroserviceA()</code> and <code>logErrorResponse()</code>, since basically they do the same...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T09:55:18.930", "Id": "256254", "ParentId": "256252", "Score": "1" } } ]
{ "AcceptedAnswerId": "256254", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T07:26:23.440", "Id": "256252", "Score": "1", "Tags": [ "java", "api", "nested" ], "Title": "Posting data to endpoints" }
256252
<p>I'm a fairly new programmer and have been learning c++ for about 8 months now. I've written a program that can take either binary, hexadecimal, and decimal inputs and convert them to the other two values. For example, if the user inputs a binary value, then the program will output both decimal and hexadecimal conversions of the number. Unfortunately, the colouring of the output is unsatisfactory due to the fact that chaning colours in cmd changes the colour off all texts in that terminal. Instead of using the cmd colour commands, I used a custom header file provided by my teacher that didn't change the colour of all the texts in the terminal. Instead of adding the header file, I replaced all the custom colour commands with cmd colour commands, for convinience. Besides all that, it would mean a lot if you could review my code and point out on where I could improve on. Please keep in mind that I'm still new to programming in general and wouldn't understand some &quot;programmer/coding&quot; vocabulary.</p> <p>Thank you.</p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; #include &lt;string&gt; #include &lt;conio.h&gt; using namespace std; long long num_limit;//user input for decimal long long hex_remainder;//hexadecimal remainder long long hexint = 0;//integer value for user input char user_inp;//identifier for user input bool userinput = true;//validator for illegal input string hex_assign;//assiging hex remainder string value string bitassign = &quot;&quot;;//identifier assigning binary values to hex void load()//loading effect { int g, c;//loop counter cout &lt;&lt; &quot; &quot;; system(&quot;color 07&quot;); for (g = 1; g &lt;= 80; g++) { for (c = 1; c &lt;= 2850000; c++) {} cout &lt;&lt; &quot;*&quot;; } //used in void bit(), void hex(), and void dec() }//load void integer_only() { while (!num_limit &gt; 0)//checking for illegal input { cin.clear(); cin.ignore(1000, '\n'); system(&quot;color 04&quot;); cout &lt;&lt; &quot; Invalid input...try again: &quot;; system(&quot;color&quot;); cin &gt;&gt; num_limit;//user input cin.ignore(1000, '\n'); } //used in void bit(), void hex(), and void dec() }//integer_only void hexassign() { switch (hex_remainder)//using &lt;remainder&gt; as a switch to assign hex characters { case 0: hex_assign = &quot;0&quot;; break; case 1: hex_assign = &quot;1&quot;; break; case 2: hex_assign = &quot;2&quot;; break; case 3: hex_assign = &quot;3&quot;; break; case 4: hex_assign = &quot;4&quot;; break; case 5: hex_assign = &quot;5&quot;; break; case 6: hex_assign = &quot;6&quot;; break; case 7: hex_assign = &quot;7&quot;; break; case 8: hex_assign = &quot;8&quot;; break; case 9: hex_assign = &quot;9&quot;; break; case 10: hex_assign = &quot;A&quot;; break; case 11: hex_assign = &quot;B&quot;; break; case 12: hex_assign = &quot;C&quot;; break; case 13: hex_assign = &quot;D&quot;; break; case 14: hex_assign = &quot;E&quot;; break; case 15: hex_assign = &quot;F&quot;; break; } //used in void bit() and void dec() }//hexassign void hex_input_validator() { switch (user_inp) { case '0':userinput = true; break; case '1':userinput = true; break; case '2':userinput = true; break; case '3':userinput = true; break; case '4':userinput = true; break; case '5':userinput = true; break; case '6':userinput = true; break; case '7':userinput = true; break; case '8':userinput = true; break; case '9':userinput = true; break; case 'A':userinput = true; break; case 'B':userinput = true; break; case 'C':userinput = true; break; case 'D':userinput = true; break; case 'E':userinput = true; break; case 'F':userinput = true; break; default: userinput = false; } //used in void hex() }//hexinput_validator void hex_binary_assign() { switch (user_inp) { case '0':bitassign = &quot;0000 &quot;; break; case '1':bitassign = &quot;0001 &quot;; break; case '2':bitassign = &quot;0010 &quot;; break; case '3':bitassign = &quot;0011 &quot;; break; case '4':bitassign = &quot;0100 &quot;; break; case '5':bitassign = &quot;0101 &quot;; break; case '6':bitassign = &quot;0110 &quot;; break; case '7':bitassign = &quot;0111 &quot;; break; case '8':bitassign = &quot;1000 &quot;; break; case '9':bitassign = &quot;1001 &quot;; break; case 'A':bitassign = &quot;1010 &quot;; break; case 'B':bitassign = &quot;1011 &quot;; break; case 'C':bitassign = &quot;1100 &quot;; break; case 'D':bitassign = &quot;1101 &quot;; break; case 'E':bitassign = &quot;1110 &quot;; break; case 'F':bitassign = &quot;1111 &quot;; break; } //used in void hex() }//hex_binary_assign void hex_int_assign() { switch (user_inp) { case '0':hexint = 0; break; case '1':hexint = 1; break; case '2':hexint = 2; break; case '3':hexint = 3; break; case '4':hexint = 4; break; case '5':hexint = 5; break; case '6':hexint = 6; break; case '7':hexint = 7; break; case '8':hexint = 8; break; case '9':hexint = 9; break; case 'A':hexint = 10; break; case 'B':hexint = 11; break; case 'C':hexint = 12; break; case 'D':hexint = 13; break; case 'E':hexint = 14; break; case 'F':hexint = 15; break; } //used in void hex() }//hex_int_assign void bit()//binary input { char user_input = 'x';//user input (1/0) int num;//identifier assigned integer value for user input int i, v, y;//loop counter long long total_dec;//decimal value long long dec_count = 0;//total decimal value long long quotient = 0;//quotient for bimary long long decimal;//identifier to be used to find decimal value string hex_val = &quot;&quot;;//total hex value in one string bool hex = true;//validator for hex calculation system(&quot;color 09&quot;); cout &lt;&lt; &quot; Enter the total number of digits: &quot;; system(&quot;color&quot;); cin &gt;&gt; num_limit;//user input cin.ignore(1000, '\n'); integer_only();//checking for illegal input cout &lt;&lt; endl;//blank line y = num_limit;//assigning max index value value for (i = 0; i &lt; num_limit; i++) { system(&quot;color 09&quot;); cout &lt;&lt; &quot; Num #&quot; &lt;&lt; i + 1 &lt;&lt; &quot;: &quot;; system(&quot;color&quot;); user_input = _getwche();//user input cout &lt;&lt; endl;//blank line switch (user_input) { case '0':num = 0; break; case '1':num = 1; break; } while (user_input != '1' &amp;&amp; user_input != '0')//checking for illegal input { system(&quot;color 07&quot;); cout &lt;&lt; &quot; Invalid input...try again: &quot;; system(&quot;color&quot;); user_input = _getwche();//user input cout &lt;&lt; endl;//blank line switch (user_input) { case '0':num = 0; break; case '1':num = 1; break; } } total_dec = num * pow(2, (y - 1));//y-1 so that calculation is in reverse order dec_count += total_dec; y--; } decimal = dec_count; while (hex)//will run while &lt;hex&gt; is true { quotient = decimal / 16; hex_remainder = decimal % 16; decimal = quotient; hexassign();//assiging hex value hex_val += hex_assign; if (quotient == 0) { hex = false; }//hex is false when quotient is 0 } system(&quot;cls&quot;);//clearing screen load();//calling loading effect cout &lt;&lt; endl;//blank line system(&quot;color 06&quot;); cout &lt;&lt; &quot; Decimal value =========&gt; &quot;; system(&quot;color&quot;); cout &lt;&lt; dec_count &lt;&lt; endl; system(&quot;color 06&quot;); cout &lt;&lt; &quot; Hexadecimal value =====&gt; &quot;; system(&quot;color&quot;); for (v = 1; v &lt;= hex_val.length(); v++)//printing backwards { cout &lt;&lt; hex_val[hex_val.length() - v]; } cout &lt;&lt; endl;//blank line }//bit void hex()//hexadecimal input { int k, o;//loop counter long long decimalvalue = 0;//total decimal value long long totaldec = 0;//decimal value string total_bin = &quot;&quot;;//all binary values in one string system(&quot;color 09&quot;); cout &lt;&lt; &quot; Enter the total number of digits: &quot;; system(&quot;color&quot;); cin &gt;&gt; num_limit;//user input cin.ignore(1000, '\n'); integer_only();//checking for illegal input cout &lt;&lt; endl;//blank line o = num_limit;//assigning loop counter its value for (k = 1; k &lt;= num_limit; k++) { system(&quot;color 09&quot;); cout &lt;&lt; &quot; Enter num #&quot; &lt;&lt; k &lt;&lt; &quot;: &quot;; system(&quot;color&quot;); user_inp = toupper(_getwche());//user input cout &lt;&lt; endl;//blank line hex_input_validator();//validating illegal input if (userinput) { hex_int_assign();//assigning a integer value hex_binary_assign();//assiging a binary value } else { while (!userinput) { system(&quot;color 04&quot;); cout &lt;&lt; &quot; Invalid input...try again: &quot;; system(&quot;color&quot;); user_inp = toupper(_getwche());//user input cout &lt;&lt; endl;//blank line hex_int_assign();//assigning ineger value hex_binary_assign();//assiging a binary value hex_input_validator();//validating illegal input } } total_bin += bitassign; totaldec = hexint * pow(16, (o - 1));//o-1 for answer in reverse order decimalvalue += totaldec; o--; } system(&quot;cls&quot;);//clearing screen load();//calling loading effect cout &lt;&lt; endl;//blank line system(&quot;color 06&quot;); cout &lt;&lt; &quot; Decimal value ======&gt; &quot;; system(&quot;color&quot;); cout &lt;&lt; decimalvalue &lt;&lt; endl; system(&quot;color 06&quot;); cout &lt;&lt; &quot; Binary value =======&gt; &quot;; system(&quot;color&quot;); cout &lt;&lt; total_bin; cout &lt;&lt; endl;//blank line }//hex void dec()//decimal input { long long bit_quotient;//binary quotient long long bit_remainder;//binary remainder long long bit_decimal;//identier to be used with binary calculation with the value of user input int f, q;//loop counter long long hex_quotient;//hexadecimal quotient long long hex_decimal;//identifier to be used with hex calculation with the value of user input string total_hex_string;//all hex string values in one string string bit_string;//assigning binary remainder, binary values string total_bit_string;//all binary values in one string bool hex = true;//validator for hex calculation bool bit = true;//validator for binary calculation system(&quot;color 09&quot;); cout &lt;&lt; &quot; Enter number: &quot;; system(&quot;color&quot;); cin &gt;&gt; num_limit;//user input cin.ignore(1000, '\n'); integer_only();//checking for illegal input bit_decimal = num_limit; hex_decimal = num_limit; while (bit) { bit_quotient = bit_decimal / 2; bit_remainder = bit_decimal % 2; bit_decimal = bit_quotient; switch (bit_remainder) { case 0:bit_string = &quot;0&quot;; break; case 1:bit_string = &quot;1&quot;; break; } total_bit_string += bit_string; if (bit_quotient == 0) { bit = false; } } while (hex) { hex_quotient = hex_decimal / 16; hex_remainder = hex_decimal % 16; hex_decimal = hex_quotient; hexassign();//assigning a hex value total_hex_string += hex_assign; if (hex_quotient == 0) { hex = false; } } system(&quot;cls&quot;);//clearing screen load();//calling loading effect cout &lt;&lt; endl;//blank line system(&quot;color 06&quot;); cout &lt;&lt; &quot; Binary value ===========&gt; &quot;; system(&quot;color&quot;); for (f = 1; f &lt;= total_bit_string.length(); f++)//printing in backwards order { cout &lt;&lt; total_bit_string[total_bit_string.length() - f]; } cout &lt;&lt; endl;//blank line system(&quot;color 06&quot;); cout &lt;&lt; &quot; Hexadecimal value ======&gt; &quot;; system(&quot;color&quot;); for (q = 1; q &lt;= total_hex_string.length(); q++)//printing in backwards order { cout &lt;&lt; total_hex_string[total_hex_string.length() - q]; } cout &lt;&lt; endl;//blank line }//dec int main() { char user_choice;//identifier for user choice char run_choice;//identifier for run choice bool run = true;//validator for running the program while (run)//will run as long as &lt;run&gt; is true { cout &lt;&lt; endl;//blank line system(&quot;color 09&quot;); cout &lt;&lt; &quot; Do you want to input (B)inary, (H)exadecimal, or (D)ecimal value? &quot;; system(&quot;color&quot;); user_choice = toupper(_getwche());//user input cout &lt;&lt; endl;//blank line cout &lt;&lt; endl;//blank line while (user_choice != 'B' &amp;&amp; user_choice != 'H' &amp;&amp; user_choice != 'D')//checking illegal emtry { system(&quot;color 04&quot;); cout &lt;&lt; &quot; Wrong input...enter again: &quot;; system(&quot;color&quot;); user_choice = toupper(_getwche());//user input cout &lt;&lt; endl;//blank line } system(&quot;cls&quot;); cout &lt;&lt; endl;//blank line if (user_choice == 'B') { bit(); }//if user chose binary else if (user_choice == 'H') { hex(); }//if user chose hexadecimal else if (user_choice == 'D') { dec(); }//if user chose decimal cout &lt;&lt; endl;//blank line system(&quot;pause&quot;); system(&quot;cls&quot;);//clearing screen cout &lt;&lt; endl;//blank line system(&quot;color 09&quot;); cout &lt;&lt; &quot; Do you want to calculate any more numbers?(Y/N): &quot;; run_choice = toupper(_getwche());//user input cout &lt;&lt; endl;//blank line cout &lt;&lt; endl;//blank line while (run_choice != 'Y' &amp;&amp; run_choice != 'N') { system(&quot;color 04&quot;); cout &lt;&lt; &quot; Wrong input...enter again: &quot;; run_choice = toupper(_getwche());//user input cout &lt;&lt; endl;//blank line } if (run_choice == 'Y') { run = true; system(&quot;cls&quot;); } else if (run_choice == 'N') { run = false; } } system(&quot;color 07&quot;);//colour reset system(&quot;cls&quot;);//clearing screen return 0; }//end </code></pre>
[]
[ { "body": "<p><strong>using namespace std;</strong>:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>This is a bad habit to get into. With larger projects it can cause name collisions. It's better to type <code>std::whatever</code> where necessary.</p>\n<hr />\n<p><strong>declaring variables</strong>:</p>\n<pre><code>long long num_limit; //user input for decimal\nlong long hex_remainder; //hexadecimal remainder\nlong long hexint = 0; //integer value for user input\nchar user_inp; //identifier for user input\nbool userinput = true; //validator for illegal input\nstring hex_assign; //assiging hex remainder string value\nstring bitassign = &quot;&quot;; //identifier assigning binary values to hex\n</code></pre>\n<p>Try to avoid global variables. These should all be local variables, function arguments or return values.</p>\n<p>We should:</p>\n<ul>\n<li>Declare variables as close to the point of use as possible (minimize their scope). Declaring local variables at the start of functions is an outdated and undesirable habit.</li>\n<li>Initialize variables directly to useful values, not placeholders.</li>\n<li>Avoid reusing variables (unless a variable requires a hefty resource allocation).</li>\n</ul>\n<p>Another example:</p>\n<pre><code>void load() //loading effect\n{\n int g, c; //loop counter\n cout &lt;&lt; &quot; &quot;;\n system(&quot;color 07&quot;);\n for (g = 1; g &lt;= 80; g++)\n {\n for (c = 1; c &lt;= 2850000; c++)\n</code></pre>\n<p><code>g</code> and <code>c</code> are not needed outside the loop, and should be declared in the loop statements:</p>\n<pre><code>for (int g = 1; g &lt;= 80; ++g)\n ...\n</code></pre>\n<p>And again:</p>\n<pre><code>int main()\n{\n char user_choice; //identifier for user choice\n char run_choice; //identifier for run choice\n bool run = true; //validator for running the program\n while (run) //will run as long as &lt;run&gt; is true\n</code></pre>\n<p><code>run</code> is ok here. The other two variables are not in the right place (they aren't used outside the loop, and aren't initialized to useful values).</p>\n<p>As a beginner, things you've just learned about may seem comment worthy. However, it's best to ask yourself if the comment actually adds something to the reader's understanding. In this case, they are just restating the code, and could be omitted.</p>\n<hr />\n<p><strong>put repetitive code in a separate function</strong>:</p>\n<pre><code> cout &lt;&lt; endl; //blank line\n system(&quot;color 09&quot;);\n cout &lt;&lt; &quot; Do you want to input (B)inary, (H)exadecimal, or (D)ecimal value? &quot;;\n system(&quot;color&quot;);\n char user_choice = toupper(_getwche()); //user input\n cout &lt;&lt; endl; //blank line\n cout &lt;&lt; endl; //blank line\n while (user_choice != 'B' &amp;&amp; user_choice != 'H' &amp;&amp; user_choice != 'D') //checking illegal emtry\n {\n system(&quot;color 04&quot;);\n cout &lt;&lt; &quot; Wrong input...enter again: &quot;;\n system(&quot;color&quot;);\n user_choice = toupper(_getwche()); //user input\n cout &lt;&lt; endl; //blank line\n }\n system(&quot;cls&quot;);\n cout &lt;&lt; endl; //blank line\n if (user_choice == 'B')\n {\n bit();\n } //if user chose binary\n else if (user_choice == 'H')\n {\n hex();\n } //if user chose hexadecimal\n else if (user_choice == 'D')\n {\n dec();\n } //if user chose decimal\n cout &lt;&lt; endl; //blank line\n system(&quot;pause&quot;);\n system(&quot;cls&quot;); //clearing screen\n cout &lt;&lt; endl; //blank line\n system(&quot;color 09&quot;);\n cout &lt;&lt; &quot; Do you want to calculate any more numbers?(Y/N): &quot;;\n char run_choice = toupper(_getwche()); //user input\n cout &lt;&lt; endl; //blank line\n cout &lt;&lt; endl; //blank line\n while (run_choice != 'Y' &amp;&amp; run_choice != 'N')\n {\n system(&quot;color 04&quot;);\n cout &lt;&lt; &quot; Wrong input...enter again: &quot;;\n run_choice = toupper(_getwche()); //user input\n cout &lt;&lt; endl; //blank line\n }\n if (run_choice == 'Y')\n {\n run = true;\n system(&quot;cls&quot;);\n }\n else if (run_choice == 'N')\n {\n run = false;\n }\n</code></pre>\n<p>A little more vertical spacing would make this more readable.</p>\n<p>Note the duplication of code when fetching user input. We could abstract that code into a function so that our <code>main</code> becomes more readable, e.g.:</p>\n<pre><code> char user_choice = get_char_from_user(&quot; Do you want to input (B)inary, (H)exadecimal, or (D)ecimal value? &quot;, { 'B', 'H', 'D' });\n\n system(&quot;cls&quot;);\n cout &lt;&lt; endl;\n\n if (user_choice == 'B')\n {\n bit();\n }\n else if (user_choice == 'H')\n {\n hex();\n }\n else if (user_choice == 'D')\n {\n dec();\n }\n\n cout &lt;&lt; endl;\n system(&quot;pause&quot;);\n system(&quot;cls&quot;);\n\n char run_choice = get_char_from_user(&quot; Do you want to calculate any more numbers?(Y/N): &quot;, { 'Y', 'N' });\n\n if (run_choice == 'Y')\n {\n run = true;\n system(&quot;cls&quot;);\n }\n else if (run_choice == 'N')\n {\n run = false;\n }\n</code></pre>\n<p><code>get_char_from_user()</code> might look something like:</p>\n<pre><code>bool vector_contains(std::vector&lt;char&gt; vec, char item)\n{\n for (auto c : vec)\n if (c == item)\n return true;\n \n return false;\n}\n\nchar get_char_from_user(std::string prompt, std::vector&lt;char&gt; valid_choices)\n{\n cout &lt;&lt; endl;\n system(&quot;color 09&quot;);\n cout &lt;&lt; prompt;\n\n while (true)\n {\n system(&quot;color&quot;);\n char user_choice = toupper(_getwche());\n cout &lt;&lt; endl;\n\n if (vector_contains(valid_choices, user_choice))\n return user_choice;\n\n system(&quot;color 04&quot;);\n cout &lt;&lt; &quot; Wrong input...enter again: &quot;;\n }\n}\n</code></pre>\n<hr />\n<p><strong>bit()</strong>:</p>\n<pre><code>char user_input = 'x'; //user input (1/0)\nint num; //identifier assigned integer value for user input\nint i, v, y; //loop counter\nlong long total_dec; //decimal value\nlong long dec_count = 0; //total decimal value\nlong long quotient = 0; //quotient for bimary\nlong long decimal; //identifier to be used to find decimal value\nstring hex_val = &quot;&quot;; //total hex value in one string\nbool hex = true; //validator for hex calculation\n</code></pre>\n<p>Note the advice about variable declaration above.</p>\n<pre><code>system(&quot;color 09&quot;);\ncout &lt;&lt; &quot; Enter the total number of digits: &quot;;\nsystem(&quot;color&quot;);\ncin &gt;&gt; num_limit; //user input\ncin.ignore(1000, '\\n');\n\ninteger_only(); //checking for illegal input\ncout &lt;&lt; endl; //blank line\n</code></pre>\n<p>We should avoid using the global variable <code>num_limit</code>. Again, we move this code into a separate function so that we only have to do:</p>\n<pre><code>int y = get_integer_from_user(&quot; Enter the total number of digits: &quot;)\n</code></pre>\n<p>Removing global variables (using function arguments and return values) and moving the input / printing code into separate functions we would get something a lot more readable:</p>\n<pre><code>void bit() //binary input\n{\n int y = get_integer_from_user(&quot; Enter the total number of digits: &quot;);\n\n long long dec_count = 0;\n for (int i = 0; i &lt; num_limit; i++)\n {\n int num = get_binary_digit_from_user(&quot; Num #&quot; + std::to_string(i + 1) + &quot;: &quot;);\n\n long long total_dec = num * pow(2, (y - 1)); //y-1 so that calculation is in reverse order\n dec_count += total_dec;\n y--;\n }\n\n string hex_val;\n long long decimal = dec_count;\n\n while (decimal)\n {\n long long quotient = decimal / 16;\n long long hex_remainder = decimal % 16;\n hex_val += hexassign(hex_remainder);\n \n decimal = quotient;\n }\n\n print_dec_result(dec_count);\n print_hex_result(hex_val);\n}\n</code></pre>\n<p>(Note: not compiled / tested).</p>\n<p>We should generally ensure that functions have only a single responsibility, so this could be split up further:</p>\n<pre><code>void bit() // binary input\n{\n std::string bin = get_binary_string_from_user(); // (read whole string before converting to decimal)\n long long dec = binary_string_to_decimal(binary);\n std::string hex = decimal_to_hex_string(decimal);\n\n print_decimal(dec);\n print_hex_string(hex);\n}\n</code></pre>\n<p>The <code>hex()</code> and <code>dec()</code> functions have similar issues, so I won't look at them specifically.</p>\n<hr />\n<p><strong><code>hexassign()</code> and switch statements</strong>:</p>\n<p>As mentioned, <code>hexassign</code> and the other similar functions should use function arguments (parameters) and return values, not global variables.</p>\n<p>The switch statements are also not ideal. We have lots of other choices here, e.g.:</p>\n<ul>\n<li><p>Look up tables - finding an index or element in a <code>std::vector</code> or <code>std::map</code> is quite simple.</p>\n</li>\n<li><p><code>std::printf(&quot;%x&quot;, ...)</code> or the modern equivalent <code>stringstream &lt;&lt; std::hex &lt;&lt; ...</code> for printing to a hex string.</p>\n</li>\n<li><p>We could also use manual character ranges (if we're careful) to do conversions: <code>return c &lt; 10 ? '0' + c : 'A' + (c - 10);</code>.</p>\n</li>\n</ul>\n<p>I'd suggest experimenting with a few different ways to see what's shortest, easiest and safest. It's worth thinking about what happens (and what we want to happen) when we pass invalid inputs into each function. <code>assert(condition)</code> or <code>if (!condition) throw std::runtime_error();</code> might be useful...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-25T11:50:19.540", "Id": "533910", "Score": "1", "body": "While `'A' + (c - 10)` does achieve the desired results in the common character codings, C++ doesn't guarantee that the letters are consecutive. A lookup such as `\"0123456789ABCDEF\"[c]` is portable, even for pedants." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T11:41:52.557", "Id": "256371", "ParentId": "256253", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T09:44:50.803", "Id": "256253", "Score": "1", "Tags": [ "c++", "beginner", "converting" ], "Title": "Binary-Decimal-Hexadecimal converter" }
256253
<p>This is a program which you can get the next &quot;different&quot;, i.e. elements in <code>A[]</code> can be identical, permutation at each call. I've written a C++ program for the same purpose in 2018, but I found it unreadable, <code>readability = NULL</code>, so here is a new one.</p> <p>Any critical comment and answer will be welcomed :)</p> <p><strong>next_different_permutation.c</strong>:</p> <pre><code>#include &lt;stdbool.h&gt; void pswap(int *l, int *r) { int temp = *l; *l = *r; *r = temp; } void reverse(int A[], int l, int r) { int size = (r-l+1); for (int i = 0; i &lt; size/2; ++i) pswap(&amp;A[l+i], &amp;A[r-i]); } bool next_different_permutation(int A[], int l, int r) { if (r-l+1 &lt;= 1) return false; // return false when [l,r] is(or back to) an increasing interval. int j = -1; // j will point to the highest peak of the interval [i,r]. for (struct{int i, j;} // this for will find the first increasing [i,j] from r to l. z = {r-1, r}; z.j != l; --z.i, j=--z.j) if (A[z.i] &lt; A[z.j]) { // find the maximal decreasing interval [j,r]. int k = r; // after swap (i, k), interval [j,r] remains decreasing. while (!(A[z.i] &lt; A[k])) // find the first A[k] where A[k] &gt; A[z.i]. --k; pswap(&amp;A[z.i], &amp;A[k]); reverse(A, z.j, r); return true; // when success we go, the z.i, z.j will be initialized in next call. } reverse(A, j, r); // Recover the A[l]&gt;=A[l+1]&gt;=...&gt;=A[r]-array back to the increasing order. return false; } </code></pre> <p><strong>Usage</strong>:</p> <pre><code>#define ARRAY_SIZE 3 int A[ARRAY_SIZE] void next_different_permutation_test_distinct() { for (int i = 0; i &lt; ARRAY_SIZE; ++i) A[i] = i+1; do { print_array(A, ARRAY_SIZE, PRINT_WIDTH); } while (next_different_permutation(A, 0, ARRAY_SIZE-1)); // the order will back to A[l]&lt;A[l+1]&lt;...&lt;A[r] } void next_different_permutation_test_some_identical() { for (int i = 0; i &lt; ARRAY_SIZE; ++i) A[i] = rand()%RAND_MOD; do { print_array(A, ARRAY_SIZE, PRINT_WIDTH); } while (next_different_permutation(A, 0, ARRAY_SIZE-1)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T11:45:17.307", "Id": "505952", "Score": "0", "body": "Is the behaviour intended to be the same as C++ `std::next_permutation()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T12:10:25.333", "Id": "505954", "Score": "0", "body": "@TobySpeight: No, but the only difference is `std` used `[l ,size)` but I personally prefer `[l, r]` when the range size will not vary. Good question btw, this is important to me also :)" } ]
[ { "body": "<ul>\n<li><p><code>size</code> and <code>i</code> in <code>reverse</code> look superficial. Consider</p>\n<pre><code>void reverse(int A[], int l, int r) {\n while (l &lt; r) {\n pswap(&amp;A[l++], &amp;A[r--]);\n }\n}\n</code></pre>\n</li>\n<li><p>The outer loop looks very strange. Its body is executed exactly once, when the longest decreasing interval is detected. Consider lifting the body out of the loop.</p>\n<p>As a side point, I don't see the point of <code>struct {int i; int j}</code>. It is initialized to <code>{r-1, r}</code>, and at each iteration both members are decremented. <code>z.i</code> is always equal to <code>z.j - 1</code>. Keeping just one <code>int</code> is enough. Consider</p>\n<pre><code> int j = r; // j will point to the highest peak of the interval [i,r].\n // this loop will find the first increasing [i,j] from r to l.\n while (j &gt; l) {\n if (A[j-1] &lt; A[j]) {\n break;\n }\n --j;\n }\n\n if (j &gt; l) {\n int k = r;\n // find the first A[k] where A[k] &gt; A[j-1].\n while (!(A[j-1] &lt; A[k])) {\n --k;\n }\n pswap(&amp;A[j-1], &amp;A[k]);\n reverse(A, j, r);\n return true;\n }\n\n reverse(A, j, r);\n return false;\n</code></pre>\n<p>It already looks cleaner, but let's get going. An obvious next step is to get rid of the duplicate calls to <code>reverse</code>:</p>\n<pre><code> if (j &gt; l) {\n ....\n pswap(....);\n }\n reverse (A, j, r);\n return j &gt; l;\n</code></pre>\n</li>\n<li><p>No naked loops please. If you felt compelled to put comments like</p>\n<pre><code> // find the maximal decreasing interval [j,r]\n // find the first A[k] where A[k] &gt; A[z.i].\n</code></pre>\n<p>you admit that you failed to express the intentions in the code. Consider refactoring these loops into functions. Consider</p>\n<pre><code> int j = find_decreasing_interval(A, l, r);\n if (l &lt; j) {\n int k = lower_bound(A, j, r, A[j-1]);\n pswap(&amp;A[j-1], &amp;A[k]);\n }\n reverse((A, j, r);\n return j &gt; l;\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T03:30:41.680", "Id": "506012", "Score": "0", "body": "This answer help me a lot!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T01:37:58.207", "Id": "256320", "ParentId": "256255", "Score": "2" } }, { "body": "<p><code>pswap()</code> and <code>reverse()</code> aren't part of the public interface, so ought to be declared with static linkage.</p>\n<p>If we passed pairs of pointers, rather than indices, we wouldn't need to also pass the start of array. Even with indices, we don't need to pass <code>l</code> - we can supply the subarray beginning at <code>l</code>.</p>\n<p>The C++ function <code>std::next_permutation()</code> has a more useful behaviour here:</p>\n<blockquote>\n<pre><code>if (r-l+1 &lt;= 1)\n return false; // return false when [l,r] is(or back to) an increasing interval.\n</code></pre>\n</blockquote>\n<p>As well as returning <code>false</code>, it wraps around to the first permutation again.</p>\n<p>Some of the choices for line-wrapping are questionable. Consider this:</p>\n<blockquote>\n<pre><code>for (struct{int i, j;} // this for will find the first increasing [i,j] from r to l.\n z = {r-1, r}; z.j != l; --z.i, j=--z.j)\n</code></pre>\n</blockquote>\n<p>Breaking the line (with an intruding comment!) between the type of <code>z</code> and <code>z</code> itself makes that much harder to read, compared with putting the newlines after each <code>;</code>:</p>\n<pre><code>// find the first increasing [i,j] from r to l.\nfor (struct{int i, j;} z = {r-1, r};\n z.j != l;\n --z.i, j=--z.j)\n</code></pre>\n<p>That said, I'd avoid declaring a new type within the <code>for</code> construct, and simply use something more like</p>\n<pre><code>for (int i = r-1, j = r; j != l; --i, --j)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T17:53:54.580", "Id": "506075", "Score": "0", "body": "By `if (r-l+1 <= 1) return false;` I meant if the array is `[1]` its next permutation is trivially wrapped back to `[1]` without doing anything. You could run the test and print out the `A[]` after the while loop, it actually does the same as `std::next_permutation`. (If anything is wrong in this comment pls let me know!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T17:57:23.523", "Id": "506076", "Score": "0", "body": "As for the `struct{...}` in for loop, that's indeed a bad idea..., I read a post mentioned it and thought it was good :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T20:30:39.207", "Id": "506085", "Score": "0", "body": "Ah, I see it's the other `return false` that's the wrapping behaviour. My mistake!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T08:36:32.717", "Id": "256329", "ParentId": "256255", "Score": "1" } } ]
{ "AcceptedAnswerId": "256320", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T10:28:13.747", "Id": "256255", "Score": "0", "Tags": [ "algorithm", "c", "programming-challenge", "combinatorics" ], "Title": "Next different permutation in C" }
256255
<p>I would like to use <code>Julia</code> to compute the hamming distance on a very large dataset. I need to get back a distance matrix between rows in order to run further analysis on this matrix.</p> <p>For my purposes, it is useful that the data are stored in a DataFrame type.</p> <pre><code>using DataFrames </code></pre> <p>The data looks something like this</p> <pre><code>a = [1 0 1 0 ; 1 1 1 1; 0 0 0 0; 0 0 0 0 ; 0 0 0 1] df = convert(DataFrame, a); nrows = size(df, 1) ncols = size(df, 2) </code></pre> <p>I made a function in <code>Julia</code></p> <pre><code>function hamjulia(df) nrows = size(df, 1) ncols = size(df, 2) m, n = nrows, nrows A = fill(0, (m, n)) for i in 1:nrows for k in 1:nrows v = 0 for j in 1:ncols if df[i,j] != df[k,j] v += 1 end end A[i,k] = v end end return A end p = hamjulia(df) p </code></pre> <p>My issue is that this code is super slow compared to some R packages. For instance, when I compared this function to the <code>rdist</code> package, <code>rdist(df, metric = 'hamming')</code>, <code>R</code> is faster.</p> <p>How could I make this code really efficient? Especially that I would need to run it on a very large dataframe.</p> <p>Thanks.</p>
[]
[ { "body": "<p>As a cheap first try I suggest <a href=\"https://github.com/JuliaStats/Distances.jl\" rel=\"nofollow noreferrer\"><code>Distances.jl</code></a> with (I think)</p>\n<pre><code>pairwise(Hamming(), df, dims=1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T17:55:41.847", "Id": "256308", "ParentId": "256257", "Score": "3" } }, { "body": "<p>I have three areas of suggestions below. Here's a modified version of your code that implements these suggestions:</p>\n<pre><code># For memory safety, restrict type to Matrix due to the use of @inbounds below.\nfunction ham(df::Matrix)\n nrows, ncols = size(df)\n A = fill(0, ncols, ncols)\n for j in 1:ncols, i in j+1:ncols\n v = 0\n for k in 1:nrows\n v += @inbounds (df[k, i] != df[k, j])\n end\n A[i, j] = A[j, i] = v\n end\n return A\nend\n\nham(df::DataFrame) = ham(convert(Matrix, df))\n</code></pre>\n<hr />\n<p><strong>1. Write code for column-major arrays.</strong></p>\n<p>Julia is <a href=\"https://en.wikipedia.org/wiki/Row-_and_column-major_order\" rel=\"nofollow noreferrer\">column-major</a> (and packages like DataFrames.jl conform with this by storing data in columns), so when performance is important, you should iterate through the rows of a column. For example, when iterating through an array <code>A[x, y, z]</code>, the leftmost index <code>x</code> should be changing the most rapidly. Looking at the innermost loop in your code,</p>\n<pre><code>for j in 1:ncols\n if df[i,j] != df[k,j]\n v += 1\n end\nend\n</code></pre>\n<p>notice that it is iterating through the columns of a row instead (i.e., <code>j</code> is changing most rapidly in <code>df[i,j]</code>). To get a free performance boost, rewrite the code to exchange the roles of columns and rows. The data will also need to be transposed. (Note that R is also column-major.)</p>\n<p>Julia documentation: <a href=\"https://docs.julialang.org/en/v1/manual/performance-tips/#man-performance-column-major\" rel=\"nofollow noreferrer\">memory order</a>.</p>\n<hr />\n<p><strong>2. In performance-critical loops, annotate <code>@inbounds</code> where possible.</strong></p>\n<p>In the modified code I gave, the array access in the innermost loop is annotated with <a href=\"https://docs.julialang.org/en/v1/base/base/#Base.@inbounds\" rel=\"nofollow noreferrer\"><code>@inbounds</code></a> to disable bounds checking. This gives a speedup in large part because it allows compiler to <a href=\"https://docs.julialang.org/en/v1/base/base/#Base.SimdLoop.@simd\" rel=\"nofollow noreferrer\">automatically vectorize</a> the loop.</p>\n<p>Only use <code>@inbounds</code> if you are certain that out-of-bounds access is impossible; in our case, we cannot guarantee this for custom types, so we restrict the input type to a <code>Matrix</code> (an alias for <code>Array{T,2} where T</code>) to ensure that <code>df[k, i]</code> and <code>df[k, j]</code> are always in bounds. Like so:</p>\n<pre><code>function ham(df::Matrix)\n [...]\n for k in 1:nrows\n v += @inbounds (df[k, i] != df[k, j])\n end\n [...]\nend\n</code></pre>\n<p>If <code>@inbounds</code> is not used, I would not restrict the input type and would instead leave it generic.</p>\n<p>Julia documentation: <a href=\"https://docs.julialang.org/en/v1/manual/performance-tips/#man-performance-annotations\" rel=\"nofollow noreferrer\">performance annotations</a>.</p>\n<hr />\n<p><strong>3. Beware of type instability.</strong></p>\n<p>For performant code, functions should be type stable, meaning that given an input type, the output type can be inferred during compilation. Similarly, variables used within a function should be type stable.</p>\n<p>As noted in its documentation, <a href=\"https://dataframes.juliadata.org/stable/lib/types/#DataFrames.DataFrame\" rel=\"nofollow noreferrer\"><code>DataFrame</code></a> columns are not type stable! That is, the type of a <code>DataFrame</code> does not contain information about the types of its columns; in fact, the <code>DataFrame</code> type is not parametric, so the type contains <em>no</em> information other than that it is a <code>DataFrame</code>. This can drastically degrade performance.</p>\n<p>The <a href=\"https://docs.julialang.org/en/v1/manual/performance-tips/#man-code-warntype\" rel=\"nofollow noreferrer\"><code>@code_warntype</code></a> macro is very helpful for diagnosing this.</p>\n<p>In our case, assuming that all columns are of the same type, a simple workaround is to copy the columns into a <code>Matrix</code> before calling the function. (The time this takes is negligible compared to the rest of the function.) To do so, we can specialize <code>ham</code> for the <code>DataFrame</code> type:</p>\n<pre><code>ham(df::DataFrame) = ham(convert(Matrix, df))\n</code></pre>\n<p>Note that the compiler specializes code for types at function boundaries, so it is important that this conversion takes place outside the original <code>ham</code> function. In particular, don't put the conversion into the original function like so:</p>\n<pre><code># Don't do this!\nfunction ham(x)\n df = convert(Matrix, x)\n [rest of ham...]\nend\n</code></pre>\n<p>because the type of <code>x</code> here might not contain sufficient information to infer the type of <code>df</code>. Such is the case for <code>DataFrames</code>.</p>\n<p>Julia documentation: <a href=\"https://docs.julialang.org/en/v1/manual/performance-tips/#kernel-functions\" rel=\"nofollow noreferrer\">function barriers</a>.</p>\n<hr />\n<p><strong>Simple benchmark</strong></p>\n<p>After implementing these suggestions, the speedup on calculating the distance matrix for 128 vectors of 256 integers each is by about 1000x: (note that the times are in microseconds vs milliseconds)</p>\n<pre><code>using BenchmarkTools\nusing DataFrames\nM = rand(0:1, 256, 128);\ndf = DataFrame(M);\ntdf = DataFrame(permutedims(M)); # transpose rows and columns\n</code></pre>\n<pre><code>julia&gt; @benchmark ham($df)\nBenchmarkTools.Trial: \n memory estimate: 387.33 KiB\n allocs estimate: 133\n --------------\n minimum time: 493.841 μs (0.00% GC)\n median time: 537.689 μs (0.00% GC)\n mean time: 610.732 μs (2.74% GC)\n maximum time: 6.215 ms (81.69% GC)\n --------------\n samples: 8176\n evals/sample: 1\n</code></pre>\n<pre><code>julia&gt; @benchmark hamjulia($tdf)\nBenchmarkTools.Trial: \n memory estimate: 128.08 KiB\n allocs estimate: 2\n --------------\n minimum time: 538.585 ms (0.00% GC)\n median time: 546.390 ms (0.00% GC)\n mean time: 551.220 ms (0.00% GC)\n maximum time: 567.238 ms (0.00% GC)\n --------------\n samples: 10\n evals/sample: 1\n</code></pre>\n<p>The additional memory allocations in <code>ham</code> are due to the conversion of the <code>DataFrame</code> to a <code>Matrix</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T09:48:22.387", "Id": "508181", "Score": "0", "body": "Thanks a lot for this! I will run some tests with it. I noticed that I don't need the `DataFrame` so much. What about only filling half of the distance matrix? Do you know how stop when we reached the diagonal? (the distance matrix is filled twice here)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T10:04:39.747", "Id": "508183", "Score": "1", "body": "No problem! The sample code already stops at the diagonal: notice that the outer loop goes `for j in 1:ncols, i in j+1:ncols`, where `i` depends on `j` and so excludes the diagonal and one half of the matrix. Hence the `A[i, j] = A[j, i] = v` sets each non-diagonal element exactly once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T10:33:00.990", "Id": "508187", "Score": "0", "body": "Oh sorry I missed that. But your function still returns a full matrix right? Wouldn't save memory to only return the half matrix?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T10:34:55.023", "Id": "508188", "Score": "0", "body": "Yes, it returns a full matrix." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T10:37:05.473", "Id": "508189", "Score": "0", "body": "Sorry to bother you with this, but it return the full matrix but only compute the half matrix. Is that correct? Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T10:46:19.480", "Id": "508193", "Score": "0", "body": "Yes. Only half the matrix is calculated but the entire matrix is filled because of the symmetric assignment `A[i, j] = A[j, i] = v`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T12:33:43.807", "Id": "508201", "Score": "0", "body": "simply beautiful ....." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-17T06:28:26.797", "Id": "257285", "ParentId": "256257", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T13:05:54.060", "Id": "256257", "Score": "5", "Tags": [ "performance", "julia" ], "Title": "Fast hamming distance function in Julia that returns a distance matrix" }
256257
<p>I was trying to code the phone keypad characters with its numbers. The first idea which came to my mind is using a <code>HashMap</code>. After trying various options I came up with the below Code. I <strong>want to know if the data structure and methodology which I implemented is good or does it need some more improvements.</strong></p> <p><strong>Things which I know and don't want to implement:</strong></p> <ol> <li>I do not want to hardcode the keypad. The reason for this is that since it was asked in timed-coding test so I don't want to write it again and again. I know that there are various ways of implementing a hardcoded keypad. I visited <a href="https://codereview.stackexchange.com/questions/104879/creating-a-numeric-phone-keypad"><strong>this</strong></a> and <a href="https://codereview.stackexchange.com/questions/90079/phone-keypad-implementation"><strong>this</strong></a> link to learn about other ways.</li> <li>I would really be thankful if the solution is given in java 7 syntax. I don't have much idea about java 8 syntax, but it'll be helpful to know the solution in that too, if possible.</li> </ol> <p><strong>Keypad feature according to my problem statement:</strong></p> <ol> <li><strong>0 and 1</strong> buttons are not functional.</li> <li><strong>7 and 9</strong> buttons contain 4 letters each and <strong>others</strong> contain 3 letters each.</li> </ol> <pre class="lang-java prettyprint-override"><code>public static void keypadDemo(){ int ax = 97; // I need to store lower-case letters so took this Map&lt;Integer, ArrayList&lt;Character&gt;&gt; hm = new HashMap&lt;&gt;(); // This is my data-structure for(int i = 0; i &lt; 10; i++){ if(i == 0 || i == 1){ hm.put(i, null); // 0 and 1 keys are not functional as per my problem statement. }else if(i == 7 || i == 9){ hm.put(i, new ArrayList&lt;&gt;(Arrays.asList((char) ax, (char) ++ax, (char) ++ax, (char) ++ax))); ax++; }else{ hm.put(i, new ArrayList&lt;&gt;(Arrays.asList((char) ax, (char) ++ax, (char) ++ax))); ax++; } } System.out.println(hm); } </code></pre> <p>Any help will be welcomed. Thanks</p> <p><strong>EDIT:</strong></p> <p><strong>Keypad format:</strong></p> <p><a href="https://i.stack.imgur.com/JysqQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JysqQ.png" alt="keypad format" /></a></p> <p><strong>The problem statement:</strong></p> <ol> <li><p>We are given two inputs:</p> <ul> <li>A phone number in string format.</li> <li>A list of strings.</li> </ul> </li> <li><p>The output is the list containing only those strings which correspond to any substring of the given phone number when converted to the corresponding letters on the phone keypad.</p> </li> <li><p><strong>Example test case:</strong></p> </li> </ol> <pre><code>Input: 3662277 words = [&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;, &quot;emo&quot;, &quot;foobar&quot;, &quot;cap&quot;, &quot;car&quot;, &quot;cat&quot;] Output: outputList = [&quot;foo&quot;, &quot;bar&quot;, &quot;foobar&quot;, &quot;emo&quot;, &quot;cap&quot;, &quot;car&quot;] </code></pre> <ol start="4"> <li>I coded the solution and it got accepted too by online judge. But since, I'm learning about <code>Collections</code> in java so wanted to know whether my choice of the data structure is up to the mark or not.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T14:38:38.533", "Id": "505965", "Score": "1", "body": "Wow, __great context-update__ to the question. Also your _contextual_ comment \"time coding test\" adds valuable rationale for the _design-decision_ to dynamically built the map in a loop." } ]
[ { "body": "<p>Welcome, there are many ways to archive your purpose, your idea of using a Hash structure is really nice, also selecting <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html\" rel=\"nofollow noreferrer\"><code>HashMap</code> over <code>Hashtable</code></a> is a good thing in java</p>\n<blockquote>\n<p>As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use <strong>HashMap</strong> in place of <strong>Hashtable</strong>. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use <strong>ConcurrentHashMap</strong> in place of <strong>Hashtable</strong>.</p>\n</blockquote>\n<p>Also, a hashed structure as we know has <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> average access time.</p>\n<p>Regarding the implementation, it's hard to tell how to improve your actual code. Perhaps the following modification could help:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void keypadDemo() {\n int ax = 97;\n Map&lt;Integer, ArrayList&lt;Character&gt;&gt; hm = new HashMap&lt;&gt;();\n hm.put(0, null);\n hm.put(1, null);\n for(int i = 2; i &lt; 10; i++) {\n if (i == 7 || i == 9)\n hm.put(i, new ArrayList&lt;&gt;(Arrays.asList((char) ax++, (char) ax++, (char) ax++, (char) ax++)));\n else hm.put(i, new ArrayList&lt;&gt;(Arrays.asList((char) ax++, (char) ax++, (char) ax++)));\n }\n System.out.println(hm);\n}\n</code></pre>\n<p>The difference consists of not checking the statement <code>if (i == 0 || i == 1)</code> all the times the loop does an iteration, offcourse it's nearly no improvement but there's no much to do.</p>\n<p>Another option (though ugly) is to insert each <code>key, value</code> pair into the Map, it implies to not create the for loop, the iteration variable <code>i</code> and to avoid comparisons <code>i &lt; 10</code> and <code>(i == 7 || i == 9)</code> in the loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T13:36:12.827", "Id": "505955", "Score": "0", "body": "Strongly discourage to engage performance-considerations as long as not an issue! Primary goal of each software/code should be (a) functionality & (b) usability/readability.\nBTW: optimize performance by either implementing the mapping as (switch-based) key-listener as [suggested by M.Blumel](https://codereview.stackexchange.com/a/256290/127399). This is common UI-best-practice. Alternatively declare the mapping as `static` constant." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T14:32:40.123", "Id": "256260", "ParentId": "256258", "Score": "0" } }, { "body": "<p>It's not possible to say if this method is a good or useful abstraction without context which you have not provided. Accordingly, this review is of the method by itself.</p>\n<p>My primary concern with this method is that it is hard to read and understand. Complexity leads to bugs, and should be avoided where possible. This method is doing a simple thing in a complex way. Readers have to worry about a loop and three branches instead of a simple, static mapping.</p>\n<p><code>keypadDemo()</code> should return the Map, not print it. Let the client decide what to do with it.</p>\n<p><code>ax</code> and <code>hm</code> are very poor variable names. Variable names should clearly indicate the value they hold.</p>\n<p>Using an integer to magically act as characters makes the method harder to read.</p>\n<p>Use the most appropriate abstraction. <code>Map&lt;Integer, List&lt;Character&gt;&gt;</code> would be preferable. The type of list is an implementation detail.</p>\n<p>A loop is the wrong structure to build this map. The code is hard to read, which means it's easy to introduce bugs and hard to notice them.</p>\n<p>Short-circuiting the loop might make it easier to read.</p>\n<p>Empty lists would be better than using <code>null</code>. It's easier to write code that correctly handles an empty list than to special-case null checks.</p>\n<p>In idiomatic Java, there is whitespace before a { and after a }. There is whitespace after a <code>for</code>, <code>if</code>, etc.</p>\n<p>If I were to need this method in my own code, it would look like: (untested)</p>\n<pre><code>/**\n * Generates a mapping from digits on a telephone keypad to the letters for \n * digit. The letters are in alphabetical order. Digits with no letters\n * map to an empty list. \n */\npublic static Map&lt;Integer, List&lt;Character&gt;&gt; digitsToCharacters() {\n Map&lt;Integer, List&lt;Character&gt;&gt; digitsToCharacters = new HashMap&lt;&gt;();\n digitsToCharacters.put(0, Arrays.asList());\n digitsToCharacters.put(1, Arrays.asList());\n digitsToCharacters.put(2, Arrays.asList('a', 'b', 'c'));\n digitsToCharacters.put(3, Arrays.asList('d', 'e', 'f'));\n digitsToCharacters.put(4, Arrays.asList('g', 'h', 'i'));\n digitsToCharacters.put(5, Arrays.asList('j', 'k', 'l'));\n digitsToCharacters.put(6, Arrays.asList('m', 'n', 'o'));\n digitsToCharacters.put(7, Arrays.asList('p', 'q', 'r', 's'));\n digitsToCharacters.put(8, Arrays.asList('t', 'u', 'v'));\n digitsToCharacters.put(9, Arrays.asList('w', 'x', 'y', 'z'));\n return Collections.unmodifiableMap(digitsToCharacters);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T13:52:14.723", "Id": "505957", "Score": "0", "body": "My deepest apologies for using the variable names and the method not returning the `Map`. Actually, I know the importance of giving the proper variable names. It improves readability. I only needed assistance about the data-structure which I used, that is the reason I didn't focused on variable names. For **return type of the method also**, I know that I have to return the `Map`. But I was testing the code so kept it a void method and also added the same to this post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T14:03:04.583", "Id": "505960", "Score": "0", "body": "One more doubt I have, please do clarify this also. Can I use this `Map` as a global `final` variable as mentioned in @hc_dev's answer. What performance issue I could face in doing so as compared to defining it inside a method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T11:27:28.310", "Id": "506044", "Score": "1", "body": "Agree with everything. It would be possible use the`Collections.emptyList` method instead of `Arrays.asList()` avoiding the creation of a new instance empty list but with the result of a a less flexible code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T20:44:07.247", "Id": "506241", "Score": "0", "body": "**Empty lists would be better than using null** :: Y'all have no idea how true this is.Empty and non-empty lists ( collections in general actually ) can be handled with the same code.Adding a empty list-of-numbers is zero, the right answer; null means I have to read the %#$# code to find out why down-stream code threw an exception." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T04:26:18.167", "Id": "256284", "ParentId": "256258", "Score": "4" } }, { "body": "<p>Why would anyone use a Map to do a lookup which is keyed on the integers 0-9?</p>\n<p>This is such an obvious use for an array. Untested code below...</p>\n<pre><code>List&lt;Character&gt;[] digitsToCharacters = new List&lt;&gt;[] {\n Arrays.asList(), // 0\n Arrays.asList(), // 1\n Arrays.asList('a', 'b', 'c'), // 2\n Arrays.asList('d', 'e', 'f'), // 3\n Arrays.asList('g', 'h', 'i'), // 4\n Arrays.asList('j', 'k', 'l'), // 5\n Arrays.asList('m', 'n', 'o'), // 6\n Arrays.asList('p', 'q', 'r', 's'), // 7\n Arrays.asList('t', 'u', 'v'), // 8\n Arrays.asList('w', 'x', 'y', 'z') // 9\n };\n</code></pre>\n<p>This should indicate that digitsToCharacters is an array, where each element is a list of characters. digitsToCharacters[2] is the list of characters corresponding to the number 2 on the keypad. This is simple and straightforward, represents the data in a natural way, and avoids the overheads of a Map.</p>\n<p>My experience, over many years writing and maintaining code, is that clear code which represents the intent simply and directly is always preferable to more elaborate models - the idea of iterating from 0 to 9, but then doing different things on different values in the range is harder to read, comprehend and maintain than representing the data explicitly.</p>\n<p>Beyond that, I'd echo other posters' comments about the magic number 97 - if you want to start at 'a' start at 'a' - and the unhelpful short names like 'ax'.</p>\n<p>I don't understand the comment about &quot;I do not want to hardcode the keypad&quot; - this hardcodes a keypad, as all the mappings are explicitly stated in the code.</p>\n<p>Personally if I were implementing this keypad lookup in Java, I'd consider using hardcoded values with switch statements. If the lookups were done enough times for performance to matter, the Just-In-Time compiler would almost certainly generate code that at least matched and quite possibly beat the implementations here.\nIf a data structure is needed, using an array would probably give the JIT enough information to generate good code, whereas using a Map hides the basically array-oriented processing and would probably make the JIT's job harder.</p>\n<p>A final note to Mandy8055 - if you want good feedback on design, it's helpful to give more detail of what you are trying to achieve. For example in this case, explaining how you'd expect to use the data structure.\nI note that the other examples you link to are concerned with mapping from letters to the corresponding keypad digit. The data structure you outline, and which we've attempted to improve on, does the opposite and if you wanted to go from letters to digits, it's almost certainly a poor choice.\nFor the latter case, I'd still be inclined to an array-based approach, using offsets from 'a' as my array index.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T11:53:55.163", "Id": "505953", "Score": "0", "body": "Agree: _indexed access_ would suffice Even an array (besides `List`) could be initialized `static final` to store a _constant predefined_ and _only numerical_ keymap Start with KISS and keep most readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T13:39:19.673", "Id": "505956", "Score": "2", "body": "(a) Please don't start an answer by insulting other site members. (b) A map makes a promise about lookup performance that a List does not. To make a similar promise, you'd need a `char[][]`. (c) the merits of an ordered vs. unordered structure depends on the use cases that need to be supported. We have no information on that. (d) Your syntax is unclear. It looks like you're trying to make a `List<Character[]>`. Square brackets go inside the type declaration. It also looks like you're trying to implement the list inside an anonymous inner class, which doesn't make much sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T13:55:08.660", "Id": "505958", "Score": "0", "body": "**Why I didn't hardcoded the keypad?:** Actually, I had timed coding test. Less time was there and I had to solve more questions. Therefore, I found using loop would save some time instead of hardcoding the whole keypad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T14:15:16.647", "Id": "505961", "Score": "0", "body": "@EricStein (a) I apologize for any offence caused, but I'd have said the same to any of my experienced java developer colleagues and would have been surprised if they were offended. (b) I'm not proposing a List - an array also gives performance promises and an array of 'List<Character>' is, in my opinion, the natural representation here. (c) ordered vs unordered is irrelevant when the key is an integer from a contiguous set. (d) my syntax is intended to denote that digitsToCharacters is an array of 10 List<Character> objects, not a list of character arrays. Is that unclear?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T11:41:54.477", "Id": "256290", "ParentId": "256258", "Score": "2" } }, { "body": "<h2>Context drives Design</h2>\n<p>The use-case/purpose plays a pivotal role for designing (choosing datastructures and implementations).</p>\n<p>Also the current situation &amp; given constraints (like only Java-7, minimum time to code, test requires a method, etc.) can heavily reduce solution space and justify design-decisions as rational.</p>\n<h3>Assumptions &amp; Constraints</h3>\n<ul>\n<li>you require a <strong>keymap</strong> because you want to be able to react on <em>keypress events</em> from such a <strong>numerical phone keypad</strong>:\n<img src=\"https://i.stack.imgur.com/IWiGV.png\" alt=\"phone keypad\" /></li>\n<li>the keypad has following <strong>number to character</strong> mapping:\n<img src=\"https://i.stack.imgur.com/6w4sM.png\" alt=\"phone keys map number to characters\" /></li>\n<li>use this <em>keymap</em> later within a UI to react on keypress-events, e.g. by implementing a listener where numbers/keys pressed are translated to a letter-typed event</li>\n</ul>\n<h2>Design choices</h2>\n<h3>Datastructures</h3>\n<p>You can use several datastructures like</p>\n<ul>\n<li>accessed by a hash-value: <code>Map</code></li>\n<li>accessed by a (numerical) index: <code>List</code> or simple Java array</li>\n</ul>\n<h3>Implementation details</h3>\n<p>.. as well as several implementations for these, based on your usage-scenarios within an application (threading, concurrency, ordered VS unordered, focus on insertion VS access, etc.).</p>\n<p>Alongside the initialization and filling of these datastructures will vary with the chosen implementation. Supposed you are writing values (e.g. actual key-mapping) only once, then more important is the reading of values. This access usually needs to be fast (e.g. Event: a digit key was pressed. Which characters does it map to?).</p>\n<p>You can compare this <em>trade-off</em> (write VS read) to the design and naming of source-code too: Code is written usually once, but read many times. Thus it is so important to have code-reviews to assure quality: comprehensible &amp; readable code.</p>\n<h2>Current implementation and issues</h2>\n<ul>\n<li>the naming of the variables is hard to read (<em>proprietary abbreviations</em> like <code>hm</code> need prior knowledge of context or decryption)</li>\n<li>a <em>predefined</em> mapping (stated by your <em>given</em> restrictions) is <strong>calculated dynamically</strong> instead of declared as <em>static constant</em></li>\n</ul>\n<h2>Recommended improvement</h2>\n<p>Start simple and use a constant to represent the keymap as most readable.</p>\n<pre class=\"lang-java prettyprint-override\"><code>/**\n * A digit to character mapping as used on phone keypads.\n * &lt;p&gt;\n * The list's index has two essential purposes:\n * (a) represents a key on a numerical keypad\n * (b) serves as index to access elements of this list\n * &lt;/p&gt;\n */\nstatic final List&lt;char[]&gt; DIGIT_TO_CHARACTERS = Arrays.asList(\n new char[] {}, // 0\n new char[] {}, // 1\n new char[] {'a', 'b', 'c'}, // 2\n new char[] {'d', 'e', 'f'}, // 3\n new char[] {'g', 'h', 'i'}, // 4\n new char[] {'j', 'k', 'l'}, // 5\n new char[] {'m', 'n', 'o'}, // 6\n new char[] {'p', 'q', 'r', 's'}, // 7\n new char[] {'t', 'u', 'v'}, // 8\n new char[] {'w', 'x', 'y', 'z'} // 9\n);\n</code></pre>\n<p>Benefits:</p>\n<ul>\n<li><strong>readable</strong>: clear readable mapping (datastructure initialization) and variable name <code>DIGIT_TO_CHARACTERS</code> (conveys intent as: <em>can map digit to (0 to many) characters</em>)</li>\n<li><strong>simply accessible</strong>: <em>get</em> the characters represented by a given digit, like following examples:\n<ul>\n<li>digit 4 is mapped to <code>DIGIT_TO_CHARACTERS.get(4)</code> and will print as character sequence <code>ghi</code></li>\n<li>a single character can be derived by 0-based index, so that <code>DIGIT_TO_CHARACTERS.get(4)[0]</code> will get the single character <code>g</code></li>\n</ul>\n</li>\n<li><strong>performant</strong>: because built at compile-time and static</li>\n</ul>\n<p>See online <a href=\"https://ideone.com/hRVZ7i\" rel=\"nofollow noreferrer\">demo on IDEone</a>.</p>\n<h3>Alternative char-array construction</h3>\n<p>Instead of <code>new char[] {'a', 'b', 'c'}</code> you can also <a href=\"https://stackoverflow.com/questions/10048899/string-to-char-array-java\">construct a char-array from String</a> like <code>&quot;abc&quot;.toCharArray();</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T13:57:07.400", "Id": "505959", "Score": "0", "body": "Thank you @hc_dev for defining the data structure, `final` and `static`. Will surely add it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T14:20:16.383", "Id": "505963", "Score": "1", "body": "@Mandy8055 appreciate :) Your comment lead me to a code-fix & update: (Java ideomatic) convention is to arrange modifiers in order [`static final`](https://stackoverflow.com/questions/507602/how-can-i-initialise-a-static-map). So, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T14:54:04.727", "Id": "505967", "Score": "1", "body": "@Mandy8055 Headless HC's second fix: naming-conventions presrcibe [UPPERCASE for `static final`](https://stackoverflow.com/questions/7259687/java-naming-convention-for-static-final-variables) a.k.a. constants." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T13:24:06.357", "Id": "256294", "ParentId": "256258", "Score": "2" } }, { "body": "<p>Now that @Mandy8055 has given a proper explanation of the use case, I've got a totally different perspective.</p>\n<p>She says her problem statement is this:</p>\n<ol>\n<li><p>We are given two inputs:</p>\n<p>A phone number in <strong>string</strong> format. (Mark: My emphasis)</p>\n<p>A list of strings.</p>\n</li>\n<li><p>The output is the list containing only those strings which correspond to any substring of the given phone number when converted to the corresponding letters on the phone keypad.</p>\n</li>\n</ol>\n<p>Example test case:</p>\n<p>Input:\n&quot;3662277&quot;</p>\n<pre><code>words = [&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;, &quot;emo&quot;, &quot;foobar&quot;, &quot;cap&quot;, &quot;car&quot;, &quot;cat&quot;]\n</code></pre>\n<p>Output:</p>\n<pre><code>outputList = [&quot;foo&quot;, &quot;bar&quot;, &quot;foobar&quot;, &quot;emo&quot;, &quot;cap&quot;, &quot;car&quot;]\n</code></pre>\n<p>Given this problem statement, converting numbers to letters is not an approach I'd choose. I'd go the other way.</p>\n<p>The key thing I notice is that the input set of digits is a String, so it's natural to treat it as such. You are never working with numbers here - you are working with characters, some of which are letters, others are digits.</p>\n<p>If you map the list of words into the equivalent strings of digits (as characters, not numbers) you get (I think - I've done this quickly by hand) this list.</p>\n<pre><code>mappedWords = [ &quot;366&quot;, &quot;227&quot;, &quot;229&quot;, &quot;366&quot;, &quot;366227&quot;,&quot;227&quot;, &quot;227&quot;, &quot;228&quot; }\n</code></pre>\n<p>Each of which you can search for in the input string &quot;3662277&quot; using <em>String.contains()</em>.</p>\n<p>You can take a number of approaches to look up digits for the letters. Neither of the examples you link to, which do this mapping, seem particularly elegant to me.</p>\n<p>If you're particularly keen on using Maps, the natural one to use in this case would look something like this :</p>\n<pre><code>private static final Map&lt;Character, Character&gt; letterToDigit = new HashMap&lt;&gt;;\nletterToDigit.put('a', '2');\nletterToDigit.put('b', '2');\n</code></pre>\n<p>etc...</p>\n<p>I'd be equally inclined to use a switch statement for the mapping - here's an outline of a method to turn an input letter to an output digit. It's incomplete, and you may wish to consider how you deal with out-of-range input:</p>\n<pre><code>private static char digitFromLetter(char letter) {\n switch(letter) {\n case 'a':\n case 'b':\n case 'c':\n return '2';\n case 'd':\n case 'e':\n case 'f':\n return '3';\n ...\n }\n}\n</code></pre>\n<p>Some may challenge the performance of this approach, but a) I'm not convinced performance is important in this particular case and b) I'd wager that a JIT compiler would make it perform perfectly well anyway.</p>\n<p>You could also look at an array-based approach, outlined here, but incomplete and needing error handling:-</p>\n<pre><code>private static final char[] digit = new char[] {\n '2', '2', '2', // abc\n '3', '3', '3', // def\n ...\n};\n\nprivate static char digitFromLetter(char letter) {\n return digit[letter - 'a'];\n}\n</code></pre>\n<p>Hope this is helpful and interesting.</p>\n<p>Edit: I had some free time and access to an IDE, so here's my solution to the stated problem.</p>\n<pre><code>package keypad;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Keypad {\n\n private static final boolean DEBUG = true;\n\n public static void main(String[] args) {\n System.out.println(selectWords(&quot;3662277&quot;, new String[]{&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;, &quot;emo&quot;, &quot;foobar&quot;, &quot;cap&quot;, &quot;car&quot;, &quot;cat&quot;}));\n }\n\n /**\n * @param letter\n * @return the corresponding digit on a telephone keypad\n * @throws IllegalArgumentException if the letter isn't in the alphabet\n */\n private static char letterToDigit(char letter) {\n switch (Character.toLowerCase(letter)) {\n case 'a' :\n case 'b' :\n case 'c' :\n return '2';\n case 'd' :\n case 'e' :\n case 'f' :\n return '3';\n case 'g' :\n case 'h' :\n case 'i' :\n return '4';\n case 'j' :\n case 'k' :\n case 'l' :\n return '5';\n case 'm' :\n case 'n' :\n case 'o' :\n return '6';\n case 'p' :\n case 'q' :\n case 'r' :\n case 's' :\n return '7';\n case 't' :\n case 'u' :\n case 'v' :\n return '8';\n case 'w' :\n case 'x' :\n case 'y' :\n case 'z' :\n return '9';\n default :\n // Bad value - we'll simply throw an unchecked exception in this example\n throw new IllegalArgumentException(String.format(&quot;The input '%s' is not in the range 'a' - 'z'&quot;, letter));\n }\n }\n\n /**\n * @param word - a word\n * @return the string of digits corresponding to that word\n */\n private static String digitise(String word) {\n StringBuffer digitisedWord = new StringBuffer(word.length());\n for (int characterIndex = 0; characterIndex &lt; word.length(); characterIndex++) {\n digitisedWord.append(letterToDigit(word.charAt(characterIndex)));\n }\n return digitisedWord.toString();\n }\n\n /**\n * @param words\n * @return the words, remapped to their keypad digit representations\n */\n private static String[] digitise(String[] words) {\n String[] digitisedWords = new String[words.length];\n for (int wordIndex = 0; wordIndex &lt; words.length; wordIndex++) {\n digitisedWords[wordIndex] = digitise(words[wordIndex]);\n }\n return digitisedWords;\n }\n\n /**\n * @param words candidate words to be checked\n * @param digitisedWords corresponding &quot;digitised&quot; words\n * @param digits a string of digits to be searched for the digitised words\n * @return all words for which their digitised version could be found in &quot;digits&quot;\n */\n private static List&lt;String&gt; filter(String[] words, String[] digitisedWords, String digits) {\n List&lt;String&gt; filteredWords = new ArrayList&lt;&gt;(); // List rather than array as we can't predict the actual size\n for (int wordIndex = 0; wordIndex &lt; words.length; wordIndex++) {\n if (digits.contains(digitisedWords[wordIndex])) {\n filteredWords.add(words[wordIndex]);\n }\n }\n return filteredWords;\n }\n\n /**\n * Check a list of words against a sequence of digits\n * @param digits\n * @param words\n * @return all words which could be represented in the sequence of digits\n */\n public static List&lt;String&gt; selectWords(String digits, String[] words) {\n if (DEBUG) {\n System.out.format(&quot;Searching for %s in %s%n&quot;, Arrays.toString(words), digits);\n }\n\n String[] digitisedWords = digitise(words);\n\n if (DEBUG) {\n System.out.format(&quot;Remapped the words to %s%n&quot;, Arrays.toString(digitisedWords));\n }\n\n return filter(words, digitisedWords, digits);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T02:45:43.473", "Id": "506011", "Score": "0", "body": "Given the update, the switch solution here is what I would go with." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T18:23:43.387", "Id": "256310", "ParentId": "256258", "Score": "2" } } ]
{ "AcceptedAnswerId": "256284", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T13:09:16.617", "Id": "256258", "Score": "6", "Tags": [ "java" ], "Title": "Best data Structure for storing a phone keypad format" }
256258
<p>This is my solution to the N-Queens Puzzle.</p> <p>Here is the AEC code (compiled to WebAssembly):</p> <pre><code>/* * My solution to the n-queens puzzle, one of the classical problems of the * structural programming. It asks in how many ways you can arrange n chess * queens on an n-times-n chessboard without breaking the rules that no two * chess queens can be in the same row, column or diagonal. */ // Import some functions we need to communicate with the outside world from // JavaScript... Function printString(CharacterPointer str) Which Returns Nothing Is External; Function clearScreen() Which Returns Nothing Is External; Function shouldWePrintChessBoards() Which Returns Integer32 Is External; // Declare the &quot;Queen&quot; structure and write relevant functions. Structure Queen Consists Of Integer32 row, column; EndStructure Function areQueensInTheSameColumn(QueenPointer first, QueenPointer second) Which Returns Integer32 Does Return first-&gt;column = second-&gt;column; EndFunction Function areQueensInTheSameRow(QueenPointer first, QueenPointer second) Which Returns Integer32 Does Return first-&gt;row = second-&gt;row; EndFunction Function areQueensOnTheSameDiagonal(QueenPointer first, QueenPointer second) Which Returns Integer32 Does Return first-&gt;row + first-&gt;column = second-&gt;row + second-&gt;column or first-&gt;row - first-&gt;column = second-&gt;row - second-&gt;column; EndFunction Function areQueensAttackingEachOther(QueenPointer first, QueenPointer second) Which Returns Integer32 Does Return areQueensInTheSameRow(first, second) or areQueensInTheSameColumn(first, second) or areQueensOnTheSameDiagonal(first, second); EndFunction // Let's write a structure representing an array of queens... Structure ChessBoard Consists Of Integer32 length; Queen queens[12]; // There are too many solutions for over 12 queens. EndStructure Function chessBoardContainsThatQueen(ChessBoardPointer chessBoard, QueenPointer queen) Which Returns Integer32 Does Integer32 i := 0; While i &lt; chessBoard-&gt;length Loop If chessBoard-&gt;queens[i].column = queen-&gt;column and chessBoard-&gt;queens[i].row = queen-&gt;row Then Return 1; EndIf i += 1; EndWhile Return 0; EndFunction // Now, let's forward-declare the functions we will write later. // Putting them here would make the code less legible. Function recursiveFunction(ChessBoardPointer chessBoard, Integer32 n) Which Returns Integer32 Is Declared; Function convertIntegerToString(CharacterPointer str, Integer32 n) Which Returns Nothing Is Declared; Function strcat(CharacterPointer dest, CharacterPointer src) Which Returns Nothing Is Declared; Function strlen(CharacterPointer str) Which Returns Integer32 Is Declared; // Let's write the function that JavaScript is supposed to call... Function nQueensPuzzle(Integer32 n) Which Returns Integer32 Does clearScreen(); If n &lt; 1 or n &gt; 12 Then printString(&quot;Please enter a number between 1 and 12!&quot;); Return -1; EndIf InstantiateStructure ChessBoard chessBoard; Character stringToBePrinted[64] := {0}; CharacterPointer stringToBePrinted := AddressOf(stringToBePrinted[0]); strcat(stringToBePrinted, &quot;Solving the n-queens puzzle for &quot;); convertIntegerToString(stringToBePrinted + strlen(stringToBePrinted), n); strcat(stringToBePrinted,&quot;:\n&quot;); printString(stringToBePrinted); Integer32 result := recursiveFunction(AddressOf(chessBoard), n); stringToBePrinted[0] := 0; strcat(stringToBePrinted, &quot;Found &quot;); convertIntegerToString(stringToBePrinted + strlen(stringToBePrinted), result); strcat(stringToBePrinted, &quot; solutions!&quot;); printString(stringToBePrinted); Return result; EndFunction // I guess moving this code out of &quot;recursiveFunction&quot; makes the // code more legible. Function printAsASolution(ChessBoardPointer chessBoard) Which Returns Nothing Does Character stringToBePrinted[64] := {0}; Character stringToBeAdded[8]; Integer32 i := 0; While i &lt; chessBoard-&gt;length Loop stringToBeAdded[0] := 'A' + chessBoard-&gt;queens[i].column; convertIntegerToString(AddressOf(stringToBeAdded[1]), chessBoard-&gt;queens[i].row + 1); strcat(AddressOf(stringToBeAdded[0]), &quot; &quot;); strcat(AddressOf(stringToBePrinted[0]), AddressOf(stringToBeAdded[0])); i += 1; EndWhile strcat(AddressOf(stringToBePrinted[0]), &quot;\n&quot;); printString(AddressOf(stringToBePrinted[0])); If shouldWePrintChessBoards() Then stringToBePrinted[0] := 0; CharacterPointer stringToBePrinted := AddressOf(stringToBePrinted[0]); strcat(stringToBePrinted, &quot; +&quot;); i := 0; While i &lt; chessBoard-&gt;length Loop strcat(stringToBePrinted, &quot;-+&quot;); i += 1; EndWhile strcat(stringToBePrinted, &quot;\n&quot;); printString(stringToBePrinted); i := chessBoard-&gt;length; While i &gt; 0 Loop stringToBePrinted[0] := 0; // Align the row numbers to the right. If i &lt; 10 Then strcat(stringToBePrinted, &quot; &quot;); EndIf convertIntegerToString(stringToBePrinted + strlen(stringToBePrinted), i); strcat(stringToBePrinted, &quot;|&quot;); Integer32 j := 0; While j &lt; chessBoard-&gt;length Loop InstantiateStructure Queen newQueen; newQueen.column := j; newQueen.row := i - 1; strcat(stringToBePrinted, chessBoardContainsThatQueen(chessBoard, AddressOf(newQueen))? &quot;Q|&quot;: mod(i + j - 1, 2)? &quot; |&quot;: // White field. &quot;*|&quot; // Black field. ); j += 1; EndWhile strcat(stringToBePrinted, &quot;\n&quot;); printString(stringToBePrinted); stringToBePrinted[0] := 0; strcat(stringToBePrinted, &quot; +&quot;); j := 0; While j &lt; chessBoard-&gt;length Loop strcat(stringToBePrinted, &quot;-+&quot;); j += 1; EndWhile strcat(stringToBePrinted, &quot;\n&quot;); printString(stringToBePrinted); i -= 1; EndWhile stringToBePrinted[0] := 0; CharacterPointer stringToBeAdded := AddressOf(stringToBeAdded[0]); stringToBeAdded[2] := 0; stringToBeAdded[0] := ' '; strcat(stringToBePrinted, &quot; &quot;); i := 0; While i &lt; chessBoard-&gt;length Loop stringToBeAdded[1] := 'A' + i; strcat(stringToBePrinted, stringToBeAdded); i += 1; EndWhile strcat(stringToBePrinted, &quot;\n&quot;); printString(stringToBePrinted); EndIf EndFunction // Now, let's implement the brute-force algorithm. Function recursiveFunction(ChessBoardPointer chessBoard, Integer32 n) Which Returns Integer32 Does // First, do some sanity checks useful for debugging... If chessBoard-&gt;length &gt; n Then printString(&quot;Bug: Chessboard length too large!&quot;); Return 0; EndIf Integer32 i := 0, j := 0; While i &lt; chessBoard-&gt;length Loop If chessBoard-&gt;queens[i].column &lt; 0 or chessBoard-&gt;queens[i].row &lt; 0 or chessBoard-&gt;queens[i].column &gt; n or chessBoard-&gt;queens[i].row &gt; n Then printString(&quot;Bug: Corrupt chessboard!&quot;); Return 0; EndIf i += 1; EndWhile // Check if there is a contradiction (queens attacking // each other) in what we have thus far... i := j := 0; While i &lt; chessBoard-&gt;length Loop j := i + 1; While j &lt; chessBoard-&gt;length Loop If not(i = j) and areQueensAttackingEachOther( AddressOf(chessBoard-&gt;queens[i]), AddressOf(chessBoard-&gt;queens[j]) ) Then Return 0; EndIf j += 1; EndWhile i += 1; EndWhile // Check if this is a solution... If chessBoard-&gt;length = n Then printAsASolution(chessBoard); Return 1; EndIf // If this is not a complete solution, but there are no contradictions // in it, branch the recursion into searching for complete solutions // based on this one. Integer32 result := 0; i := 0; While i&lt;n Loop InstantiateStructure ChessBoard newChessBoard := ValueAt(chessBoard); newChessBoard.length += 1; newChessBoard.queens[chessBoard-&gt;length].column := chessBoard-&gt;length; newChessBoard.queens[chessBoard-&gt;length].row := i; result += recursiveFunction(AddressOf(newChessBoard), n); i += 1; EndWhile Return result; EndFunction // Now go the helper functions related to string manipulation, // copied from the Dragon Curve program. They are named the same // as the corresponding functions in the standard C library. Function strlen(CharacterPointer str) Which Returns Integer32 Does Integer32 length := 0; While ValueAt(str + length) Loop length := length + 1; EndWhile Return length; EndFunction Function strcpy(CharacterPointer dest, CharacterPointer src) Which Returns Nothing Does While ValueAt(src) Loop ValueAt(dest) := ValueAt(src); dest := dest + 1; src := src + 1; EndWhile ValueAt(dest) := 0; EndFunction Function strcat(CharacterPointer dest, CharacterPointer src) Which Returns Nothing Does strcpy(dest + strlen(dest), src); EndFunction Function reverseString(CharacterPointer string) Which Returns Nothing Does CharacterPointer pointerToLastCharacter := string + strlen(string) - 1; While pointerToLastCharacter - string &gt; 0 Loop Character tmp := ValueAt(string); ValueAt(string) := ValueAt(pointerToLastCharacter); ValueAt(pointerToLastCharacter) := tmp; string := string + 1; pointerToLastCharacter := pointerToLastCharacter - 1; EndWhile EndFunction Function convertIntegerToString(CharacterPointer string, Integer32 number) Which Returns Nothing Does Integer32 isNumberNegative := 0; If number &lt; 0 Then number := -number; isNumberNegative := 1; EndIf Integer32 i := 0; While number &gt; 9 Loop ValueAt(string + i) := '0' + mod(number, 10); number := number / 10; i := i + 1; EndWhile ValueAt(string + i) := '0' + number; i := i + 1; If isNumberNegative Then ValueAt(string + i) := '-'; i := i + 1; EndIf ValueAt(string + i) := 0; reverseString(string); EndFunction </code></pre> <p>Here is my HTML code:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;!-- See Arithmetic Operators Test for explanations.--&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;title&gt;AEC-to-WebAssembly compiler - N-Queens Puzzle&lt;/title&gt; &lt;style type=&quot;text/css&quot;&gt; body { font-family: sans-serif; } #format_as_code { font-family: &quot;Lucida Console&quot;, monospace; white-space: pre; width: 100%; background: #eeeeee; height: 75vh; display: block; overflow: scroll; } h1 { text-align: center; } &lt;/style&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;N-Queens Puzzle&lt;/h1&gt; I have decided to write a solution to the &lt;a href=&quot;https://en.wikipedia.org/wiki/Eight_queens_puzzle&quot;&gt; N-Queens Puzzle&lt;/a &gt;, one of the classic problems in computer science, in the &lt;a href=&quot;https://flatassembler.github.io/AEC_specification.html&quot; &gt;AEC programming language&lt;/a &gt;. That puzzle asks in how many ways you can arrange &lt;i&gt;n&lt;/i&gt; chess queens on an &lt;i&gt;n&lt;/i&gt;-times-&lt;i&gt;n&lt;/i&gt; chessboard without breaking the rules that no two chess queens can be in the same row, column or diagonal. &lt;br /&gt; &lt;b&gt;This only works in very modern browsers.&lt;/b&gt; I'm not too interested in targeting archaic browsers here. This only works in Firefox 62 and newer or Chrome 69 and newer. After a few years (if not months), all JavaScript environments will become as capable as they are, rather than like Internet Explorer.&lt;br /&gt;&lt;br /&gt; &lt;form&gt; &lt;label for=&quot;enterTheNumber&quot; &gt;Enter the numberi &lt;i&gt;n&lt;/i&gt; (between 1 and 12):&lt;/label &gt;&lt;br /&gt; &lt;input type=&quot;text&quot; id=&quot;enterTheNumber&quot; name=&quot;enterTheNumber&quot; /&gt;&lt;br /&gt; &lt;input type=&quot;checkbox&quot; id=&quot;printChessBoards&quot; name=&quot;printChessBoards&quot; /&gt;&lt;label for=&quot;printChessBoards&quot;&gt;Print chess-boards using ASCII art&lt;/label&gt; &lt;/form&gt; &lt;button onclick=&quot;invokeAECfunctions()&quot;&gt;Invoke AEC program!&lt;/button &gt;&lt;br /&gt;&lt;br /&gt; AEC program output:&lt;br /&gt; &lt;span id=&quot;format_as_code&quot;&gt;&lt;/span&gt; &lt;br /&gt; You can see the source code of the AEC program &lt;a href=&quot;nQueensPuzzle.aec.html&quot;&gt;here&lt;/a&gt;. &lt;script type=&quot;text/javascript&quot;&gt; const stack_pointer = new WebAssembly.Global( { value: &quot;i32&quot;, mutable: true }, 0 ); let memory = new WebAssembly.Memory({ initial: 1 }); function printString(ptr) { let buffer = new Uint8Array(memory.buffer); let str = &quot;&quot;; while (buffer[ptr]) { str += String.fromCharCode(buffer[ptr]); ptr++; } document.getElementById(&quot;format_as_code&quot;).innerHTML += str; } function clearScreen() { document.getElementById(&quot;format_as_code&quot;).innerHTML = &quot;&quot;; } function shouldWePrintChessBoards() { return document.getElementById(&quot;printChessBoards&quot;).checked; } let importObject = { JavaScript: { stack_pointer: stack_pointer, memory: memory, printString: printString, clearScreen: clearScreen, shouldWePrintChessBoards: shouldWePrintChessBoards, }, }; let nQueensPuzzle; fetch(&quot;nQueensPuzzle.wasm&quot;) .then((response) =&gt; response.arrayBuffer()) .then((bytes) =&gt; WebAssembly.instantiate(bytes, importObject)) .then((results) =&gt; { const exports = results.instance.exports; nQueensPuzzle = exports.nQueensPuzzle; }); function invokeAECfunctions() { let originalNumber = parseInt( document.getElementById(&quot;enterTheNumber&quot;).value ); nQueensPuzzle(originalNumber); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>You can (hopefully) see it live here: <a href="https://flatassembler.github.io/nQueensPuzzle.html" rel="nofollow noreferrer">https://flatassembler.github.io/nQueensPuzzle.html</a></p> <p>So, what do you think, how can I make it better?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T13:54:27.533", "Id": "256259", "Score": "0", "Tags": [ "n-queens", "webassembly" ], "Title": "N-Queens Puzzle in AEC" }
256259
<p>I have the following code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = Array.from({length: 5}, (_, i) =&gt; i + 1); const finalArray = []; for (let i = 0; i &lt; arr.length; i++) { for (let j = 0; j &lt; arr.length; j++) { finalArray.push(arr[i] + '-' + arr[j]) } } console.log(finalArray);</code></pre> </div> </div> </p> <p>Which creates an array of range 1 =&gt; 5, and returns an array with a combination of all elements in the original array.</p> <p>This code runs in O(n²), is it possible to make it more efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T08:35:11.890", "Id": "506115", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<h1>No</h1>\n<p>You cannot output <span class=\"math-container\">\\$\\Theta(n^2)\\$</span> items in <span class=\"math-container\">\\$o(n^2)\\$</span> time. Output size is a <strong>trivial lower bound</strong> of any algorithms.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T12:30:04.957", "Id": "506133", "Score": "0", "body": "So you mean that my code is most performant?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T01:26:57.107", "Id": "506187", "Score": "1", "body": "@callback from the view of big-O notation: Yes. To improve its performance: Maybe No." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T07:41:07.730", "Id": "256366", "ParentId": "256261", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T15:04:34.027", "Id": "256261", "Score": "0", "Tags": [ "javascript", "performance" ], "Title": "loop inside loop over one array" }
256261
<p>The following script upgrades an existing, all core (no add ons) MediaWiki install. I run it with <code>set -x</code> for debugging (I avoid <code>set -euo</code> because I often run this script line by line and/or block by block and in case of typos or problems this terminates the session, which I don't want to happen).</p> <p>I have double tested the script and it is working fine (if your hosting provider requires you to add a directory such as <code>public_html</code> on top of <code>web_application_root/domain</code> than of course it should be added and the script should be updated accordingly).</p> <p>By the way, I double create backups; before running this entire script I create filetree and DB backups from my hosting provider's tools as well and store them on my own computer device, just in case.</p> <h2>Code</h2> <h3>File 1: General preface</h3> <pre><code>#!/bin/bash ## Declare latest mediawiki core download link: latest_mediawiki_core=&quot;https://releases.wikimedia.org/mediawiki/1.35/mediawiki-1.35.1.tar.gz&quot; ## Declare web application variables: read domain read db_name read db_nonroot_user_name web_application_root=&quot;${HOME}/www&quot; domain_dir=&quot;${web_application_root}/${domain}&quot; </code></pre> <h3>File 2: Backups preface</h3> <pre><code>#!/bin/bash ## Declare existing installation backup variables: current_date=&quot;$(date +%d-%m-%Y-%H-%M-%S)&quot; &amp;&amp; general_backups_dir=&quot;${HOME}/mediawiki_general_backups&quot; &amp;&amp; specific_backups_dir=&quot;${HOME}/mediawiki_specific_backups&quot; ## If fresh backup directories don't exist, create them: # due to the rm -rf command below I personally prefer to first do a pre-script backup of both the DB and filetree rm -rf &quot;${general_backups_dir}&quot; &amp;&amp; mkdir -p &quot;${general_backups_dir}&quot; &amp;&amp; rm -rf &quot;${specific_backups_dir}&quot; &amp;&amp; mkdir -p &quot;${specific_backups_dir}&quot; ## Test existence of empty directories ll &quot;${general_backups_dir}&quot; &amp;&amp; ll &quot;${specific_backups_dir}&quot; </code></pre> <h3>File 3: Database backups</h3> <pre><code>#!/bin/bash ## Create database general backup: mysqldump -u&quot;$db_nonroot_user_name&quot; -p &quot;$db_name&quot; &gt; &quot;${general_backups_dir}/${db_nonroot_user_name}-${current_date}.sql&quot; ## Test database general backup: ll $general_backups_dir </code></pre> <h3>File 4: Filetree backups</h3> <pre><code>#!/bin/bash ## Create filetree general backups: zip -r &quot;${general_backups_dir}/${domain}-directory-backup-${current_date}.zip&quot; &quot;${domain_dir}&quot; ## Create filetree specific backups (Some files have shell glob patterns outside quote marks): cp &quot;${domain_dir}/LocalSettings.php&quot; &quot;${specific_backups_dir}&quot; &amp;&amp; cp &quot;${domain_dir}/robots.txt&quot; &quot;${specific_backups_dir}&quot; &amp;&amp; cp &quot;${domain_dir}/${domain}.png&quot; &quot;${specific_backups_dir}&quot; &amp;&amp; cp &quot;${domain_dir}&quot;/.htaccess* &quot;${specific_backups_dir}&quot; &amp;&amp; cp &quot;${domain_dir}&quot;/google*.html &quot;${specific_backups_dir}&quot; ## Test filetree general backups: ll $general_backups_dir ## Test filetree specific backups: ll $specific_backups_dir </code></pre> <h3>File 5: Installation</h3> <pre><code>#!/bin/bash ## Prepare to download, install and configure MediaWiki and specific backups: ## cd &quot;${web_application_root}&quot; rm -rf &quot;${domain_dir}&quot; ## Download and configure MediaWiki core: wget &quot;${latest_mediawiki_core}&quot; &amp;&amp; find . -maxdepth 1 -iname 'mediawiki*.tar.gz' -type f -exec tar -xzf {} \; &amp;&amp; find . -maxdepth 1 -type d -iname '*mediawiki*' -execdir mv {} &quot;${domain}&quot; \; &amp;&amp; find . -maxdepth 1 -iname 'mediawiki*.tar.gz' -type f -exec rm {} \; ## Test previous operation: ## ll ## Retrieve specific backups to the new installation: cp -a &quot;${specific_backups_dir}&quot;/.htaccess &quot;${domain_dir}&quot; # Only .htaccess file; cp -a &quot;${specific_backups_dir}&quot;/* &quot;${domain_dir}&quot; # All files besides .htaccess; ## Test specific backups retrieving: ll ${domain_dir} </code></pre> <h3>File 6: Configurations</h3> <pre><code>## Prepare to create and configure a new sitemap and to update database: cd &quot;${domain_dir}&quot; ## Create a new sitemap: rm -rf &quot;${domain_dir}/sitemap&quot; mkdir -p &quot;${domain_dir}/sitemap&quot; php &quot;${domain_dir}/maintenance/generateSitemap.php&quot; \ --memory-limit=50M \ --fspath=/&quot;${domain_dir}/sitemap&quot; \ --identifier=&quot;${domain}&quot; \ --urlpath=/sitemap/ \ --server=https://&quot;${domain}&quot; \ --compress=yes # Ensure that robots.txt sitemap directive is: # Sitemap: https://&quot;${domain}&quot;/sitemap/sitemap-index-&quot;${domain}&quot;.xml ## Update database (One might need to change LocalSettings.php before doing so): php &quot;${domain_dir}/maintenance/update.php&quot; --quick &amp;&amp; php maintenance/rebuildrecentchanges.php </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T17:38:00.017", "Id": "505889", "Score": "1", "body": "This question was [linked to at the MediaWiki support desk](https://mediawiki.org/wiki/Topic:W3sx24rgg0eul8zt)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T17:39:42.857", "Id": "505890", "Score": "0", "body": "Yes, and BTW, is there someone here whom will agree to add a \"MediaWiki\" tag in the tags section? Some MediaWiki engineers are registered users in the wide community and might get an RSS feed about this thread so (I think)." } ]
[ { "body": "<p>Some remarks</p>\n<p>File 1: General preface</p>\n<pre><code>## Declare web application variables:\nread domain\nread db_name\nread db_nonroot_user_name\n</code></pre>\n<p>When the user is prompted for a string, please tell what is wanted:</p>\n<pre><code>read -p &quot;Domain: &quot; domain\nread -p &quot;Database name: &quot; db_name\nread -p &quot;Datebase user (not admin): &quot; db_nonroot_user_name\n</code></pre>\n<p>File 2: Backups preface</p>\n<pre><code>## Declare existing installation backup variables:\ncurrent_date=&quot;$(date +%d-%m-%Y-%H-%M-%S)&quot; &amp;&amp;\ngeneral_backups_dir=&quot;${HOME}/mediawiki_general_backups&quot; &amp;&amp;\nspecific_backups_dir=&quot;${HOME}/mediawiki_specific_backups&quot;\n</code></pre>\n<p>Remove the <code>&amp;&amp;</code>, the assignment will work.</p>\n<pre><code>rm -rf &quot;${general_backups_dir}&quot; &amp;&amp;\nmkdir -p &quot;${general_backups_dir}&quot; &amp;&amp;\nrm -rf &quot;${specific_backups_dir}&quot; &amp;&amp;\nmkdir -p &quot;${specific_backups_dir}&quot;\n</code></pre>\n<p>You do not have a check on the last command. When another command fails, the next command is skipped, but the script continues. Consider error handling like</p>\n<pre><code>die() {\n echo &quot;Fatal error: $*&quot;\n exit 1\n}\n\nrm -rf &quot;${general_backups_dir}&quot; || die &quot;Removing ${general_backups_dir} failed.&quot;\nmkdir -p &quot;${general_backups_dir}&quot; || die &quot;Creating ${general_backups_dir} failed.&quot;\nrm -rf &quot;${specific_backups_dir}&quot; || die &quot;Removing ${specific_backups_dir} failed.&quot;\nmkdir -p &quot;${specific_backups_dir}&quot; || die &quot;Creating ${specific_backups_dir} failed.\n</code></pre>\n<p>&quot;</p>\n<pre><code>## Test existence of empty directories\nll &quot;${general_backups_dir}&quot; &amp;&amp;\nll &quot;${specific_backups_dir}&quot;\n</code></pre>\n<p>Test is not needed with the <code>die</code> construction. When you want to test, use</p>\n<pre><code>test -d &quot;${general_backups_dir}&quot; || die &quot;Missing ${general_backups_dir}.&quot; \n</code></pre>\n<p>File 4: Filetree backups</p>\n<pre><code>## Create filetree specific backups \ncp &quot;${domain_dir}/LocalSettings.php&quot; &quot;${specific_backups_dir}&quot; &amp;&amp; ...\n</code></pre>\n<p>Test the copy result with</p>\n<pre><code>cp &quot;${domain_dir}/LocalSettings.php&quot; &quot;${specific_backups_dir}&quot; || die &quot;cp LocalSettings failed.&quot;\n</code></pre>\n<p>File 5: Installation</p>\n<pre><code>## Prepare to download, install and configure MediaWiki and specific backups: ##\ncd &quot;${web_application_root}&quot;\n</code></pre>\n<p>The cd commands are really important. What will happen, when the user doesn't has a www directory?</p>\n<pre><code>cd &quot;${web_application_root}&quot; || die &quot;cd ${web_application_root} failed&quot;\n</code></pre>\n<p>Remove with care</p>\n<pre><code>rm -rf &quot;${domain_dir}&quot;\n</code></pre>\n<p>Sure about this? Perhaps the user hit enter by accident when he was asked for a domain.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T20:48:26.683", "Id": "257455", "ParentId": "256262", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T15:19:05.987", "Id": "256262", "Score": "3", "Tags": [ "bash", "database", "linux", "modules", "automation" ], "Title": "All core MediaWiki upgrade script (round 2)" }
256262
<p>I was trying to make a sorting algorithm for an array of integers. Here's are the steps/theory:</p> <p>It turns an array into a <code>HashSet</code>, iterates over every integer value from the minimum value in the array to the maximum. It carries an array that starts with 1 element, the minimum. While iterating to higher values through increments, if it finds a value in that HashSet that is equal to the value, it pushes that value to the array and continues iterating until it hits the max value.</p> <p>Here is a JS implementation of what I mean with a shuffled array from 1 to a 1000 with 2 integers missing (which are <code>224</code> and <code>507</code> that I manually deleted, so 998 elements in the array)</p> <pre class="lang-javascript prettyprint-override"><code>const log = console.log let arr = [71,825,522,901,579,219,251,6,672,9,578,81,195,315,64,763,538,500,772,75,713,127,800,766,185,609,945,182,511,803,671,365,309,920,159,572,225,405,403,123,77,283,370,421,98,937,76,437,916,21,15,376,641,218,870,122,878,449,138,475,142,893,966,152,394,749,134,687,924,595,859,100,824,333,524,104,850,358,254,407,751,646,933,443,61,736,699,745,784,773,454,388,922,615,119,950,528,607,166,816,596,600,741,292,299,926,291,724,711,550,639,627,462,176,161,902,156,31,258,983,624,667,257,598,837,350,163,558,115,351,214,717,51,99,810,238,375,441,228,848,97,770,169,808,664,764,137,1000,946,849,799,354,856,688,38,321,868,845,40,217,366,360,820,682,456,904,73,935,701,807,726,594,493,363,861,14,539,301,439,665,928,434,999,260,330,758,307,237,995,153,476,669,542,270,102,978,915,481,440,815,177,203,728,563,490,406,748,265,145,526,661,362,171,192,359,754,173,155,280,425,684,415,791,266,503,90,865,903,19,364,940,863,533,199,317,710,442,554,178,734,174,463,706,435,725,997,702,547,36,882,930,847,485,328,670,927,224,187,722,12,683,515,140,50,760,658,871,514,649,608,809,862,636,355,41,757,562,794,148,491,322,495,715,753,261,418,556,811,605,747,319,663,938,357,704,900,492,857,325,777,629,264,887,812,29,65,49,619,504,836,662,83,628,698,604,230,121,653,220,762,689,212,361,11,1,465,918,141,259,194,543,385,497,279,973,737,712,467,103,79,170,209,914,775,520,519,110,459,941,744,25,470,52,656,131,383,342,382,931,569,846,638,352,48,339,586,297,395,60,318,529,335,603,986,453,535,793,552,346,587,557,472,44,271,331,675,774,537,635,525,461,697,416,445,248,952,985,457,839,17,263,631,94,268,386,377,886,298,120,781,278,223,464,471,206,546,393,139,679,408,881,874,183,707,398,3,967,196,189,305,906,883,344,634,92,723,714,136,483,245,829,826,532,730,827,830,626,124,984,401,782,720,452,898,567,236,994,612,677,242,790,948,56,840,23,934,39,565,96,314,241,30,469,412,204,879,795,107,125,282,981,414,304,716,601,787,191,62,281,894,151,235,959,801,998,574,499,226,128,789,921,160,295,517,540,765,308,873,78,296,834,501,813,549,22,399,284,971,450,486,960,709,502,955,771,28,482,68,833,340,694,129,426,561,311,911,835,113,685,423,780,84,494,735,516,822,796,909,432,57,381,876,571,555,369,496,963,969,872,739,643,232,972,623,988,786,473,190,752,42,367,16,327,585,854,742,144,591,866,126,243,479,647,633,353,252,59,573,805,13,436,424,982,74,2,34,430,290,215,197,621,534,877,559,593,592,884,288,7,977,923,875,806,648,767,674,508,274,545,889,566,613,895,956,577,944,53,729,618,976,802,614,606,962,400,718,905,66,518,105,844,149,632,211,819,286,58,957,460,262,611,993,964,792,891,645,18,419,719,164,731,560,253,202,630,858,943,67,409,267,932,269,444,814,387,527,992,55,974,411,951,372,564,590,468,818,275,755,389,657,617,338,625,45,690,368,154,80,256,681,990,216,429,277,474,821,130,996,273,740,167,249,949,334,642,26,179,768,54,150,85,912,804,175,294,234,337,101,8,106,240,20,233,853,695,447,108,838,146,205,379,551,510,86,817,93,541,652,111,239,640,374,410,487,488,864,95,349,320,184,35,531,597,785,306,4,135,644,72,255,227,880,738,289,89,132,954,326,336,303,783,654,272,438,855,548,536,907,521,678,422,343,246,384,523,925,208,200,899,947,616,929,828,158,332,207,221,888,913,779,703,896,310,582,466,588,293,378,373,580,610,402,622,867,420,673,851,427,841,392,509,247,345,890,897,91,987,478,660,37,581,506,147,696,287,637,732,965,112,33,87,553,843,970,743,63,570,484,477,5,312,576,692,892,489,32,47,750,910,676,860,390,396,316,505,761,650,756,708,276,961,180,979,568,455,193,323,919,82,347,968,659,324,458,975,480,70,727,666,451,285,942,433,575,602,769,746,776,46,118,417,397,231,651,831,908,512,162,693,210,201,391,869,980,778,186,530,448,404,24,356,939,114,788,498,686,117,759,989,250,936,885,691,109,680,832,620,842,823,513,88,10,431,329,181,168,705,172,43,668,165,721,198,413,371,798,544,313,852,583,213,599,446,589,157,229,380,917,991,348,341,27,302,222,584,116,797,133,958,428,143,188,953,733,300,69,700,655 ]; const sort = to_sort =&gt; { let parts = new Set(to_sort); function getMinMax(arr) { let min = arr[0]; let max = arr[0]; let i = arr.length; while (i--) { min = arr[i] &lt; min ? arr[i] : min; max = arr[i] &gt; max ? arr[i] : max; } return { min, max }; } let minMax = getMinMax(to_sort); const sortArray = (value,array) =&gt; { if (value &gt; minMax.max) { return array; } if (parts.has(value)) { array.push(value); } return sortArray(value+1,array) } return sortArray(minMax.min+1,[minMax.min]) } console.time() log(sort(arr)); console.timeEnd() </code></pre> <p>Limitations I know of are:</p> <ol> <li><p>There cannot be any duplicates in the array, I could use a <code>HashMap</code> if there are.</p> </li> <li><p>Bad performance for arrays where the integer value difference is significant, which means more iterating and a possible <code>call stack exceeded</code> error.</p> </li> <li><p>Uses a decent amount of memory</p> </li> </ol> <p>It takes about 8 milliseconds to sort the array when <a href="https://repl.it/@Kudos/Hashsort#index.js" rel="nofollow noreferrer">testing it online</a></p> <p><a href="https://storage.googleapis.com/replit/images/1613836679652_845e08b52a0e4fb7388038f5e012183c.png" rel="nofollow noreferrer"><img src="https://storage.googleapis.com/replit/images/1613836679652_845e08b52a0e4fb7388038f5e012183c.png" alt="Output" /></a></p> <p>After all of this context, I would like to know:</p> <ol> <li><p>What sort of algorithm is this (or based on)?</p> </li> <li><p>Does this have any performance benefit compared to other algorithms?</p> </li> </ol>
[]
[ { "body": "<p>Use <code>const</code> instead of <code>let</code> to prevent accidental overwrite of variables.</p>\n<p>Use consistent variable names. Seems weird to combine snake_case and camelCase.</p>\n<p>For empty input, min and max is undefined. You can check this case and return empty array directly.</p>\n<p>The getMinMax function is hidden inside the sort function and only called once, you can unwrap it and just embed it's body directly within the sort function.</p>\n<p>But personally, I wouldn't bother with the getMinMax function and just use Math.min and Math.max. That single loop seems like premature optimization.</p>\n<p>The sortArray function does not need to be recursive, it can be a simple loop. In which case it would be called only once and thus could be also unwrapped and it's body embedded directly in the sort function. This would also avoid call stack exceeded problem.</p>\n<p>Pushing to the array is not necessary. You know from the start how many items will be in the output - same as in the input. Resize the array accordingly and keep track of index where to write the next element.</p>\n<p>I don't know if this has any name or if it has been used for something real world.</p>\n<p>So let me just try to describe the complexity of your algorithm.</p>\n<p>Seems that the algorithm is O(n-min+max) in time, so it may theoretically be faster for certain inputs then common sorting methods that usually are between O(n*log(n)) and O(n^2) inclusive. (n - number of input elements, min - minimum value, max - maximum value). Question is for how many elements and how small max-min difference this starts to pay off and whether it's worth it at all. Could be, but you must be working in a context where you know that your inputs are satisfying the criteria that lead to its good performance. Well, at least most of the time.</p>\n<p>The memory complexity is O(n) which is minimum memory complexity for any not in-place sorting method. Although here we need some extra memory for the Set. And of course in your recursive implementation also for all the stack frames.</p>\n<p>PS: your code has some indentation issues. Not sure if this comes from copy pasting but it's always nice to read properly indented code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T18:36:19.533", "Id": "256269", "ParentId": "256264", "Score": "1" } }, { "body": "<h2>Review</h2>\n<h3>Style</h3>\n<ul>\n<li><p>Use <code>const</code> for constant variables. <code>arr</code>, <code>parts</code>, <code>minMax</code> all should be constants.</p>\n</li>\n<li><p>Spaces between operators eg <code>value+1</code> is <code>value + 1</code>, and after commas eg <code>[71,825,522,901</code> should be <code>[71, 825, 522, 901</code></p>\n</li>\n<li><p>JavaScript uses camelCase, avoid using snake_case. <code>to_sort</code> should be <code>toSort</code></p>\n</li>\n<li><p>Naming is inconsistent. You call the array, <code>toSort</code>, and <code>arr</code>. Try and use the same name for the same data.</p>\n</li>\n<li><p>Inconsistent use of semicolons.</p>\n</li>\n</ul>\n<h2>Design</h2>\n<p>Some design changes could be considered.</p>\n<h3>Finding min max</h3>\n<p>The function <code>getMinMax</code> can be simplified by using <code>Math.min</code>, and <code>Math.max</code>, or you can take advantage of the fact that the min and max values will always be different. See rewrites.</p>\n<h3>Exit recursion</h3>\n<p>A very common (what I consider) mistake in recursive algorithms is the placement of the exit clause.</p>\n<p>You have <code>if (value &gt; minMax.max) { return arr; }</code> as first line inside the call. This can be done before the recursion call. See rewrites</p>\n<p>Though a very minor optimization in this case, there are many cases where this can provide significant improvements.</p>\n<h3>Call stack limit</h3>\n<p>Recursion in JS is always a problem as there is a limit to the call stack well below the array size limit. To avoid the call stack overflow it is always better to use the simpler loop. For simple algorithms a loop often provides more performant execution.</p>\n<h3>Consider the known knowns</h3>\n<p>As it is required that all values be unique it is highly probable that the min and max values are already known, this also applies to the array, the same set may need sorting many times. As an optimization you can accept both the hash map and the min and max.</p>\n<p>You could also provide an option to give the common divisor so that a range of values can be sorted eg <code>[0.3, 0.1, 0.2, 0.4]</code> would use the divisor <code>0.1</code></p>\n<h2>Questions</h2>\n<blockquote>\n<p><em>&quot;What sort of algorithm is this (or based on)?&quot;</em></p>\n</blockquote>\n<p>Your sort is not a real sort as it relies on the uniqueness of each item in the array and the items must be numeric (or at least convertible to unique ordered numeric values) with a common divisor (in this case 1)</p>\n<p>Because of this it can sort an array of unique values in <span class=\"math-container\">\\$O(n)\\$</span>, even if you consider arrays with irregular spaced values <span class=\"math-container\">\\$n\\$</span> is scaled by the mean of the differences, such that <code>arr = [0, 2 ** 31 -1]</code> will require <code>2 ** 31 -1</code> steps to sort it is still <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n<p>However your function should only be considered an option if the mean difference is less than <span class=\"math-container\">\\$log(n)\\$</span> if all other conditions are met.</p>\n<p>This sort is a type of <a href=\"https://en.wikipedia.org/wiki/Sorting_algorithm#Non-comparison_sorts\" rel=\"nofollow noreferrer\">Non-comparison sort</a> as the name suggests it does not compare values.</p>\n<blockquote>\n<p><em>&quot;Does this have any performance benefit compared to other algorithms?&quot;</em></p>\n</blockquote>\n<p>Yes, there are many situation that require the sorting of a known set of unique values. If the interval is constant between items it is well worth considering it as a sort option.</p>\n<p>Considering that the min, max, and hash map can be known ahead of time the algorithm can be considered very useful in these circumstances.</p>\n<h2>Rewrites</h2>\n<p>Two alternative min max functions</p>\n<pre><code>function getMinMax(arr) {\n return {\n min: Math.min(...arr),\n max: Math.max(...arr),\n };\n}\n</code></pre>\n<p>Or slightly faster then your original.</p>\n<pre><code>function getMinMax(arr) {\n var min = arr[0], max = min;\n for (const val of arr) { val &lt; min ? min = val : val &gt; max &amp;&amp; (max = val) }\n return { min, max };\n}\n</code></pre>\n<h3>The Sort</h3>\n<p>Adding options for known <code>min</code>, <code>max</code> and hash <code>map</code> the function can be written to avoid the overheads to calculate these values each time. Useful when sorting the same data many times.</p>\n<p><strong>Using recursion</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function sort(arr, min, max, map = new Set(arr)) {\n [min, max] = min === undefined ? minMax(arr) : [min, max];\n return sort(min + 1, [min]);\n function minMax(arr) {\n var min = arr[0], max = min;\n for (const val of arr) { val &lt; min ? min = val : val &gt; max &amp;&amp; (max = val) }\n return [min, max];\n }\n function sort(value, arr) {\n map.has(value) &amp;&amp; arr.push(value);\n return ++value &gt; max ? arr : sort(value, arr);\n }\n}\nconsole.log(sort([6, 0, 1, 9, 3, 4, 5, 2, 7, 8], 0, 9) + \"\");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Using while loop</strong></p>\n<p>This version also adds a divisor optional parameter.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function sort(arr, min, max, divisor = 1, map = new Set(arr)) {\n [min, max] = min === undefined ? getMinMax(arr) : [min, max];\n const res = [min];\n var value = min + divisor;\n while (value &lt;= max) {\n map.has(value) &amp;&amp; res.push(value);\n value += divisor;\n }\n return res;\n\n function getMinMax(arr) {\n var min = arr[0], max = min;\n for (const val of arr) { val &lt; min ? min = val : val &gt; max &amp;&amp; (max = val) }\n return [min, max];\n }\n}\nconsole.log(sort([12, 0, 2, 18, 6, 8, 10, 4, 14, 16], 0, 18, 2) + \"\");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T00:04:28.467", "Id": "256357", "ParentId": "256264", "Score": "2" } }, { "body": "<h2>Name of Algorithm</h2>\n<p>What you had implemented is not a correct sort algorithm (as it cannot handle duplicate items). So there won't be any sort algorithm work like this. The most similar one I can see would be <strong><a href=\"https://en.wikipedia.org/wiki/Counting_sort\" rel=\"nofollow noreferrer\">Counting sort</a></strong>. Counting sort also track how many occurrence of each integer in the array so it would work with duplicate values.</p>\n<h2>Time complexity</h2>\n<p>Time complexity of your program is <span class=\"math-container\">\\$O\\left(max-min+size\\right)\\$</span>. As this algorithm is not a compare based sorting algorithm, the lower bound of time complexity <span class=\"math-container\">\\$\\Omega\\left(size\\cdot\\log size\\right)\\$</span> for compare based algorithms not applied here. It would work better than compare based algorithms (quick sort for example) when given input only contains a small range of integers.</p>\n<h2>Implementation</h2>\n<p>The hash set is not required by getting <span class=\"math-container\">\\$min\\$</span> / <span class=\"math-container\">\\$max\\$</span>. A simple loop on input array would work. And your loop may iterate over the given array, not from <span class=\"math-container\">\\$min\\$</span> to <span class=\"math-container\">\\$max\\$</span>. You may find a lot of implementations if you search &quot;Counting sort&quot;. So, I believe, I don't need to add another one myself here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T07:25:17.160", "Id": "256365", "ParentId": "256264", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T16:04:42.093", "Id": "256264", "Score": "2", "Tags": [ "javascript", "performance", "algorithm", "comparative-review", "set" ], "Title": "Sort an array of integers with a hashset" }
256264
<pre><code>def T(n): if n &lt;= 0: return 1 else: return T(n-1) + (n-1) * T(n-2) print T(4) </code></pre> <p>I need an effective way to print out the output of the function <code>T(n)</code> generated using the recurrence relation above. Is there any way to make the above code more efficient?</p> <p>Sample output:</p> <pre><code>10 </code></pre>
[]
[ { "body": "<p>You should use an <a href=\"https://codereview.stackexchange.com/a/231410\"><code>if &quot;__name__&quot; == __main__:</code></a> guard.</p>\n<p>From Python 3.2 you can use <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"noreferrer\"><code>functools.lru_cache</code></a> and from Python 3.9 you can use <a href=\"https://docs.python.org/3/library/functools.html#functools.cache\" rel=\"noreferrer\"><code>functools.cache</code></a> to memoize the function calls, to only call <code>T</code> <span class=\"math-container\">\\$O(n)\\$</span> times. Which is a fancy name for caching the input and output of the function. The way this works is by wrapping a function. Each time the decorated function is called we compare the arguments to the keys in a cache:</p>\n<ul>\n<li>if there is a match we return the value, and</li>\n<li>if there is no match we call the function to get the return value. Store the returned value in the cache and return the returned value to the caller.</li>\n</ul>\n<p>Since you're using Python 2, we can make this function ourselves. We can use a closure to build a decorator function to hold the cache.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def cache(fn):\n def inner(*args):\n try:\n return CACHE[args]\n except KeyError:\n pass\n CACHE[args] = value = fn(*args)\n return value\n CACHE = {}\n return inner\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>@cache\ndef T(n):\n if n &lt;= 0:\n return 1\n else:\n return T(n-1) + (n-1) * T(n-2)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T17:30:34.730", "Id": "505885", "Score": "0", "body": "Thanks for the answer! But I was wondering if you had something for Python 2.7... I wanted the solution to make use of only one recursive invocation of the function T. (The current one invokes the function T twice.) I'm looking for something simple and easy to understand..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T17:32:29.827", "Id": "505886", "Score": "1", "body": "@Justin My answer above does have something for Python 2.7. Please read the part that says \"Since you're using Python 2\". Asking to change code from calling a function twice to only once is not part of what Code Review is about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T17:35:02.263", "Id": "505887", "Score": "0", "body": "Ah yes, the rest of the answer just loaded for me. I guess this works, but I would like the code to be shorter. I do not understand some of the complicated functions that Python has to offer and I was hoping for something simple and efficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T17:36:56.163", "Id": "505888", "Score": "0", "body": "Also, isn't changing code from calling a function twice to only once making the code more efficient? I didn't know how to do that, so I asked it here. Is there anywhere else I could ask?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T17:41:02.110", "Id": "505891", "Score": "0", "body": "@Justin There is a difference between \"how can I make my code more efficient\" and \"how can I do this in Python\". Code Review is about the former question where you are asking the latter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T17:45:30.287", "Id": "505892", "Score": "0", "body": "But... I'm clearly asking for my code to be made more efficient... I just didn't want a complicated response." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:09:03.110", "Id": "505895", "Score": "0", "body": "@Justin You're asking for the code to be short, effectiveness has nothing to do with length." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:23:20.207", "Id": "505902", "Score": "1", "body": "By short, I meant concise... sorry!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T17:22:45.387", "Id": "256268", "ParentId": "256267", "Score": "6" } }, { "body": "<p>If you cannot use <code>functools.cache</code> or <code>functools.lru_cache</code> and if\nyou don't understand or want to use a decorator, as shown in another\nanswer, here a low-tech approach to <a href=\"https://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">memoization</a>. Please note\nthat the <code>functools</code> approach is easier, more robust, etc. But\nif you are not worried about all of that and just want simple code\nthat is radically faster than your current approach, this will work.</p>\n<pre><code>def T(n):\n if n not in T.cache:\n if n &lt;= 0:\n T.cache[n] = 1\n else:\n T.cache[n] = T(n-1) + (n-1) * T(n-2)\n return T.cache[n]\n\n# Initialize the cache.\nT.cache = {}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:14:56.630", "Id": "505896", "Score": "3", "body": "If you change `T.cache = {0: 1}` you can get rid of the if :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:19:56.337", "Id": "505897", "Score": "3", "body": "@Peilonrayz Hah, good idea, although I think at least `{0: 1, -1: 1}` is needed. And I don't know whether the function should gracefully handle negative integers, so I'll leave those optimizations to the OP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:21:47.407", "Id": "505898", "Score": "0", "body": "Is there a way to time the code and check how fast each code gives an output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:22:03.620", "Id": "505899", "Score": "0", "body": "@Justin Yes, it's called profiling." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:22:05.607", "Id": "505900", "Score": "0", "body": "Oops, yeah I made a mistake there!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:22:59.573", "Id": "505901", "Score": "0", "body": "@Mast - Okay, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:38:53.810", "Id": "505903", "Score": "0", "body": "Is there any documentation on `.cache` that I could have a look at?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:43:52.993", "Id": "505904", "Score": "1", "body": "@Justin Probably, but not specifically. Most things in Python, including functions, are objects. Objects can have attributes. We are just giving the `T` function an attribute called `cache`, and it's a `dict` that we intend to use for memoization. Regarding timing/profiling, there are many ways to do that, including using Python profiling libraries. But if you want simple, you can just do it \"manually\" with the `time` library: `t0 = time.time() ; DO SOMETHING ; t1 = time.time() ; print(t1 - t0)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:45:01.010", "Id": "505905", "Score": "0", "body": "@FMc Alright, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T21:08:36.463", "Id": "506307", "Score": "0", "body": "So I used the profiling method that you mentioned, and apparently, your program takes more time to execute than mine... Not sure if I was doing it right, but could you look into it? (I got `4.76837158203125e-06` for yours and `4.76837158203125e-07` for mine if that helps)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T22:20:48.687", "Id": "506316", "Score": "1", "body": "@Justin Need more specifics to make those times meaningful: what did you measure? For example, your function will indeed be faster for low values of `n`, because it does not incur any caching costs. The big differences emerge for larger values of `n`; that's when the caching approach yields big benefits because the code doesn't have to repeatedly compute a result for an input it has already seen before." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T22:26:03.453", "Id": "506317", "Score": "0", "body": "@FMc - Yes, you're completely right. The program seems to work faster for larger values of `n`. I tested both programs using smaller values of `n`. Thanks for clarifying! (Btw, I tested using `n=25`, I got 5e-05 for yours, and 0.046 seconds for mine, so it works faster for larger values of `n`, as you mentioned.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-27T04:19:44.707", "Id": "506423", "Score": "0", "body": "Also, can `n == 0 or n == 1`? Like the only difference would be that inputting negative values would result in an error, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-27T15:59:26.443", "Id": "506445", "Score": "1", "body": "@Justin Yes, if I understand you correctly. If you aren't worried about the function handling negative numbers gracefully, you can just initialize the cache as `{0: 1, -1: 1}` and then drop the `if-else` structure entirely, as noted in the comments above." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T19:11:35.277", "Id": "256271", "ParentId": "256267", "Score": "8" } }, { "body": "<p>One more option is to not recurse at all, but to instead compute the sequence until we get the desired term. This not only avoids the original algorithm's exponential complexity; it also avoids the at least linear (in terms of counting values) memory complexity of memoization. (Recursion/memoization can also run into implementation-specific issues such as recursion depth errors or memory errors, which are not a concern with the code below.)</p>\n<pre><code>def T(n):\n if n&lt;=0: return 1\n # Set a, b to T(-1), T(0)\n a, b = 1, 1\n for i in range(n):\n # Change a, b from T(i-1), T(i) to T(i), T(i+1)\n a, b = b, b+i*a\n # i=n-1 set b to T(n)\n return b\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T22:42:53.627", "Id": "256279", "ParentId": "256267", "Score": "10" } } ]
{ "AcceptedAnswerId": "256271", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T16:53:58.980", "Id": "256267", "Score": "3", "Tags": [ "python", "performance", "python-2.x" ], "Title": "Bifurcating recursive calculation with redundant calculations" }
256267
<p>ApplicationDetail.txt:</p> <pre><code>URL: https://www.abc.com applicationNo : 123456 </code></pre> <p>Application Class:</p> <pre><code>from dataclasses import dataclass @dataclass class Application(object): &quot;&quot;&quot; Binding Json Data to this Class &quot;&quot;&quot; Status: str ApplicationType: str StatusDate: str Location: str LocationDate: str ConfirmationNumber: int FirstNamedApplicant: str EntityStatus: str </code></pre> <p>Code:</p> <pre><code>from selenium import webdriver import json from selenium.webdriver.common.by import By import logging import traceback from Application import Application # importing Application Class def PrintObj(applicationObject): &quot;&quot;&quot;This Function Will Print Object Binded to Application Class&quot;&quot;&quot; try: print(' ***************** After Deserialize *****************') print('Status: %s' % applicationObject.Status) print('ApplicationType: %s' % applicationObject.ApplicationType) print('StatusDate: %s' % applicationObject.StatusDate) print('Location: %s' % applicationObject.Location) print('LocationDate: %s' % applicationObject.LocationDate) print('ConfirmationNumber:', applicationObject.ConfirmationNumber) print('FirstNamedApplicant: %s' % applicationObject.FirstNamedApplicant) print('EntityStatus: %s' % applicationObject.EntityStatus) print('---------------------------------------------------') except AttributeError as ex: print(ex) logging.error(ex, exc_info=True) except: print('ERROR Occurred in PrintObj Method') logging.error('ERROR Occurred in PrintObj Method', exc_info=True) def ApplicationDetail(path, mode): &quot;&quot;&quot;This Function Will Fetch ApplicationDetail from .txt File in given path&quot;&quot;&quot; try: logging.info('Opening ApplicationDetail File') with open(path, mode) as file: # Opening ApplicationDetail File webSiteURL = file.readline().replace('URL : ', '').replace('\n', '') application_no = file.readline().replace('applicationNo : ', '').replace('\n', '') file.close() # closed ApplicationDetail File logging.info('closed ApplicationDetail File') return webSiteURL, application_no except FileNotFoundError as ex: print(ex) logging.critical(ex, exc_info=True) except: print('Something ERROR Occurred in ApplicationDetail Method') logging.critical('Something ERROR Occurred in ApplicationDetail Method', exc_info=True) def JsonStringSerialize(recordDictionary): &quot;&quot;&quot;This Function Will Convert Formal Parameter(recordDictionary) to json_string and Write in .json File&quot;&quot;&quot; try: jsonString = json.dumps(recordDictionary, indent=4) # serilazing recordDictionary logging.info('Serialzing Done') with open('ApplicationData.json', 'w') as f_Out: logging.info('Writing in .json File') f_Out.write(jsonString) # writing in .json file logging.info('Writing completed in .json File') f_Out.close() # closing .json File except json.encoder.JSONEncoder: print('Cannot Serializable') logging.error('Cannot Serializable', exc_info=True) except: print('Serialization Failed') logging.error('Serialization Failed', exc_info=True) def DeserializeJson(): &quot;&quot;&quot;This Function Will Fetch JSON from .json File, Deserialize and Bind to Application Class&quot;&quot;&quot; try: with open('ApplicationData.json', 'r') as f_Out: jsonString = json.load(f_Out) # Deserializing Json Data logging.info('Deserialzing Done') return Application(**jsonString) # Binding to Application Class except json.decoder.JSONDecodeError: print('Cannot Deserializable') logging.error('Cannot Deserializable', exc_info=True) except: print('Deserialization Failed') logging.error('Deserialization Failed', exc_info=True) def ScrapData(URL, applicationNo, xpath, elementID, xpath2): &quot;&quot;&quot;This Function will scrap data from given URL&quot;&quot;&quot; try: webBrowser = webdriver.Ie(r'C:\Users\XYZ\WebDriver\IEDriverServer.exe') webBrowser.get(URL) webBrowser.implicitly_wait(15) webBrowser.find_element_by_xpath(xpath).send_keys(applicationNo) # webBrowser.find_elements_by_class_name('saeRow').text webBrowser.find_element_by_id(elementID).click() logging.info('Scraping Started') applicationData = [td.text for td in webBrowser.find_elements_by_xpath(xpath2)] logging.info('Scraping Completed') return {'Status': applicationData[0], 'ApplicationType': applicationData[1], 'StatusDate': applicationData[2], 'Location': applicationData[3], 'LocationDate': applicationData[4], 'ConfirmationNumber': applicationData[5], 'FirstNamedApplicant': applicationData[6], 'EntityStatus': applicationData[7]} except: print('Something Error Occurred in ScrapData Method') logging.critical('Something Error Occurred in ScrapData Method', exc_info=True) finally: webBrowser.__exit__() if __name__ == '__main__': try: logging.basicConfig(format='%(levelname)s - %(asctime)s - %(message)s', datefmt='%Y-%m-%d %I:%M:%S %p', filename='Log_File.log', level=logging.DEBUG) logging.info('Task Started') webSiteURL, applicationNo = ApplicationDetail('ApplicationDetails.txt', 'r') JsonStringSerialize(ScrapData(webSiteURL, applicationNo, '//input[@id=&quot;id&quot;]', &quot;Submit&quot;, '//td')) if input(' U Want to Deserialize y || n\n') == 'y': PrintObj(DeserializeJson()) except TypeError as ex: print(ex) logging.critical(ex, exc_info=True) except NameError as ex: print(ex) logging.critical(ex, exc_info=True) except ModuleNotFoundError as ex: print(ex) #traceback.print_exc() logging.critical(ex, exc_info=True) except: print('Something Error Occurred in Main Method') logging.critical('Something Error Occurred in Main Method') finally: logging.info('Task Completed') </code></pre> <p>The above project will scrap data from the website using selenium in python Any suggestion/review of the above code will be helpful?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T18:43:10.647", "Id": "256270", "Score": "2", "Tags": [ "python-3.x", "web-scraping", "selenium" ], "Title": "Web Scraping data from website using Selenium in python" }
256270
<p>I'm a C noob and I'm learning about concurrency using C. I came across an exercise in a <a href="https://rads.stackoverflow.com/amzn/click/com/B00EKZ123U" rel="noreferrer" rel="nofollow noreferrer">book</a> asking me to find the approximate value of Pi using the Monte Carlo technique with OpenMP. I came up with the following:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;pthread.h&gt; #include &lt;math.h&gt; #include &lt;omp.h&gt; int in_circle = 0; int total = 10000; int thread_numb = 4; void calculate_in_circle_random_count() { srand((unsigned int)time(NULL)); for (int i = 0; i &lt; total / thread_numb; i++) { float x = (float)rand()/(float)(RAND_MAX); float y = (float)rand()/(float)(RAND_MAX); float val = (x * x) + (y * y); if (val &lt; 1.0) { #pragma omp critical { in_circle++; } } } } int main(int argc, char const *argv[]) { #pragma omp parallel num_threads(thread_numb) { printf(&quot;Hello from process: %d\n&quot;, omp_get_thread_num()); calculate_in_circle_random_count(); } float pi_approx = 4 * (float)in_circle / (float)total; printf(&quot;In circle: %d\n&quot;, in_circle); printf(&quot;Total: %d\n&quot;, total); printf(&quot;Pi approximation: %.6f\n&quot;, pi_approx); return 0; } </code></pre> <p>I have the sample count of 10000 to calculate approximation and I want to dedicate 4 threads to be parallel for the calculation. So since I want 4 threads, I make sure the for loop is run until <code>total / 4</code> for each thread. And whenever <code>(val &lt; 1.0)</code> is <code>true</code> I increase the <code>in_circle</code> variable in a critical section.</p> <p>Does this approach make sense? If not, how could it be improved?</p>
[]
[ { "body": "<p>I think you're over-complicating this. You can let OpenMP divide the work between the threads for you, using <code>#pragma openmp parallel for</code>.</p>\n<p>You can use a reduction for <code>in_circle</code> instead of a critical section - that allows OpenMP to sum into a per-thread variable, and add them all at the end, reducing contention for the variable.</p>\n<p>Here's a simpler version (I've removed the unused includes, too, and made the function declaration a prototype):</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\ndouble calculate_in_circle_random_count(void)\n{\n static const unsigned total = 1000000;\n unsigned in_circle = 0;\n\n#pragma omp parallel for reduction(+:in_circle)\n for (unsigned i = 0; i &lt; total; ++i) {\n double x = (double)rand() / RAND_MAX;\n double y = (double)rand() / RAND_MAX;\n\n double val = x * x + y * y;\n in_circle += val &lt; 1.0;\n }\n\n return 4.0 * in_circle / total;\n}\n\nint main(void)\n{\n const double pi_approx = calculate_in_circle_random_count();\n printf(&quot;Pi approximation: %.6f\\n&quot;, pi_approx);\n}\n</code></pre>\n<p>Note that at this scale, the parallelisation overheads dominate, making the parallel version much slower than the serial. With more iterations, you'll get closer, but there's so little in the loop that the benefits are small.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T07:04:38.990", "Id": "505927", "Score": "0", "body": "I see this version is much simpler! One question though, I see you removed `srand((unsigned int)time(NULL));` I thought that was needed to properly seed the random number generation. Is it not only needed but would also harm the performance of the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T08:34:04.940", "Id": "505940", "Score": "1", "body": "Do you really need a different result every time? If so, then it's appropriate to call `srand()`, but here it seems that starting with the generator in its default state is adequate. BTW, I didn't check whether `rand()` generates distinct values in each thread, so you may find that all the threads are working with the same inputs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T08:36:28.090", "Id": "505941", "Score": "2", "body": "Worse that that, I have actually checked and discovered `rand()` is not even thread-safe, so calling it concurrently could actually corrupt its state. You'll need to find a thread-safe generator, such as POSIX `rand_r()` or its successor `erand48()` (which conveniently yields values between 0.0 and 1.0)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T08:41:16.250", "Id": "506032", "Score": "1", "body": "There are random number generators which are explicitly designed for use in parallel environments (and are available in many math libraries). Read \"Parallel Random Numbers: As Easy as 1, 2, 3 - The Salmons\", fhttp://www.thesalmons.org/john/random123/papers/random123sc11.pdf for instance. Merely initialising each thread's generator with a random seed is could still lead to sampling the same sequence in multiple threads if you are unlucky..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T21:03:43.143", "Id": "256275", "ParentId": "256274", "Score": "4" } }, { "body": "<p>This code has a serious problem due to (at least the typical implementation of) <code>rand()</code>. <code>rand()</code> normally has a (hidden) seed value, and each call to <code>rand()</code> modifies the seed. At least in most implementations, that means <code>rand</code> always forces serialization.\nThat means, calling <code>rand()</code> (a couple of times) in your inner loop will prevent code from scaling well at all. In fact, in most cases (as Toby Speight showed) a multi-threaded version will run substantially <em>slower</em> than a single-threaded version.</p>\n<p>To fix this, you pretty much need to use some other random number generator. Your implementation may provide one (e.g., <code>erand48</code> is fairly common). If you really need your code to be portable, you could write your own, something on this order:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;time.h&gt;\n\ntypedef unsigned long long rand_state;\n\n// multiplier/modulus taken from Knuth Volume 2, Table 1\nstatic const int multiplier = 314159269;\nstatic const int addend = 1;\nstatic const int modulus = 0xffffffff;\n\n// note that this works differently from srand, returning a seed rather than setting\n// a hidden seed.\nrand_state omp_srand() {\n rand_state state = time(NULL);\n state ^= (unsigned long long)omp_get_thread_num() &lt;&lt; 32;\n return state;\n}\n\nint omp_rand(rand_state *state) {\n *state = *state * multiplier + addend;\n return *state &amp; modulus;\n}\n</code></pre>\n<p>Note that since it's entirely likely that all the threads get started in the same second, this combines the current time with the thread ID to seed each thread's generator. Although it's not 100% guaranteed, this gives a pretty high likelihood that each thread's generator will start with a unique seed. On the other hand, it also means that we have to start the thread, and then seed the generator inside that thread.</p>\n<p>To use this, our code would be something on this general order:</p>\n<pre class=\"lang-c prettyprint-override\"><code>double calculate_in_circle_random_count(void) {\n\n static const unsigned total = 1000000000;\n unsigned in_circle = 0;\n\n#pragma omp parallel reduction(+:in_circle)\n {\n // do per-thread initialization\n rand_state seed = omp_srand();\n int count = total / omp_get_num_threads();\n int i;\n\n // then do this thread's portion of the computation:\n for (i = 0; i &lt; count; ++i) {\n\n double x = (double)omp_rand(&amp;seed) / OMP_RAND_MAX;\n double y = (double)omp_rand(&amp;seed) / OMP_RAND_MAX;\n\n double val = x * x + y * y;\n in_circle += val &lt; 1.0;\n }\n }\n return 4.0 * in_circle / total;\n}\n\nint main(int argc, char const *argv[])\n{\n int num_threads = 1;\n\n if (argc &gt; 1) \n num_threads = atoi(argv[1]);\n\n omp_set_num_threads(num_threads);\n\n float pi_approx = calculate_in_circle_random_count();\n\n printf(&quot;Pi approximation: %.6f\\n&quot;, pi_approx);\n\n return 0;\n}\n</code></pre>\n<p>With this modification, the code is at least <em>capable</em> of scaling. To get it to scale very well, you'd need to change your <code>total</code> to a rather larger number though--with it as small as you've specified, it takes longer to start up multiple threads than it saves in calculation. But at least this code <em>can</em> scale well, so if we make <code>total</code> quite a bit larger, it really will run faster. For timing, I added a few more zeros to <code>total</code>, and rewrote <code>main</code> a bit, to create a loop to use 1, 2, 3, and 4 threads and print out the time each iteration. On my machine, this produced the following:</p>\n<pre><code>With 1 threads: Pi approximation: 3.140259, time: 3,652,683 microseconds\nWith 2 threads: Pi approximation: 3.139389, time: 1,892,415 microseconds\nWith 3 threads: Pi approximation: 3.138885, time: 1,268,917 microseconds\nWith 4 threads: Pi approximation: 3.138306, time: 935,579 microseconds\n</code></pre>\n<p>So with this, 4 threads is at least close to 4 times as fast as one thread. I'm pretty sure if you use <code>rand</code> inside the loop, you'll never get it to scale well at all.</p>\n<p>For anybody who cares, the version of main that produces that output is written in C++, and looks like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int main(int argc, char const* argv[]) {\n using namespace std::chrono;\n\n std::cout.imbue(std::locale(&quot;&quot;));\n\n int processors = omp_get_num_procs();\n\n for (int num_threads = 1; num_threads &lt;= processors; num_threads++) {\n std::cout &lt;&lt; &quot;With &quot; &lt;&lt; std::setw(2) &lt;&lt; num_threads &lt;&lt; &quot; threads: &quot;;\n omp_set_num_threads(num_threads);\n\n auto start = high_resolution_clock::now();\n float pi_approx = calculate_in_circle_random_count();\n auto stop = high_resolution_clock::now();\n\n printf(&quot; %.6f, time: &quot;, pi_approx);\n std::cout &lt;&lt; std::setw(9) &lt;&lt; duration_cast&lt;microseconds&gt;(stop - start).count() &lt;&lt; &quot; microseconds\\n&quot;;\n }\n return 0;\n}\n</code></pre>\n<p>This remains pretty much the same, but with some timing code hacked in. In particular, it's <em>not</em> an attempt at rewriting the code in C++ in general. If I were doing that, I'd probably do a number of things rather differently (starting with the fact that the C++ <code>&lt;random&gt;</code> header already provides a clean way to handle per-thread random number generation, so I'd use that instead of rolling my own).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T03:47:52.727", "Id": "505923", "Score": "0", "body": "Won't this end up with all threads using the same random number seed, because `seed` is initialized via `omp_srand()` before the OMP loop is entered, so that initial value will be copied to all the threads?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T07:07:54.677", "Id": "505928", "Score": "0", "body": "This is very informative! Would you mind sharing the benchmarking code where you got the time comparisons? I would like to compare how using rand() affects performance locally." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T07:09:32.860", "Id": "505929", "Score": "1", "body": "@emrepun: I don't mind sharing it, but (at least right now) it's written in C++, because it uses the C++ chrono library for timing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T07:12:34.483", "Id": "505930", "Score": "0", "body": "I would still like to see it which would be another exercise for me to see the C++ version of it :) @JerryCoffin" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T07:14:07.510", "Id": "505931", "Score": "0", "body": "@emrepun: I didn't rewrite the rest of the code at all, just added a bit of timing code, which happens to use a library written in C++." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T07:15:48.977", "Id": "505932", "Score": "0", "body": "I see, I will have a look at the chrono library then. @JerryCoffin" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T07:26:27.910", "Id": "505934", "Score": "1", "body": "@emrepun: For what it's worth, I believe OpenMP provides a timing function as well. Oh, and I've edited the version of `main` with the chrono-based timing code into the answer above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T07:30:36.103", "Id": "505935", "Score": "0", "body": "@1201ProgramAlarm: Oops, yes it did. I believe I've corrected that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T07:31:02.703", "Id": "505936", "Score": "0", "body": "Thanks! One last thing, was `OMP_RAND_MAX` not included in the code snippet. I see it does not come from <omp.h> @JerryCoffin" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T07:32:53.887", "Id": "505937", "Score": "1", "body": "@emrepun: oops--a copy and paste error on my part. It should be: `#define OMP_RAND_MAX 0xffffffff`. Just to be clear: it's something I made up for the `omp_rand`/`omp_srand` I wrote for this, not something defined by OpenMP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T08:53:56.763", "Id": "505947", "Score": "0", "body": "Me again, I cannot get this to work, pi approximation yields to 4 all the time. Maybe it is because of the way I compile the executable? I run this command (file name is openmp_approximate_pi.c): \n\n`clang -Xpreprocessor -fopenmp openmp_approximate_pi.c -lomp`\n\n@JerryCoffin\n\nAny thoughts on this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T16:22:52.163", "Id": "505977", "Score": "0", "body": "@emrepun: It's my fault. As I was writing this, I decided to switch `omp_rand` from producing signed to unsigned results, and looking at things, some of what I've posted is for one, and some for the other. If it's going to produce signed, its return type needs to be `int` and `OMP_RAND_MAX` and `modulus` should both be `0x7fffffff`. For unsigned, its return needs to be `unsigned` and `modulus` and `OMP_RAND_MAX` both need to be `0xffffffff`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T19:55:10.933", "Id": "505993", "Score": "0", "body": "I submitted an edit for signed. @JerryCoffin" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T07:59:32.160", "Id": "506025", "Score": "0", "body": "(@emrepun: If I didn't check these comments, I would have rejected your edit for not following Knuth's for a supposed *word size* of 32: suggest following the post comments in an edit comment where useful.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T08:06:38.707", "Id": "506027", "Score": "0", "body": "Makes sense @greybeard I should have provided more context in my edit proposal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T07:19:38.720", "Id": "506194", "Score": "0", "body": "Well although this is the accepted answer, it is not working as it is, and if someone else in the future uses the code provided, she won't be able to get it to work unless she goes through the comments. Would you mind editing your answer? @JerryCoffin" } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T01:00:49.280", "Id": "256282", "ParentId": "256274", "Score": "5" } } ]
{ "AcceptedAnswerId": "256282", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T20:14:49.823", "Id": "256274", "Score": "5", "Tags": [ "c", "multithreading", "openmp" ], "Title": "Calculating pi with Monte Carlo using OpenMP" }
256274
<p>For an (completely optional) assignment for an introductory course to programming with C++, I am trying to implement a diagonal matrix-vector multiplication (<code>?diamv</code>) kernel, i.e. mathematically <span class="math-container">$$\mathbf{y} \leftarrow \alpha\mathbf{y} + \beta \mathbf{M}\mathbf{x}$$</span> for a diagonally clustered matrix <span class="math-container">\$\mathbf{M}\$</span>, dense vectors <span class="math-container">\$\mathbf{x}\$</span> and <span class="math-container">\$\mathbf{y}\$</span>, and scalars <span class="math-container">\$\alpha\$</span> and <span class="math-container">\$\beta\$</span>. I believe that I can reasonably motivate the following assumptions:</p> <ol> <li>The processors executing the compute threads are capable of executing the SSE4.2 instruction set extension (but not necessarily AVX2),</li> <li>The access scheme of the matrix <span class="math-container">\$\mathbf{M}\$</span> does not affect the computation and therefore temporal cache locality between kernel calls does not need to be considered,</li> <li>The matrix <span class="math-container">\$\mathbf{M}\$</span> does not fit in cache, is very diagonally clustered with a diagonal pattern that is known at compile time, and square,</li> <li>The matrix <span class="math-container">\$\mathbf{M}\$</span> does not contain regularly occurring sequences in its diagonals that would allow for compression along an axis,</li> <li>No reordering function exists for the structure of the matrix <span class="math-container">\$\mathbf{M}\$</span> that would lead to a cache-oblivious product with a lower cost than an ideal multilevel-memory optimized algorithm,</li> <li>The source data is aligned on an adequate boundary,</li> <li>OpenMP, chosen for its popularity, is available to enable shared-memory parallelism. No distributed memory parallelism is necessary as it is assumed that a domain decomposition algorithm, e.g. DP-FETI, will decompose processing to the node level due to the typical problem size.</li> </ol> <p>Having done a literature review, I have come to the following conclusions on its design and implementation (this is a summary, in increasing granularity, with the extensive literature review being available upon request to save space):</p> <ol> <li>&quot;In order to achieve high performance, a parallel implementation of a sparse matrix-vector multiplication must maintain scalability&quot; per White and Sadayappan, 1997.</li> <li>The diagonal matrix storage scheme, <span class="math-container">$$\DeclareMathOperator{\vec}{vec}\DeclareMathOperator{\val}{val} \vec\left(\val{(i,j)}\equiv a_{i,i+j}\right)$$</span> where <span class="math-container">\$\vec\$</span> is the matrix vectorization operator, which obtains a vector by stacking the columns of the operand matrix on top of one another. By storing the matrix in this format, I believe the cache locality to be as optimal as possible to allow for row-wise parallelization. Checkerboard partitioning reduces to row-wise for diagonal matrices. Furthermore, this allows for source vector re-use, which is necessary unless the matrix is re-used while still in cache (Frison 2016).</li> <li>I believe that the aforementioned should <em>always</em> hold, before vectorization is even considered? The non-regular padded areas of the matrix, i.e. the top-left and bottom-right, can be handled separately without incurring extra cost in the asymptotic sense (because the matrix is diagonally clustered and very large).</li> <li>Because access to this matrix is linear, software prefetching should not be necessary. I have included it anyways, for code review, at the spot which I considered the most logical.</li> </ol> <p>The following snippet represents my best effort, taking the aforementioned into consideration:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;stdint.h&gt; #include &lt;type_traits&gt; #include &lt;xmmintrin.h&gt; #include &lt;emmintrin.h&gt; #include &lt;omp.h&gt; #include &quot;tensors.hpp&quot; #define CEIL_INT_DIV(num, denom) 1 + ((denom - 1) / num) #if defined(__INTEL_COMPILER) #define AGNOSTIC_UNROLL(N) unroll (N) #elif defined(__CLANG__) #define AGNOSTIC_UNROLL(N) clang loop unroll_count(N) #elif defined(__GNUG__) #define AGNOSTIC_UNROLL(N) unroll N #else #warning &quot;Compiler not supported&quot; #endif /* Computer-specific optimization parameters */ #define PREFETCH true #define OMP_SIZE 16 #define BLK_I 8 #define SSE_REG_SIZE 128 #define SSE_ALIGNMENT 16 #define SSE_UNROLL_COEF 3 namespace ranges = std::ranges; /* Calculate the largest absolute value ..., TODO more elegant? */ template &lt;typename T1, typename T2&gt; auto static inline largest_abs_val(T1 x, T2 y) { return std::abs(x) &gt; std::abs(y) ? std::abs(x) : std::abs(y); } /* Define intrinsics agnostically; compiler errors thrown automatically */ namespace mm { /* _mm_load_px - [...] */ inline auto load_px(float const *__p) { return _mm_load_ps(__p); }; inline auto load_px(double const *__dp) { return _mm_load_pd(__dp); }; /* _mm_store_px - [...] */ inline auto store_px(float *__p, __m128 __a) { return _mm_store_ps(__p, __a); }; inline auto store_px(double *__dp, __m128d __a) { return _mm_store_pd(__dp, __a); }; /* _mm_set1_px - [...] */ inline auto set_px1(float __w) { return _mm_set1_ps(__w);}; inline auto set_px1(double __w) { return _mm_set1_pd(__w); }; /* _mm_mul_px - [...] */ inline auto mul_px(__m128 __a, __m128 __b) { return _mm_mul_ps(__a, __b);}; inline auto mul_px(__m128d __a, __m128d __b) { return _mm_mul_pd(__a, __b); }; } namespace tensors { template &lt;typename T1, typename T2&gt; int diamv(matrix&lt;T1&gt; const &amp;M, vector&lt;T1&gt; const &amp;x, vector&lt;T1&gt; &amp;y, vector&lt;T2&gt; const &amp;d, T1 alpha, T1 beta) noexcept { /* Initializations */ /* - Compute the size of an SSE vector */ constexpr size_t sse_size = SSE_REG_SIZE / (8*sizeof(T1)); /* - Validation of arguments */ static_assert((BLK_I &gt;= sse_size &amp;&amp; BLK_I % sse_size == 0), &quot;Cache blocking is invalid&quot;); /* - Reinterpretation of the data as aligned */ auto M_ = reinterpret_cast&lt;T1 *&gt;(__builtin_assume_aligned(M.data(), SSE_ALIGNMENT)); auto x_ = reinterpret_cast&lt;T1 *&gt;(__builtin_assume_aligned(x.data(), SSE_ALIGNMENT)); auto y_ = reinterpret_cast&lt;T1 *&gt;(__builtin_assume_aligned(y.data(), SSE_ALIGNMENT)); auto d_ = reinterpret_cast&lt;T2 *&gt;(__builtin_assume_aligned(d.data(), SSE_ALIGNMENT)); /* - Number of diagonals */ auto n_diags = d.size(); /* - Number of zeroes for padding TODO more elegant? */ auto n_padding_zeroes = largest_abs_val(ranges::min(d), ranges::max(d)); /* - No. of rows lower padding needs to be extended with */ auto n_padding_ext = (y.size() - 2*n_padding_zeroes) % sse_size; /* - Broadcast α and β into vectors outside of the kernel loop */ auto alpha_ = mm::set_px1(alpha); auto beta_ = mm::set_px1(beta); /* Compute y := αy + βMx in two steps */ /* - Pre-compute the bounding areas of the two non-vectorizable and single vect. areas */ size_t conds_begin[] = {0, M.size() - (n_padding_ext+n_padding_zeroes)*n_diags}; size_t conds_end[] = {n_padding_zeroes*n_diags, M.size()}; /* - Non-vectorizable areas (top-left and bottom-right resp.) */ #pragma AGNOSTIC_UNROLL(2) for (size_t NONVEC_LOOP=0; NONVEC_LOOP&lt;2; NONVEC_LOOP++) { for (size_t index_M=conds_begin[NONVEC_LOOP]; index_M&lt;conds_end[NONVEC_LOOP]; index_M++) { auto index_y = index_M / n_diags; auto index_x = d[index_M % n_diags] + index_y; if (index_x &gt;= 0) y_[index_y] = (alpha * y_[index_y]) + (beta * M_[index_M] * x_[index_x]); } } /* - Vectorized area - (parallel) iteration over the x parallelization blocks */ #pragma omp parallel for shared (M_, x_, y_) schedule(static) for (size_t j_blk=conds_end[0]+1; j_blk&lt;conds_begin[1]; j_blk+=BLK_I*n_diags) { /* Iteration over the x cache blocks */ for (size_t j_bare = 0; j_bare &lt; CEIL_INT_DIV(sse_size, BLK_I); j_bare++) { size_t j = j_blk + (j_bare*n_diags*sse_size); /* Perform y = ... for this block, potentially with unrolling */ /* *** microkernel goes here *** */ #if PREFETCH /* __mm_prefetch() */ #endif } } return 0; }; } </code></pre> <p>Some important notes:</p> <ol> <li><p><code>tensors.hpp</code> is a simple header-only library that I've written for the occasion to act as a uniform abstraction layer to tensors of various orders (with the CRTP) having different storage schemes. It also contains aliases to e.g. vectors and dense matrices.</p> </li> <li><p>For the microkernel, I believe there to be two possibilities</p> <p>a. Iterate linearly over the vectorized matrix within each cache block; this would amount to row-wise iteration over the matrix <span class="math-container">\$\mathbf{M}\$</span> within each cache block and therefore a dot product. To the best of my knowledge, dot products are inefficient in dense matrix-vector products due to both data dependencies and how the intrinsics decompose into μops.</p> <p>b. Iterate over rows in cache blocks in the vectorized matrix, amounting to iteration over diagonals in the matrix <span class="math-container">\$\mathbf{M}\$</span> within each cache block. Because of the way the matrix <span class="math-container">\$\mathbf{M}\$</span> is stored, i.e. in its vectorized form, this would incur the cost of broadcasting the floating-point numbers (which, to the best of my knowledge is a complex matter) but allow rows within blocks to be performed in parallel.</p> <p>I'm afraid that I've missed out some other, better, options. This is the primary reason for opening this question. I'm completely stuck. Furthermore, I believe that the differences in how well the source/destination vectors are re-used are too close to call. Does anyone know how I would approach shedding more insight into this?</p> </li> <li><p>Even if the cache hit rate is high, I'm afraid of the bottleneck shifting to e.g. inadequate instruction scheduling. Is there a way to check this in a machine-independent way other than having to rely on memory bandwidth?</p> </li> <li><p>Is there a way to make the &quot;ugly&quot; non-vectorizable code more elegant?</p> </li> </ol> <p>Proofreading the above, I feel like a total amateur; all feedback is (very) much appreciated. Thank you in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T00:26:30.013", "Id": "505922", "Score": "0", "body": "There is a bunch of code to review here, but the most important part is missing. IMO that part should be added (even if done in an inefficient way) to make the question \"complete for review\". By the way dot-product is a solvable problem, the efficient ways aren't very pretty but so be it" } ]
[ { "body": "<p>The functions in the <code>mm</code> namespace do not seem to provide any value over just calling the mnemonics directly. I would get rid of these to keep the code simple. Also, do you know the language rules around the use of leading underscores in names by heart? If not, I'd suggest avoiding their use altogether, otherwise I'd caution against it anyway because not everyone knows these obscure rules (referring to the arguments starting with double underline).</p>\n<p>You've gone through considerable effort to try to make it fast. Have you benchmarked it? Do you know if your code is actually faster than the naive element wise product of two vectors? (Assuming the matrix is indeed diagonal as you say first, not clustered like you later say). Starting and communicating between threads that distribute the workload is overhead that is likely going to not be worth it for small matrices. How small you ask? Depends on your CPU. Benchmark, benchmark, benchmark! In addition to comparing to the naive implementation (again, assuming the matrix is actually diagonal), I would compare to an existing library like <a href=\"https://eigen.tuxfamily.org/index.php?title=Main_Page\" rel=\"nofollow noreferrer\">Eigen</a> or <a href=\"http://arma.sourceforge.net\" rel=\"nofollow noreferrer\">Armadillo</a> to see where your code lands in the grand scheme of things.</p>\n<p>I understand this is an exercise, but I'll just point out that if it wasn't, you should totally use one of the existing libraries for this.</p>\n<p>I'm not sure if the loop unroll pragmas actually help you, the compiler should do unrolling already to a suitable degree. It seems like this pragma at best does nothing or at worst forces an unrolling when you might not want it (e.g. when debugging or if you want the binary size to be smaller). With that in mind it adds additional complexity to the code. I'd benchmark with and without using -O2 and -O3 and seeing the difference.</p>\n<p>I see this a lot with beginner C/C++ programmers, they want to do all the fancy things to make it fast, hand unrolling, extracting common subexpressions etc. What they usually don't know it's that the compiler already does all of this and so much more, and it does it better than what they can do or at least not worse in almost all cases. The compilers we have today are not your grandpa's old compiler, they're amazing at generating efficient code to the point that the best thing you can do is to clearly express your algorithm and intent and let the compiler generate the code.</p>\n<p>Case in point, which is faster:</p>\n<pre><code>int factorial(int n){\n if(1==n)\n return n;\n return n * factorial(n-1);\n}\n</code></pre>\n<p>or</p>\n<pre><code>int factorial (int n){\n int ans=1;\n while (n&gt;1){\n ans*=n;\n n--;\n }\n return ans;\n}\n</code></pre>\n<p>?</p>\n<p>We'll it's a trick question because the compiler will generate the same machine code for both, so they're identical. My point being, let the compiler do it's job and worry about expressing your intent clearly. And only if the compiler is failing at generating fast code should you go crazy, but always with benchmark in hand.</p>\n<p>Did you know the compiler can generate SSE and other vector instructions where it makes sense of you tell it that it's allowed to? See for example\n<a href=\"https://gcc.gnu.org/projects/tree-ssa/vectorization.html\" rel=\"nofollow noreferrer\">this website</a>. I'm sure you can find an equivalent in clang and msvc.</p>\n<p>All this is to say... Do you really need the complexity that you're adding? I don't know because you haven't shown me any benchmarks. :)</p>\n<p>As for prefetching, I've never seen a case where a manual insertion of a prefetch instruction made any noticeable difference, the CPU prefetchers are generally very good.</p>\n<p>I'm going to avoid going into details of reviewing the code because I feel like that's predicated on the outcome of the benchmarking results, and I have a suspicion that you'll likely be surprised by the results and might want to reconsider your implementation.</p>\n<p>Hope that helps!</p>\n<p>(Written on a phone, sorry for typos and autocorrect)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T11:30:33.737", "Id": "505950", "Score": "0", "body": "Thank you very much! 1) The point of the mm namespace is to overload the intrinsics, \ne.g. _mm_load_ps and _mm_load_pd 2) the __arg follow the conventions in the header files 3) apologies, the matrix is diagonally clustered, not strictly diagonal 4) the matrices are relatively large, in the >300k elements 5) I understand what you mean by optim. compilers, will look into, Hager & Wellein state that such cases difficult to optimize automatically/with hints 6) not able to find an open source diamv implementation, only intel mkl 7) I'll benchmark once I finish (auto)vectorization. Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T23:19:23.190", "Id": "506004", "Score": "0", "body": "2) the convention is reserved for internal use by the compiler, you should not follow it because you're not the compiler and you could get name clashes with internal compiler macros and what not which might not even show up as a compiler error. This is what I meant with language rules around the use of leading underscores. 5) there's been big improvements the last years not sure how old your reference is. Which is why you should benchmark :) 6) for starters you can compare against sparse matrices in Eigen. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T23:22:56.383", "Id": "506005", "Score": "0", "body": "One thing to consider, sometimes it's better to add zeros in the vectors to pad out the operations than to have extra code to handle the parts that don't align perfectly into aligned vector reads. If that makes sense." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T10:00:48.167", "Id": "256289", "ParentId": "256281", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-20T23:47:55.793", "Id": "256281", "Score": "3", "Tags": [ "c++", "performance", "matrix" ], "Title": "Optimizing a diagonal matrix-vector multiplication (?diamv) kernel" }
256281
<p>Below is my solution for the <a href="https://github.com/hmemcpy/milewski-ctfp-pdf" rel="nofollow noreferrer">CTFP chapter 4 challenges</a> which essentially involves composing partial functions (that don't have defined outputs for all possible inputs i.e. returning a Maybe).</p> <p>The challenge is to implement composition, identity(to satisfy category requirements) and try it out with 2 partial functions. As I'm relatively new to Haskell, I was hoping to get a general code review with suggestions on better idioms and testing I could follow. <a href="https://onecompiler.com/haskell/3wpfu3tc5" rel="nofollow noreferrer">Link to Code</a></p> <pre><code>import Test.HUnit module Main where -- Given safeRoot :: Double -&gt; Maybe Double safeRoot x | x &lt; 0 = Nothing | otherwise = Just (sqrt x) -- Q1: Identity and composition partialFnId :: a -&gt; Maybe a partialFnId x = Just x partialFnCompose :: (b -&gt; Maybe c) -&gt; (a -&gt; Maybe b) -&gt; (a -&gt; Maybe c) partialFnCompose g f = \x -&gt; case (f x) of Just value -&gt; g value Nothing -&gt; Nothing -- Testing Q1 testPartialFnMeetsCategoryRequirements1 = TestCase $ assertEqual &quot;Id should pass through inputs&quot; (Just 3) (partialFnId 3) testPartialFnMeetsCategoryRequirements2 = TestCase $ assertEqual &quot;Composition with identity is noop(1)&quot; (Just 2.0) ((partialFnCompose partialFnId safeRoot) 4) testPartialFnMeetsCategoryRequirements3 = TestCase $ assertEqual &quot;Composition with identity is noop(2)&quot; (Just 2.0) ((partialFnCompose safeRoot partialFnId) 4) -- Q2: Implement safeReciprocal safeReciprocal :: Double -&gt; Maybe Double safeReciprocal x | x == 0 = Nothing | otherwise = Just (1 / x) -- Q3: Implement safeRootReciprocal via composing the above 2. safeRootReciprocal :: Double -&gt; Maybe Double safeRootReciprocal = partialFnCompose safeRoot safeReciprocal -- Testing Q3 testSafeRootReciprocal1 = TestCase $ assertEqual &quot;Provides root of reciprocal for valid inputs&quot; (Just 2.0) (safeRootReciprocal 0.25) testSafeRootReciprocal2 = TestCase $ assertEqual &quot;Provides Nothing on invalid inputs(1)&quot; Nothing (safeRootReciprocal 0.0) testSafeRootReciprocal3 = TestCase $ assertEqual &quot;Provides Nothing on invalid inputs(2)&quot; Nothing (safeRootReciprocal (-0.25)) main = do runTestTT $ TestList [testPartialFnMeetsCategoryRequirements1, testPartialFnMeetsCategoryRequirements2, testPartialFnMeetsCategoryRequirements3, testSafeRootReciprocal1, testSafeRootReciprocal2, testSafeRootReciprocal3] </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T06:04:55.887", "Id": "256287", "Score": "2", "Tags": [ "programming-challenge", "haskell", "functional-programming" ], "Title": "Partial Function composability in Haskell" }
256287
<p>I'm trying to solve the problem given <a href="https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/" rel="nofollow noreferrer">here</a>.</p> <blockquote> <p>Arrange given numbers to form the biggest number | Set 1</p> <p>Given an array of numbers, arrange them in a way that yields the largest value. For example, if the given numbers are &gt; {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. And if the given numbers are {1, 34, 3, 98, 9, &gt; 76, 45, 4}, then the arrangement 998764543431 gives the largest value.</p> <p>A simple solution that comes to our mind is to sort all numbers in descending order, but simply sorting doesn’t work. &gt; For example, 548 is greater than 60, but in output 60 comes before 548. As a second example, 98 is greater than 9, but &gt; 9 comes before 98 in output.</p> <p>So how do we go about it? The idea is to use any comparison based sorting algorithm. In the used sorting algorithm, instead of using the default comparison, write a comparison function myCompare() and use &gt; it to sort numbers.</p> <p>Given two numbers X and Y, how should myCompare() decide which number to put first – we compare two numbers XY (Y &gt; appended at the end of X) and YX (X appended at the end of Y). If XY is larger, then X should come before Y in output, &gt; else Y should come before. For example, let X and Y be 542 and 60. To compare X and Y, we compare 54260 and 60542. Since 60542 is greater than 54260, we put Y first.</p> <p>Following is the implementation of the above approach. To keep the code simple, numbers are considered as strings, the vector is used instead of a normal array.</p> </blockquote> <p>I'm getting the required output but the written code looks like code bloat(I mean could've have written better simpler and easy code). Can somebody suggest a better way of doing it. This is my code</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;algorithm&gt; bool comp(const int32_t ia, const int32_t ib) { const std::string a = std::to_string(ia); const std::string b = std::to_string(ib); int32_t i = 0; if (a.size() == b.size()) { while (i &lt; a.size()) { if (a.at(i) == b.at(i)) { ++i; continue; } else if (a.at(i) &gt; b.at(i)) return true; else return false; } } else { int32_t min_size = static_cast&lt;int32_t&gt;(std::min(a.size(), b.size())); int32_t max_size = static_cast&lt;int32_t&gt;(std::max(a.size(), b.size())); while (i &lt; min_size) { if (a.at(i) == b.at(i)) { ++i; continue; } else if (a.at(i) &gt; b.at(i)) return true; else return false; } const char temp = a.at(0); const std::string&amp; max_str = (a.size() &gt; b.size()) ? a : b; if (max_str == b) { while (i &lt; max_size) { if (temp &gt;= max_str.at(i++)) return true; else return false; } } else { while (i &lt; max_size) { if (temp &gt;= max_str.at(i++)) return false; else return true; } } } } int32_t main() { int32_t arr[] = { 546, 548, 54, 60 }; int32_t arr_size = sizeof(arr) / sizeof(*arr); std::sort(arr, arr + arr_size, comp); for (const int val : arr) std::cout &lt;&lt; val; std::cout &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T14:18:39.387", "Id": "505962", "Score": "0", "body": "Use the C++ STL container classes such as std::vector and use iterators." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T14:45:49.683", "Id": "505966", "Score": "0", "body": "In the future please add the text of the problem as well as the link since links can break." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T15:46:11.590", "Id": "505972", "Score": "1", "body": "Please don’t edit the code in the question; it makes the answers nonsensical. If you want a new review with modified code, ask another question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T13:15:05.527", "Id": "506053", "Score": "0", "body": "That is a shocking amount of code for something that could be `return a+b > b+a;` once `a` and `b` are assigned!" } ]
[ { "body": "<h2>Simplify the Returns</h2>\n<p>There is no need for the complex if statements such as</p>\n<pre><code>if (a.at(i) &gt; b.at(i))\n return true;\nelse\n return false;\n</code></pre>\n<p>These can be simplified to</p>\n<pre><code>return (a.at(i) &gt; b.at(i));\n</code></pre>\n<p>There is no need for the <code>continue;</code> statement in any of the loops since they are all embedded in if statements and the following code is outside the body of the current <code>if</code> clause.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T15:42:12.153", "Id": "505969", "Score": "0", "body": "Thanks for the suggestions. I've made the suggested changes of you and it's more elegant than before." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T15:44:22.310", "Id": "505970", "Score": "0", "body": "It’s probably also worth mentioning that all of those loops look like variations on `string::compare()`. The first one (before the original code was edited, of course), basically looks like just `return a < b;` (ignoring bugs where nothing gets returned)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T15:52:10.617", "Id": "505974", "Score": "0", "body": "I think the part of the code which @pacmaninbw is saying is not repetition because I'm returning different value in the `if` and `else` part for the same conditions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T16:11:44.387", "Id": "505976", "Score": "0", "body": "Sorry, your correct about the duplication I missed that." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T14:58:33.997", "Id": "256298", "ParentId": "256295", "Score": "1" } }, { "body": "<h1>The code is broken</h1>\n<p>Before asking “can this code be sexier”, you should be asking “does this code work”.</p>\n<p>Spoiler: it doesn’t.</p>\n<h2>Always test your code</h2>\n<p>You have written a function <code>comp(a, b)</code>. You haven’t written any tests for it. You’ve used it in a single case and got the correct answer, but that means very little.</p>\n<p>At the bare minimum, you should have a test suite that has two test cases: one for when <code>a</code> and <code>b</code> are equal, and one for when they are not.</p>\n<p>For example, for the “equal” test case, you can just generate bunch of random numbers between 0 and some maximum. Here’s what that might look like using <a href=\"https://github.com/catchorg/Catch2\" rel=\"nofollow noreferrer\">the Catch2 test framework</a>:</p>\n<pre><code>#define CATCH_CONFIG_MAIN\n#include &quot;catch2/catch.hpp&quot;\n\n#include &lt;cstdint&gt; // need for std::size_t, std::uint32_t\n#include &lt;limits&gt;\n\n// include the header with comp() declared\n\nTEST_CASE(&quot;comparing equal&quot;)\n{\n constexpr auto num_trials = std::size_t{10};\n\n constexpr auto min_val = std::int32_t{0};\n constexpr auto max_val = std::numeric_limits&lt;std::int32_t&gt;::max();\n\n auto value = GENERATE(take(num_trials, random(min_val, max_val)));\n\n INFO(&quot;value = &quot; &lt;&lt; value);\n CHECK_FALSE(comp(value, value)); // value cannot be less-than itself\n}\n</code></pre>\n<p>This compiles (with warnings, more on that later), and runs, and all tests pass. That’s what happened for me, anyway. You may or may not get all tests passing, because there is a critical bug in your code. We’ll get back to that in the next section, but for now, I’ll just assume all tests passed.</p>\n<p>So now for the “unequal” test case, you just list a bunch of pairs of numbers, where the first number should always compare less-than the second:</p>\n<pre><code>TEST_CASE(&quot;comparing unequal&quot;)\n{\n auto data = GENERATE(table&lt;std::uint32_t, std::uint32_t&gt;({\n // single digit numbers\n {1, 0},\n {9, 0},\n {9, 8},\n // ... etc.\n // multi-digit numbers\n {111, 110},\n {124, 123},\n {130, 120},\n {130, 129},\n {200, 100},\n {200, 109},\n {200, 190},\n {200, 199},\n // ... etc.\n // other interesting cases, add as many as you please\n\n {1, 110}, // this works, but...\n {112, 1}, // try this one!\n\n {321, 3212}, // okay...\n {3214, 321}, // ... also okay...\n {3213, 321}, // ... but uh-oh!\n }));\n\n INFO(&quot;a = &quot; &lt;&lt; std::get&lt;0&gt;(data));\n INFO(&quot;b = &quot; &lt;&lt; std::get&lt;1&gt;(data));\n\n CHECK(comp(std::get&lt;0&gt;(data), std::get&lt;1&gt;(data)));\n\n CHECK_FALSE(comp(std::get&lt;1&gt;(data), std::get&lt;0&gt;(data)));\n}\n</code></pre>\n<p>Again, compile and run. This time, there are failures.</p>\n<p>Why does those cases fail? I’ll explain later, but for now I’ll just say that your algorithm will fail for <em>some</em> cases where one number is <code>&lt;pattern&gt;</code>, and the second number is <code>&lt;pattern&gt;D&lt;something&gt;</code> where the digit <code>D</code> is the same as the first digit of the pattern. For example, 545 and 54 (the former should come first, to get 54554, rather than 54545) would fail, but 565 and 56 work (56556 is less than 56565).</p>\n<p>This is why we write tests.</p>\n<h2>Turn on warnings</h2>\n<p>If you compile with g++ or clang (and probably any other compiler), and turn warnings on… <em><strong>which you always should</strong></em>… you will get a warning like this:</p>\n<pre><code>warning: control reaches end of non-void function [-Wreturn-type]\n</code></pre>\n<p>(I actually get <em>two</em> warnings, and <em>both</em> matter, but the second isn’t as critical, because you’re only going to be dealing with small sizes. I’ll mention it later, though.)</p>\n<p>What that warning is telling is you that you have a function—<code>comp()</code>—that returns something—something that is not <code>void</code>—but <em>somehow</em> it is possible to reach the end of the function—the closing <code>}</code>—without returning a value.</p>\n<p>We can figure out exactly what is going on later, but for now, let’s hack a nasty little fix to shut the warning up. At the very end of <code>comp()</code>, right before the closing brace, add the following two lines:</p>\n<pre><code>\n std::cerr &lt;&lt; &quot;you have a bug!&quot; &lt;&lt;\n &quot;\\n a = &quot; &lt;&lt; ia &lt;&lt;\n &quot;\\n b = &quot; &lt;&lt; ib &lt;&lt;\n '\\n';\n return false;\n</code></pre>\n<p>If the compiler is right, and if it is possible to get to the end of this function without returning a value, this will display an error message, and then just return <code>false</code>. So compile the test code again, and run it and…</p>\n<p>… you get the same results as before… but now there are 10 messages in the output:</p>\n<pre><code>you have a bug!\n a = 1867888929\n b = 1867888929\nyou have a bug!\n a = 1276619030\n b = 1276619030\nyou have a bug!\n a = 1911218783\n b = 1911218783\n... [ and so on ]\n</code></pre>\n<p>(The random numbers will be different, of course, but the pattern—the same number appearing for both <code>a</code> and <code>b</code>—will be the same.)</p>\n<p>The compiler was right. You have a bug.</p>\n<p>Looking at the messages printed, it seems to only happen when <code>a</code> equals <code>b</code>. Before we caught the bug, the function was just returning gibberish whenever <code>a</code> and <code>b</code> were equal… but you didn’t notice, because it didn’t matter to the algorithm (and also because you didn’t test), because when <code>a</code> and <code>b</code> are equal, the function could either return <code>true</code> or <code>false</code> and it makes no difference. It is undefined behaviour, and just <em>happens</em> to “work” on my platform (and probably yours, but who’s to say, because you didn’t test)… but on other platforms, anything could happen.</p>\n<p>This is why we turn on warnings, and fix them.</p>\n<h2>Summary</h2>\n<p>Although your code <em>appeared</em> to be working, writing some tests and turning on warnings revealed:</p>\n<ol>\n<li>There are cases where it fails.</li>\n<li>Even when it <em>appears</em> to work, there is dangerous undefined behaviour.</li>\n</ol>\n<p>You should always write tests to test your code; oftentimes it will blow your mind how it can fail in surprising and unexpected ways.</p>\n<p>You should also always turn on all warnings, and then fix them. Some people even recommend turning warnings into errors, so that even a single warning will kill the compile. That’s not bad advice.</p>\n<h1>Code review</h1>\n<h2>General issues</h2>\n<p>Overall, the biggest issue with your code is that it is—as you suspected—<em>wildly</em> overcomplicated. It is so ridiculously overcomplicated, that <em>at least</em> two expert level C++ programmers looked at your code and missed critical bugs, and/or failed to understand what was actually going on. (And I’m not even counting myself; I probably missed stuff, too.) That should be a sign.</p>\n<p>There are two general rules that would make a <em>HUGE</em> difference:</p>\n<ul>\n<li>Break up complicated functions into simpler ones. There are <em>multiple</em> parts of <code>comp()</code> that really should be broken out into separate functions. You have <em>4 loops</em> in <code>comp()</code>; <em>1</em> is the max you should aim for… and even that might be too much, because of the second rule.</li>\n<li>Avoid writing loops. If you find yourself writing a loop, stop… think about what you’re <em>actually</em> trying to do… it’s probably some standard algorithm. In that case, use that algorithm.</li>\n</ul>\n<p>The second rule is really the most important, because when you stop yourself from writing naked loops and think in terms of algorithms instead:</p>\n<ul>\n<li>Your code becomes easier to understand. <code>std::mismatch(a.begin(), a.begin() + min_size, b.begin(), b.begin() + min_size)</code> is already complicated, but I can still tell at a glance roughly what’s going on <em>much</em> easier than I can with a manual loop.</li>\n<li>Complications are easier to spot. It is trivial to spot the difference between <code>std::mismatch(p, p + max_str.size(), max_str.begin(), max_str.end())</code> and <code>std::mismatch(max_str.begin(), max_str.end(), p, p + max_str.size())</code>. Spotting the difference between those two loops? Not so much.</li>\n<li>Mistakes are easier to spot. That first loop is just <code>return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());</code>. But because of the complexity of the loop, you didn’t realize you’d failed to account for the situation where the two strings are equal, and you get to the end of the loop without returning anything.</li>\n<li>Especially when dealing with standard algorithms, they’re already tested and optimized. You can almost never beat them without serious sorcery (and even then, often not).</li>\n</ul>\n<h2>Review</h2>\n<pre><code>bool comp(const int32_t ia, const int32_t ib)\n</code></pre>\n<p>You use <code>int32_t</code> throughout, but there are two problems with that.</p>\n<ul>\n<li>First, it’s not <code>int32_t</code>. It’s <code>std::int32_t</code>, and you have to include <code>&lt;cstdint&gt;</code>. The reason it <em>appears</em> to work for you is probably that you’re using a C++ compiler/library that also doubles as a C compiler/library, and they just include <code>int32_t</code> without the <code>std::</code> to be lazy. But it’s not guaranteed to work everywhere.</li>\n<li>Second, <code>int32_t</code> is not portable in any case. All the fixed-width types are platform dependent. The moment you use one, you make your code less portable. And in this case, there’s no reason whatsoever for using one.</li>\n</ul>\n<p>There’s absolutely no reason to use <code>int32_t</code> and not <code>int</code>. Using the wrong type breaks your code in some places (like returning it from <code>main()</code>). Where it doesn’t, it just makes your code unnecessarily unportable.</p>\n<pre><code>const std::string a = std::to_string(ia);\nconst std::string b = std::to_string(ib);\n</code></pre>\n<p>While these work fine, they’re unnecessarily inefficient. You already know the maximum size string you’ll need, and you know that both <code>ia</code> and <code>ib</code> should be greater than or equal to zero. You could use arrays and <code>numeric_limits&lt;type&gt;::digits10()</code>, and then <code>to_chars()</code> to do all this <em>lightning</em> fast, and with no memory allocation, something like so:</p>\n<pre><code>auto a_chars = std::array&lt;char, std::numeric_limits&lt;decltype(ia)&gt;::digits10() + 2&gt;{};\nauto b_chars = std::array&lt;char, std::numeric_limits&lt;decltype(ib)&gt;::digits10() + 2&gt;{};\n\nstd::to_chars(a_chars.data(), a_chars.data() + a_chars.size(), ia);\nstd::to_chars(b_chars.data(), b_chars.data() + b_chars.size(), ib);\n</code></pre>\n<p>Or, better yet, move all that into its own function.</p>\n<pre><code>int32_t i = 0;\n</code></pre>\n<p>This is bad practice for a number of reasons.</p>\n<p>First, you should only declare variables where you’re going to use them; unless you have a <em>damn</em> good reason, you should never declare them up at the top of a function.</p>\n<p>And you should <em>especially</em> not reuse a variable for different things throughout a function. <code>i</code> is used as a loop counter in both branches of that <code>if</code>, for two (or more) entirely different loops. That’s bad. You don’t need it at all for either of the first two loops; in the first loop, it should just be a local counter for a <code>for</code>, if anything, and in the second loop, the same, and after you could set it using <code>min_size</code>.</p>\n<pre><code>if (a.size() == b.size()) {\n while (i &lt; a.size()) {\n if (a.at(i) == b.at(i)) {\n ++i;\n \n continue;\n }\n else if (a.at(i) &gt; b.at(i))\n return true;\n else\n return false;\n }\n} else {\n</code></pre>\n<p>Alright, so what <em>exactly</em> is going on here? The manual loop just complicates what is actually a very simple thing. If the two strings are the same size, you go through looking for any mismatched characters, and if you find a mismatched pair, you return true if the character in <code>a</code> is less than the character in <code>b</code>.</p>\n<p>What you don’t account for, though, is what happens if <em>all</em> the characters are equal. In that case, you just fall out of the loop and continue on… and eventually get to the end of the function, which returns nothing. That’s your critical bug.</p>\n<p>This is what the code above is <em>actually</em> doing, using algorithms to make everything clearer:</p>\n<pre><code>if (a.size() == b.size())\n{\n auto [it_a, it_b] = std::mismatch(a.begin(), a.end(), b.begin()); // don't need b.end(), because the sizes are the same\n if (it_a != a.end()) // don't need to check it_b, because the sizes are the same\n {\n return *it_a &lt; *it_b;\n }\n else\n {\n // what happens here?\n //\n // your current code does nothing, so the program continues on to the\n // end of the function, which has no return statement... thus, the bug\n }\n}\n</code></pre>\n<p>So what is supposed to happen if the two strings are equal? Logically, I’d think, you would return <code>false</code>, because if the two strings are equal, then <code>ia</code> is <em>not</em> less-than <code>ib</code>. So:</p>\n<pre><code>if (a.size() == b.size())\n{\n auto [it_a, it_b] = std::mismatch(a.begin(), a.end(), b.begin());\n if (it_a != a.end())\n {\n return *it_a &lt; *it_b;\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n<p>But searching for the first mismatch and then returning true if the first char is less than the second is just a lexicographical compare:</p>\n<pre><code>if (a.size() == b.size())\n{\n return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());\n}\n</code></pre>\n<p>But that’s just what <code>std::string</code>’s <code>operator&lt;</code> does:</p>\n<pre><code>if (a.size() == b.size())\n{\n return a &lt; b;\n}\n</code></pre>\n<p>In other words, if the two strings are same size, return true only if <code>a</code> is lexicographically less than <code>b</code>. If you reason about your code at a higher level, rather than getting bogged down with loops, you can spot these simplifications much more easily. In other words, don’t focus on the details, step back and think about the big picture.</p>\n<pre><code>int32_t min_size = static_cast&lt;int32_t&gt;(std::min(a.size(), b.size()));\nint32_t max_size = static_cast&lt;int32_t&gt;(std::max(a.size(), b.size()));\n</code></pre>\n<p>Forcing <code>int32_t</code> here introduces potential bugs. None are likely to trigger in reality, because the lengths of the two strings should be very, very small, even for 64- or 128-bit integers. However, there’s no sensible reason to tempt fate.</p>\n<p>The first potential bug is truncation if the size is greater than what would fit in an <code>int32_t</code>. Again, that will never happen in reality, but again, why play dangerously for no good reason?</p>\n<p>The second potential bug is what a decent compiler with warnings turned on will warn you about. Comparing signed and unsigned values is a craps shoot. If you are mixing signedness in a comparison, you can get absurdities like <code>-1 &gt; 1u</code>.</p>\n<p>There’s no reason to force-cast any of the above into <code>int32_t</code>… or to force-cast it into <em>anything</em>. Just use <code>auto</code>, and everything works:</p>\n<pre><code>auto const min_size = std::min(a.size(), b.size());\nauto const max_size = std::min(a.size(), b.size());\n</code></pre>\n<p>Much less typing, too. Or:</p>\n<pre><code>auto const [min_size, max_size] = std::minmax(a.size(), b.size());\n</code></pre>\n<p>That works just as well.</p>\n<pre><code>while (i &lt; min_size) {\n if (a.at(i) == b.at(i)) {\n ++i;\n \n continue;\n }\n else if (a.at(i) &gt; b.at(i))\n return true;\n else\n return false;\n}\n</code></pre>\n<p>The next naked loop; what exactly is this one doing? Well, it’s going from 0 (which is the value of <code>i</code> at the start of the loop, though it isn’t immediately obvious from the code), to the minimum size of the two strings, and doing a lexicographical comparison. In other words:</p>\n<pre><code>if (auto const res = a.compare(0, min_size, b); res != 0)\n{\n return res &lt; 0;\n}\n</code></pre>\n<p>We don’t even need to check which one is smaller here, because we’re using the minimum size.</p>\n<p>Now from this point on is where the problems really start. At this point, you’ve dealt with the case where the two strings have equal length (of course, you need to fix the bug when they’re exactly equal). You’ve also dealt with the case where you have a short string and a long string, and the first part of the long string is either greater or less than the short string. So what you have now is the case where you have a short string, and a longer string that starts with the short string. In other words: the short string is <code>&lt;pattern&gt;</code>, and the long string is <code>&lt;pattern&gt;&lt;something&gt;</code>.</p>\n<p>So what happens next?</p>\n<p>Well, what you do is get the first digit of <code>&lt;pattern&gt;</code>, and then compare it with every digit in <code>&lt;something&gt;</code>. But does that make sense?</p>\n<p>Consider when <code>&lt;pattern&gt;</code> is 42, and <code>&lt;something&gt;</code> is 41 or 49:</p>\n<ul>\n<li><p>With 41, you compare the first 4 with the 4 in 41… it’s <code>&gt;=</code>, so you return <code>true</code>.</p>\n<p>No problem, 42 should compare less than 4241, because 424241 is greater than 424142.</p>\n</li>\n<li><p>With 49, you compare the first 4 with the 4 in 49… it’s <code>&gt;=</code>, so you return <code>true</code>.</p>\n<p>But 42 should compare less than 4249, because 424249 is <em>NOT</em> greater than 424942.</p>\n</li>\n</ul>\n<p>So your algorithm doesn’t work.</p>\n<p>As for the rest of the function, I won’t review it in detail (because it needs to be rewritten), but I’ll just say:</p>\n<ul>\n<li>Avoid <code>std::string.at()</code>. It’s unnecessary. You know for a fact the string is not empty, so <code>a[0]</code> is <em>guaranteed</em> to work.</li>\n<li>You do some trickery with multiple loops to handle the two cases where <code>a</code> is shorter or longer than <code>b</code>, but that just caused confusion (as you saw). Instead, just do something like:</li>\n</ul>\n<pre><code>if (a.size() &lt; b.size())\n some_helper_function(a, b);\nelse\n some_helper_function(b, a);\n</code></pre>\n<p>This is clearer, and safer.</p>\n<h2>Suggestions for fixing</h2>\n<p>First, write test cases. <em>Especially</em> consider test cases that might be troublesome.</p>\n<p>Your function basically has two paths, one for when the two numbers have equal amounts of digits, and one for when they don’t. So you probably need (at least) three test cases:</p>\n<pre><code>TEST_CASE(&quot;equal values&quot;)\n{\n // ...\n}\n\nTEST_CASE(&quot;unequal values with the same digit count&quot;)\n{\n // ...\n}\n\nTEST_CASE(&quot;unequal values with different digit counts&quot;)\n{\n // ...\n}\n</code></pre>\n<p>In the latter case, you should check a bunch of of cases, but especially some cases where the short value is repeated one or more times, like:</p>\n<ul>\n<li>1 and 11</li>\n<li>1 and 1111111</li>\n<li>12 and 1212</li>\n<li>12 and 12121212</li>\n<li>21 and 2121</li>\n<li>21 and 21212121</li>\n</ul>\n<p>And you should check cases where the short value is repeated, then followed by something that will make it sort before <em>or</em> after, like:</p>\n<ul>\n<li>45 and 451</li>\n<li>45 and 454</li>\n<li>45 and 459</li>\n<li>45 and 4545451</li>\n<li>45 and 4545454</li>\n<li>45 and 4545459</li>\n<li>54 and 541</li>\n<li>54 and 545</li>\n<li>54 and 549</li>\n<li>54 and 5454541</li>\n<li>54 and 5454545</li>\n<li>54 and 5454549</li>\n</ul>\n<p>Once you have your test cases set up, you should think about what makes one number sort before or after another… especially when there is a repeated pattern. Like, does 56 come before or after 561, 565 and 569, and why? What about 56 and 5656561, 5656565, and 5656569? I’ll give you one tip: it’s all about lexical comparisons with the short pattern… <em>repeated</em> lexical comparisons with the short pattern, not just one-and-done.</p>\n<p>And of course, turn on warnings, and heed them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T04:30:31.107", "Id": "506014", "Score": "0", "body": "+5. I hope your review is not taken as discouraging or frustrating as there is a lot to learn here. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T13:07:10.053", "Id": "506052", "Score": "0", "body": "You missed the third issue with `std::int32_t`: it's a signed type, so a poor fit in an unsigned problem domain." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T13:23:10.867", "Id": "506054", "Score": "0", "body": "Eww, I see what you mean about `int32_t` everywhere - `int32_t main()` is only legal by chance... (I'm assuming OP's platform has `int` that happens to be the same type)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T13:48:23.267", "Id": "506056", "Score": "0", "body": "Thanks for the detailed explanation and good suggestions for writing better code. I learned a lot from you." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T00:14:38.663", "Id": "256317", "ParentId": "256295", "Score": "4" } } ]
{ "AcceptedAnswerId": "256317", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T13:40:00.267", "Id": "256295", "Score": "0", "Tags": [ "c++", "programming-challenge" ], "Title": "std::sort custom compare function" }
256295
<p>I have been trying to improve my knowledge with Python and I think the code is pretty forward. However I do dislike abit the coding style I have done where I use too much try except in a content there it might not needed to be at first place.</p> <p>My goal is basically to have a ready payload before scraping as you will see at the top of the code. Those should be always declared before scraping. What im trying to do basically is to try to scrape those different data. If we don't find the data, then it should skip or set the value to [], None or False (Depending on what we are trying to do). I have read abit regarding <code>getattr</code> and <code>isinstance</code> functions but im not sure if there might be a better way than using lots of Try except as a cover if it doesn't find the element on the webpage.</p> <p>I would appreciate all kind of helps!</p> <pre><code>import requests from bs4 import BeautifulSoup payload = { &quot;name&quot;: &quot;Untitled&quot;, &quot;view&quot;: None, &quot;image&quot;: None, &quot;hyperlinks&quot;: [] } site_url = &quot;https://stackoverflow.com/questions/743806/how-to-split-a-string-into-a-list&quot; response = requests.get(site_url) bs4 = BeautifulSoup(response.text, &quot;html.parser&quot;) try: payload['name'] = &quot;{} {}&quot;.format( bs4.find('meta', {'property': 'og:site_name'})[&quot;content&quot;], bs4.find('meta', {'name': 'twitter:domain'})[&quot;content&quot;] ) except Exception: # noqa pass try: payload['view'] = &quot;{} in total&quot;.format( bs4.find('div', {'class': 'grid--cell ws-nowrap mb8'}).text.strip().replace(&quot;\r\n&quot;, &quot;&quot;).replace(&quot; &quot;, &quot;&quot;)) except Exception: pass try: payload['image'] = bs4.find('meta', {'itemprop': 'image primaryImageOfPage'})[&quot;content&quot;] except Exception: pass try: payload['hyperlinks'] = [hyperlinks['href'] for hyperlinks in bs4.find_all('a', {'class': 'question-hyperlink'})] except Exception: # noqa pass print(payload) </code></pre>
[]
[ { "body": "<p>My take, in short:</p>\n<ul>\n<li>in programming there is nothing worse than silently swallowing exceptions :) And the fact that you are catching <em>any</em> exception, and not just those related to those specific operations, means than all kinds of errors will go unnoticed.</li>\n<li>At the very least, the exceptions should be logged somewhere</li>\n<li>be more specific and catch relevant exceptions instead, usually it will be stuff like HTMLParser.HTMLParseError and also requests.exceptions - experiment a bit</li>\n<li>Note the difference in behavior between find and find_all since you are using both functions:</li>\n</ul>\n<blockquote>\n<p>If find_all() can’t find anything, it returns an empty list. If find()\ncan’t find anything, it returns None</p>\n</blockquote>\n<ul>\n<li>Armed with that knowledge you can simply test your expressions for None before you try to fetch the value with <code>find</code> - it's better to avoid an exception than having to handle it.</li>\n<li>Likewise, if <code>bs4.find_all('a', {'class': 'question-hyperlink'})</code> returns an empty list, you don't proceed with the list comprehension but you assign some default value, possibly: <code>payload['hyperlinks'] = None</code></li>\n</ul>\n<p>So the key here is to test the result of every call to <code>find</code> or <code>find_all</code> and act accordingly. Then you can get rid of those try catch blocks. Only one all-purpose exception handler for the whole procedure shall suffice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T16:39:41.093", "Id": "505979", "Score": "0", "body": "Thank you very much! I totally agree. There is some places I could use the `find` without needing any try/expect due to if it doesn't find then it will be None anyways! But what I wish is to have sort of if else function where if its None then we could have a default value such as getattr has but that should work as well with one liner if else statement too" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T16:47:15.273", "Id": "505980", "Score": "1", "body": "You are welcome. My advice to stress-test your program and to make it more robust is to test it in adverse conditions. Try to parse a totally unrelated page and see how it reacts. Not finding the expected elements in page should not crash the application, the exception handler should kick in when other types of issues do occur. Also try to fetch pages from unreachable sites (with a misspelled address for example) to test behavior. A good program should handle exceptions gracefully." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T16:50:59.670", "Id": "505981", "Score": "0", "body": "Very well said! I will do that right away! I hoped that I could use getattr since it had a nice function to check if the webelement has a value and u could also have a default exception if its not found for example which I liked but was not able to get it to work with webscraping" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T15:55:50.530", "Id": "256299", "ParentId": "256296", "Score": "2" } } ]
{ "AcceptedAnswerId": "256299", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T14:12:43.427", "Id": "256296", "Score": "2", "Tags": [ "python", "web-scraping", "beautifulsoup" ], "Title": "Scraping webpage elements using Python" }
256296
<p>I made an brute force algorithm to find the longest palindrome within the string. This palindrome is a substring of the input. Below is the code.</p> <pre><code> def generate_substrings(string): &quot;&quot;&quot; avg time: O(len(string) * len(string)) avg space: O(1) amortized time: O(len(string) * len(string)) amortized space: O(1) &quot;&quot;&quot; col = 0 for row in range(len(string)): col = row + 1 while col &lt; len(string) + 1: yield string[row:col] col = col + 1 def test_generate_substrings(): assert list(generate_substrings('')) == [] assert list(generate_substrings('a')) == ['a'] assert list(generate_substrings('ab')) == ['a', 'ab', 'b'] def is_palindrome(string): &quot;&quot;&quot; avg time: O(len(string)) avg space: O(len(string)) amortized time: O(len(string)) amortized space: O(len(string)) &quot;&quot;&quot; return string[::-1] == string def test_is_palindrome(): assert is_palindrome('') == True assert is_palindrome('ab') == False assert is_palindrome('bb') == True assert is_palindrome('abc') == False assert is_palindrome('ddd') == True def find_palindrome(string): &quot;&quot;&quot; avg time: O(len(string) * len(string)) avg space: O(len(string)) amortized time: O(len(string) * len(string)) amortized space: O(len(string)) &quot;&quot;&quot; answer = '' vec = [] for string in generate_substrings(string): if is_palindrome(string): vec.append(string) for string in vec: if len(answer) &lt;= len(string): answer = string return answer def test_find_palindrome(): assert find_palindrome('ab') == 'b' assert find_palindrome('aa') == 'aa' def main(): &quot;&quot;&quot; entry point for test code &quot;&quot;&quot; test_generate_substrings() test_is_palindrome() test_find_palindrome() if __name__ == '__main__': main() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T18:06:58.823", "Id": "505986", "Score": "1", "body": "What's the point of the time estimates in the doc string? Usually we use these to describe functionality" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T14:53:19.443", "Id": "506143", "Score": "1", "body": "And what's \"avg\" time and space? How does it differ from the amortized values?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T16:56:27.600", "Id": "506150", "Score": "0", "body": "@TobySpeight Average complexity is the probability distribution with the assumption that any sized input is equally likely to happen. Where amortized is the average where we know the history of the function and can then infer the complexity average. For example appending to an ArrayList (Python's `list`) is amortized \\$O(1)\\$ because when the internal array changes we know we've had \\$n\\$ \\$O(1)\\$ operations before the \\$1\\$ \\$O(n)\\$ one so \\$\\frac{nO(1) + O(n)}{n + 1} = O(1)\\$. I'd guess an ArrayList's append has something like \\$O(\\log(n))\\$ avg complexity." } ]
[ { "body": "<p>It's good to see code that comes with tests - well done!</p>\n<p>I would add some more tests in places. Specifically, we ought to test <code>is_palindrome()</code> with a single-letter input, as that's something that could easily get broken, and <code>find_palindrome()</code> needs testing with some strings where the longest palindrome is at beginning, middle or end.</p>\n<p>I'm concerned at</p>\n<blockquote>\n<pre><code>assert find_palindrome('ab') == 'b'\n</code></pre>\n</blockquote>\n<p>There's nothing in the problem statement that says we couldn't return <code>'a'</code> instead, so this is actually <em>over-testing</em> the code. There's something similar going in in <code>test_generate_substrings()</code> where we require a specific order (we'd be better testing the result converted to <code>set</code> rather than <code>list</code>, to make the test more reasonable).</p>\n<hr />\n<p>In terms of the algorithm, I see an obvious candidate for improvement:</p>\n<blockquote>\n<pre><code>for string in generate_substrings(string):\n if is_palindrome(string):\n vec.append(string)\n\nfor string in vec:\n if len(answer) &lt;= len(string):\n answer = string\n</code></pre>\n</blockquote>\n<p>We store all of the palindromes in <code>vec</code>, even though we only want the longest one. So we don't really need <code>vec</code>:</p>\n<pre><code>for string in generate_substrings(string):\n if is_palindrome(string) and len(answer) &lt;= len(string):\n answer = string\n</code></pre>\n<p>We could do even better if we arrange for <code>generate_substrings()</code> to return all the substrings longest first. Then we wouldn't need to generate or use all the shorter substrings:</p>\n<pre><code>for string in generate_substrings_longest_first(string):\n if is_palindrome(string):\n return string\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T14:52:32.333", "Id": "256377", "ParentId": "256297", "Score": "1" } } ]
{ "AcceptedAnswerId": "256377", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T14:35:17.823", "Id": "256297", "Score": "0", "Tags": [ "python", "algorithm", "python-3.x", "palindrome" ], "Title": "Algorithm For Longest Palindrome" }
256297
<p>Similar to <a href="https://codereview.stackexchange.com/questions/256287/partial-function-composability-in-haskell">Partial Function composability in Haskell</a>, I've attempted to implement partial function composability in C++20 via C++ concepts. More details about the problem(for which my solution is available below) from the linked post:</p> <blockquote> <p>Below is my solution for the CTFP chapter 4 challenges which essentially involves composing partial functions(that don't have defined outputs for all possible inputs i.e. returning a Maybe/std::optional in C++). The challenge is to implement composition, identity(to satisfy category requirements) and try it out with 2 partial functions.</p> </blockquote> <pre><code>#include &lt;optional&gt; #include &lt;cmath&gt; #include &lt;cassert&gt; #include &lt;concepts&gt; // C++17 alternative with std::function: http://coliru.stacked-crooked.com/a/d8a8ed976dc59715 namespace detail{ template&lt;typename&gt; struct unary_fn; template&lt;typename M, typename R, typename Arg&gt; struct unary_fn&lt;R(M::*)(Arg)&gt; { using return_type = R; using arg_type = Arg; }; template&lt;typename R, typename Arg&gt; struct unary_fn&lt;R(*)(Arg)&gt; { using return_type = R; using arg_type = Arg; }; template&lt;typename Lambda&gt; struct unary_fn : unary_fn&lt;decltype(&amp;Lambda::operator())&gt; { }; template &lt;typename T&gt; struct is_optional: std::false_type {}; template &lt;typename T&gt; struct is_optional&lt;std::optional&lt;T&gt;&gt;: std::true_type {}; } // Concept to check composability template &lt;typename PartialFn1, typename PartialFn2, typename OutType = detail::unary_fn&lt;PartialFn2&gt;::return_type, typename InType = detail::unary_fn&lt;PartialFn1&gt;::arg_type&gt; concept SingleArgComposable = requires(PartialFn1 pf1, PartialFn2 pf2, InType elem) { requires detail::is_optional&lt;typename detail::unary_fn&lt;PartialFn1&gt;::return_type&gt;::value; { pf2(*pf1(elem)) } -&gt; std::same_as&lt;OutType&gt;; requires detail::is_optional&lt;OutType&gt;::value; }; // Given(using std::optional) and safe_root std::optional&lt;double&gt; safe_root(double x) { return x &gt;= 0 ? std::optional{std::sqrt(x)} : std::nullopt; } // Q1: Construct the Kleisli category for partial functions (define composition and identity). template &lt;typename T&gt; std::optional&lt;T&gt; id(T input) { return input; } template &lt;typename PartialFn1, typename PartialFn2, typename RetType = detail::unary_fn&lt;PartialFn2&gt;::return_type&gt; requires SingleArgComposable&lt;PartialFn1, PartialFn2, RetType&gt; auto compose(PartialFn1 firstCallable, PartialFn2 secondCallable) { return [firstCallable, secondCallable](auto inValue) { auto firstResult = firstCallable(inValue); if(firstResult) { return secondCallable(*firstResult); } return RetType{}; }; } // Q2: Implement safe_reciprocal std::optional&lt;double&gt; safe_reciprocal(double input) { return (input != 0) ? std::optional{1 / input} : std::nullopt; } int main(){ static_assert(detail::is_optional&lt;std::optional&lt;double&gt;&gt;::value); // Q1(Testing id + compose) assert((safe_root(4.) == compose(id&lt;double&gt;, safe_root)(4.)) &amp;&amp; safe_root(4.) == std::optional&lt;double&gt;{2.}); assert((safe_root(4.) == compose(safe_root, id&lt;double&gt;)(4.)) &amp;&amp; safe_root(4.) == std::optional&lt;double&gt;{2.}); assert((safe_root(-5.) == compose(safe_root, id&lt;double&gt;)(-5.)) &amp;&amp; safe_root(-5.) == std::nullopt); // Q3: Compose safe_root and safe_reciprocal auto safe_root_reciprocal = compose(safe_reciprocal, safe_root); assert(*safe_root_reciprocal(0.25) == 2.0); assert(safe_root_reciprocal(0) == std::nullopt); assert(safe_root_reciprocal(-0.25) == std::nullopt); } </code></pre> <p><a href="http://coliru.stacked-crooked.com/a/6102f86319495ff4" rel="nofollow noreferrer">Coliru Link</a></p> <p>Hoping to get suggestions on:</p> <ul> <li>C++20 alternatives I can use to avoid having to implement &quot;unary_fn&quot;.</li> <li>Any improvements I could make to the <code>SingleArgComposable</code> concept(to make it closer to the Haskell &quot;concept&quot; <code>(b -&gt; Maybe c) -&gt; (a -&gt; Maybe b) -&gt; (a -&gt; Maybe c)</code>). <code>std::function</code> is actually able to come pretty close(<a href="http://coliru.stacked-crooked.com/a/d8a8ed976dc59715" rel="nofollow noreferrer">coliru link</a>), but I was hoping to do this with concepts.</li> <li>General review for improvements and C++20 features I should be using.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T19:29:48.363", "Id": "506168", "Score": "0", "body": "Does `std::function` not support all this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T19:34:06.000", "Id": "506170", "Score": "1", "body": "Unfortunately C++ is never going to support \"Partial Functions\" in the same way. Some of these functional languages allowed partial execution of the function with the given parameters blocking when missing parameters were needed (and re-starting when they were provided). C++ will never be able to do that. Fortunately that feature hardly ever pays of in increased performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T20:29:22.143", "Id": "506172", "Score": "0", "body": "`std::function` does support this - I implemented it that way in the C\n++17 link above: http://coliru.stacked-crooked.com/a/d8a8ed976dc59715. I was trying to implement this in a generic way to use regular/member/lambda and std::function using C++20 concepts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T20:43:14.223", "Id": "506174", "Score": "0", "body": "Agreed, about some of the fancier features. But I've found that the type constraints Haskell provides is a good way to formulate concepts which was what I was trying in the example above. Additionally, a simple FP concept like compose does seem like it would be handy in C++." } ]
[ { "body": "<p>I looked at chapter 4 and the safe sqrt example:</p>\n<p>Here: <code>safeSqrt</code> is your partial function.</p>\n<pre><code>#include &lt;cmath&gt;\n#include &lt;iostream&gt;\n#include &lt;optional&gt;\n\nauto safeSqrt = [](double x)\n{\n if (x != 0) {\n return std::optional&lt;double&gt;{sqrt(x)};\n }\n return std::optional&lt;double&gt;{};\n};\n\nint main()\n{\n std::cerr &lt;&lt; sqrt(4) &lt;&lt; &quot;\\n&quot;;\n\n auto x = safeSqrt(4);\n std::cerr &lt;&lt; x.value() &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T20:32:38.470", "Id": "506173", "Score": "1", "body": "Apologies - could you clarify your suggestion? - is there a mistake in the way i've implemented `safe_root` above. Also my question was more so asking on suggestions re: the `SingleArgComposable` concept used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T22:17:43.330", "Id": "506179", "Score": "1", "body": "@tangy Why does the above not solve the problem. You have optionals and composed a function using another function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T22:29:44.013", "Id": "506181", "Score": "1", "body": "But I didnt really have any problem(I had already got the composition working), was more so looking for feedback on improving the code. The `safeSqrt` you've provided is equivalent to the `safe_root` I've already written." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T00:25:39.243", "Id": "506183", "Score": "0", "body": "@tangy I am trying to understand why you need any of your code. It seems that it can be done much more simply by using `auto`/`lambda` and a couple of lines of code. What is so special that the above pattern does not solve your problem. Maybe I just don't understand what you are trying to achieve?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T01:49:17.130", "Id": "506188", "Score": "0", "body": "Completely agreed - it can be implemented in a shorter/cleaner way via lambdas. However, my understanding is that applying type constraints via concepts can help with (1) Clearer error messages (2) Making the normally implicit requirements of the function explicit and imposing the same to ensure that inputs meet preconditions. For example in the link here I'm able to erroneously pass in and execute compose with a non partial function which could be caught at compile time with the concept: http://coliru.stacked-crooked.com/a/5fc1f5e4dd686416" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T02:20:45.490", "Id": "506189", "Score": "0", "body": "@MartinYork One short suggestion. It's often better to read if you create a lambda with explicit return type. Instead of getting irritated by empty optional constructor, std::nullopt is more expressive.\n\n```auto safeSqrt = [](double x) -> std::optional<double> { if (x != 0) { return sqrt(x); } return std::nullopt; };```" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T19:45:57.033", "Id": "256390", "ParentId": "256301", "Score": "0" } }, { "body": "<p>First of all, your <code>unary_fn</code> is totally misguided. You're trying to take a C++ object and ask it &quot;What is your first argument type?&quot; C++ doesn't really <em>do</em> that, because we have overloading. See <a href=\"https://quuxplusone.github.io/blog/2018/06/12/perennial-impossibilities/#detect-the-first-argument-type-of-a-function\" rel=\"nofollow noreferrer\">&quot;Perennial impossibilities of C++&quot;</a> (2018-06-12).</p>\n<pre><code>auto abs = [](const auto&amp; x) { return (x &lt; 0) ? -x : x; };\nunary_fn&lt;decltype(abs)&gt; u; // oops, does not compile!\n</code></pre>\n<p>However, to avoid reimplementing the (misguided, wobbly) wheel, you could definitely switch to <a href=\"https://www.boost.org/doc/libs/master/libs/callable_traits/doc/html/callable_traits/reference.html#callable_traits.reference.ref_args\" rel=\"nofollow noreferrer\">Boost.CallableTraits</a>: <code>boost::callable_traits&lt;decltype(abs)&gt;::args</code> also does not compile, but it takes <em>less hand-written code</em> to achieve that same non-compilation. ;)</p>\n<hr />\n<pre><code>template &lt;typename PartialFn1, typename PartialFn2, typename OutType = detail::unary_fn&lt;PartialFn2&gt;::return_type, typename InType = detail::unary_fn&lt;PartialFn1&gt;::arg_type&gt;\nconcept SingleArgComposable = requires(PartialFn1 pf1, PartialFn2 pf2, InType elem) {\n requires detail::is_optional&lt;typename detail::unary_fn&lt;PartialFn1&gt;::return_type&gt;::value;\n { pf2(*pf1(elem)) } -&gt; std::same_as&lt;OutType&gt;;\n requires detail::is_optional&lt;OutType&gt;::value;\n};\n</code></pre>\n<p>This code is pretty impenetrable. Whitespace and newlines would help. So would shorter template parameter names; for example, <code>PartialFn1</code> and <code>PartialFn2</code> are only one trailing digit different, which tends to get lost in the noise, whereas <code>F</code> and <code>G</code> are much more distinct names that convey the exact same amount of information: &quot;this thing is a type parameter.&quot;</p>\n<p>You also don't have to say <code>typename OutType</code>; we know it's a <code>Type</code> because it's a type parameter. Just <code>class Out</code> is good enough. (I prefer <code>class</code> because it's shorter, and doesn't get confused with the other meaning of <code>typename</code> inside complicated templates.)</p>\n<p>Finally, some helper aliases would... help. :)</p>\n<pre><code>template&lt;class F&gt; using unary_arg_t = detail::unary_fn&lt;F&gt;::arg_type;\ntemplate&lt;class F&gt; using unary_return_t = detail::unary_fn&lt;F&gt;::return_type;\n\ntemplate&lt;class F, class G, class Out = unary_return_t&lt;G&gt;, class In = unary_arg_t&lt;F&gt;&gt;\nconcept SingleArgComposable = requires(F f, G g, In x) {\n\n requires detail::is_optional&lt;unary_return_t&lt;F&gt;&gt;::value;\n requires detail::is_optional&lt;Out&gt;::value;\n\n { g(f(x).value()) } -&gt; std::same_as&lt;Out&gt;;\n};\n</code></pre>\n<p>At this point it's actually just about as easy to eliminate the <code>In</code> and <code>Out</code> parameters.</p>\n<pre><code>template&lt;class F, class G&gt;\nconcept SingleArgComposable = requires(F f, G g, unary_arg_t&lt;F&gt; x) {\n\n requires detail::is_optional&lt;unary_return_t&lt;F&gt;&gt;::value;\n requires detail::is_optional&lt;unary_return_t&lt;G&gt;&gt;::value;\n\n { g(f(x).value()) } -&gt; std::same_as&lt;unary_return_t&lt;G&gt;&gt;;\n};\n</code></pre>\n<hr />\n<p>Here's another impenetrable token soup:</p>\n<pre><code>template &lt;typename PartialFn1, typename PartialFn2, typename RetType = detail::unary_fn&lt;PartialFn2&gt;::return_type&gt; requires SingleArgComposable&lt;PartialFn1, PartialFn2, RetType&gt;\nauto compose(PartialFn1 firstCallable, PartialFn2 secondCallable) {\n return [firstCallable, secondCallable](auto inValue) {\n auto firstResult = firstCallable(inValue);\n if(firstResult) {\n return secondCallable(*firstResult);\n }\n return RetType{};\n };\n}\n</code></pre>\n<p>Rewritten to let in some natural light:</p>\n<pre><code>template&lt;class F, class G, class R = unary_return_t&lt;G&gt;&gt;\nauto compose(F f, G g)\n requires SingleArgComposable&lt;F, G&gt;\n{\n return [=](auto x) -&gt; R {\n if (auto fx = f(x)) {\n return g(*fx);\n }\n return std::nullopt;\n };\n}\n</code></pre>\n<p>If this were production code, I would change all the by-copy stuff to use move semantics:</p>\n<pre><code>template&lt;class F, class G, class R = unary_return_t&lt;G&gt;&gt;\nauto compose(F f, G g)\n requires SingleArgComposable&lt;F, G&gt;\n{\n return [f = std::move(f), g = std::move(g)]&lt;class X&gt;(X&amp;&amp; x) -&gt; R {\n if (auto fx = f(std::forward&lt;X&gt;(x))) {\n return g(std::move(*fx));\n }\n return std::nullopt;\n };\n}\n</code></pre>\n<hr />\n<p>Oh, and about halfway through the code you seem to have forgotten about all that <code>unary_fn</code> stuff you had started out with. Clearly, if you want <code>compose(f,g)</code> to itself be composable, you either have to</p>\n<ul>\n<li><p>throw out all that <code>unary_fn</code> stuff because it can't handle generic lambdas such as <code>compose(f,g)</code>, or</p>\n</li>\n<li><p>make <code>compose(f,g)</code> return a non-generic lambda.</p>\n</li>\n</ul>\n<p>For example:</p>\n<pre><code>template&lt;class F, class G&gt;\nauto compose(F f, G g)\n requires SingleArgComposable&lt;F, G&gt;\n{\n return [=](unary_arg_t&lt;F&gt; x) -&gt; unary_return_t&lt;G&gt; {\n if (auto fx = f(x)) {\n return g(*fx);\n }\n return std::nullopt;\n };\n}\n</code></pre>\n<p>Now you can do <code>compose(f, compose(g, h))</code> and so on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T16:46:40.737", "Id": "256416", "ParentId": "256301", "Score": "1" } } ]
{ "AcceptedAnswerId": "256416", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T16:47:18.917", "Id": "256301", "Score": "2", "Tags": [ "c++", "c++20" ], "Title": "Partial function composability in C++" }
256301
<p><a href="https://atcoder.jp/contests/dp/tasks/dp_h" rel="nofollow noreferrer">atcoder.jp Problem Statement</a>:</p> <blockquote> <p>There is a grid with <code>H</code> horizontal rows and W vertical columns. Let <code>(i,j)</code> denote the square at the <code>i</code>-th row from the top and the <code>j</code>-th column from the left.</p> <p>For each <code>i</code> and <code>j</code> (1≤i≤H, 1≤j≤W), Square <code>(i,j)</code> is described by a character <span class="math-container">\$a_{i,j}\$</span>. If <span class="math-container">\$a_{i,j}\$</span> is <code>.</code>, Square <code>(i,j)</code> is an empty square; if <span class="math-container">\$a_{i,j}\$</span> is <code>#</code>, Square <code>(i,j)</code> is a wall square. It is guaranteed that Squares <code>(1,1)</code> and <code>(H,W)</code> are empty squares.</p> <p>Taro will start from Square <code>(1,1)</code> and reach <code>(H,W)</code> by repeatedly moving right or down to an adjacent empty square.</p> <p>Find the number of Taro's paths from Square <code>(1,1)</code> to <code>(H,W)</code>. As the answer can be extremely large, find the count modulo 10⁹+7.</p> </blockquote> <p>In short -<br /> We have H×W grid with each element either '.' or '#' where # denote that we can't visit this block and '.' denote we can visit it. (1,1) and (H,W) will be always '.' . Find total no. of path from (1,1) to (H,W).</p> <p>My approach</p> <pre><code>#include&lt;iostream&gt; #include&lt;vector&gt; using namespace std; const int k=1000000007; int sol(int i,int j,vector&lt;vector&lt;char&gt;&gt;v,int h,int w,vector&lt;vector&lt;int&gt;&gt;dp){ if(i&gt;h || j&gt;w){ return 0; } if(i==h &amp;&amp; j==w){ return 1; } if(v[i][j]=='#'){ return 0; } if(dp[i][j]!=-1){ return dp[i][j]; } dp[i][j]=(sol(i+1,j,v,h,w,dp)%k + sol(i,j+1,v,h,w,dp)%k)%k; return dp[i][j]; } int main(){ int h,w; cin&gt;&gt;h&gt;&gt;w; vector&lt;vector&lt;char&gt;&gt;v(h); char c; vector&lt;vector&lt;int&gt;&gt;dp(h); for(int i=0;i&lt;h;i++){ for(int j=0;j&lt;w;j++){ cin&gt;&gt;c; v[i].push_back(c); dp[i].push_back(-1); } } h--; w--; cout&lt;&lt;sol(0,0,v,h,w,dp)&lt;&lt;endl; } </code></pre> <p>For below test case i am getting TLE</p> <pre><code> 20 20 .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... </code></pre> <p>How I can improve the time complexity of my approach?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T19:04:43.627", "Id": "505987", "Score": "0", "body": "You can start by passing `v` and `dp` into `sol` by reference (const reference for `v`). Also it looks like you have a bounds issue in `sol` because `v[h]` will be out of bounds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T19:29:43.437", "Id": "505989", "Score": "0", "body": "You make copies of the vectors, so writes to `dp[i][j]` would be in that local copy and the caller would never see the change. (Effectively you were never caching any results.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T19:31:31.017", "Id": "505990", "Score": "0", "body": "@1201ProgramAlarm thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T19:49:54.257", "Id": "505991", "Score": "0", "body": "@1201ProgramAlarm I understood that i should pass dp[][] by refrence but i have one more doubt that why i should pass v by refrence I mean we are not making any changes in v. But if i do not pass v by refrence then also get TLE in some test case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T20:17:21.513", "Id": "505996", "Score": "1", "body": "If you pass `v` by reference, only a pointer is passed on the stack. If you don't pass by reference, you pass by value, so the entire vector of vectors is _copied_ on every call. This consumes a lot memory and likely will take more execution time than the rest of the function will take." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T04:21:38.260", "Id": "506013", "Score": "0", "body": "@ErenYeager if you want protection from writing, use `const &`. The point of reference passing is to save expensive copying." } ]
[ { "body": "<h1>Understand argument passing</h1>\n<p>In the code below</p>\n<pre><code>int sol(int i,int j,vector&lt;vector&lt;char&gt;&gt;v,int h,int w,vector&lt;vector&lt;int&gt;&gt;dp){\n</code></pre>\n<p>you pass all arguments <strong>by value</strong>. This means that the compiler will generate deep copies of all the parameters. As you're calling this function repeatedly, this is very expensive for the vectors. However this means that the caller will not see any changes to the variables.</p>\n<p>You should change these to pass <strong>by reference</strong> by changing to:</p>\n<pre><code>int sol(int i,int j, const vector&lt;vector&lt;char&gt;&gt;&amp; v,int h,int w,vector&lt;vector&lt;int&gt;&gt;&amp; dp){\n</code></pre>\n<p>This will avoid copying the vectors and save large amounts of execution time just in the copying. It will also protect the <code>v</code> vector from unintended mutations by passing <strong>by const reference</strong>.</p>\n<p>Note that is this case, because you're creating copies of the <code>dp</code> vector instead of passing a reference to the same vector, the code below will always be false:</p>\n<pre><code>if(dp[i][j]!=-1){\n return dp[i][j];\n}\n</code></pre>\n<p>Because at each call to <code>sol</code> you're getting a copy of the <code>dp</code> vector before anything was written to it. I.e. the <code>dp</code> vector will always be <code>-1</code> everywhere at every point in the recursion. This means that this solution is actually not a dynamic programming solution but rather a depth first summing without the mnemonics that would make it a DP algorithm.</p>\n<h2>The code is computing in the opposite direction</h2>\n<p>You are actually computing the number of paths modulo K from the end to the start, and not the start to the end moving left and up. Instead of from start to end, moving right and left, the solution could be the same for may test cases but I'm not immediately convinced that this is always true.</p>\n<h2>White space</h2>\n<p>The code is devoid of most white space, while perfectly legal code that the compiler is happy to accept, it's very hard to read. I would much appreciate if you at the least added a space after <code>,</code> in argument and parameter lists. You could look into a tool such as <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"nofollow noreferrer\">clang-format</a> that can automatically format your code prior to review. I don't want to prescribe a style as long as it's consistent and readable.</p>\n<h2>Improvement for performance</h2>\n<p>To be clear, the critical problem with the code as presented is that it is actually not reusing computational results because the DP matrix is passed by value. The secondary problem is that the other vectors are also copied at each recursion point which is unnecessarily slow.</p>\n<p>First of we should use an iterative approach to filling in the DP matrix. This is possible because to fill in the first row, we only need elements from the left, and when filling in the next row the previous row and element is already available. This also means that in order to compute the result we only ever need two rows of the DP matrix, the current and the previous. An other interesting impact of filling in the DP matrix in this iterative way from left to right, top to bottom is that we do not actually need to store the maze layout, because we're processing it simultaneously to reading it in.</p>\n<p>By carefully choosing sizes and starting conditions, we can write a very compact and efficient solution shown below. The code below computes the answer to test case number 4 in around <strong>120 microseconds</strong> (ignoring the time it takes to print the result) on my computer and passes the other example test cases.</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n\nconst unsigned long k = 1000000007;\nconst unsigned long w_max = 1001;\n\nint main() {\n unsigned long h, w;\n std::cin &gt;&gt; h &gt;&gt; w;\n\n // We allocate a contiguous array of longs on the stack.\n // We use long instead of int as long is guaranteed to be at least 32 bits\n // which can hold the result of k+k without truncating before we take the modulo,\n // while int is only guaranteed to be 16 bits (although it's 32 on PC).\n //\n // Allocating it on the stack as a fixed size avoids a slow memory and page allocation.\n // Note that we're over allocating the size here so that we can have an extra zero\n // padding before the actual DP matrix begins, this allows us to not have to check\n // for the left edge in the inner loop, avoiding a costly branch as long as this pad\n // is set to zero which it always will be as we never over write it.\n unsigned long dp[2 * (w_max + 1)] = {0};\n\n // We take two pointers into the above buffer so we can alternate them easily.\n unsigned long* dp_curr = &amp;dp[0];\n unsigned long* dp_prev = &amp;dp[w + 1];\n\n // This is the starting condition. It's stored in the dp_curr[1] (remember, \n // after the pad) it'll then be swapped into dp_prev[1] when entering the loop\n // then when computing dp_curr[1] = dp_curr[0] + dp_prev[1] it'll be correctly\n // transfered to the starting square without additional branching in the inner loop.\n dp_curr[1] = 1;\n\n for (unsigned long i = 0; i &lt; h; i++) {\n // Re-use old previous as new current and old current as new previous.\n // No need to clear the new current as we'll overwrite it below anyway\n // and we'll never access non-overwritten values.\n std::swap(dp_curr, dp_prev);\n for (unsigned long j = 1; j &lt;= w; j++) {\n char c;\n std::cin &gt;&gt; c;\n if (c == '#') {\n dp_curr[j] = 0; // No ways to reach a wall\n } else {\n // This is where the magic happens. Because we use two rows and we initialized\n // both rows to 0, (ignoring the starting condition) then we do not need to\n // special case the first row to avoid out of bounds access.\n // In the same way, because we added a 0 padd to the left and start at j=1,\n // j-1 will always be valid and when j==1, dp_curr[j-1] is aways 0 thanks to\n // the pad, this again allows us to avoid bounds checking in the inner most loop.\n dp_curr[j] = (dp_curr[j - 1] + dp_prev[j]) % k;\n }\n }\n }\n // Of course, when we're done, the result is stored in the current DP row\n // at the last position and we need only to print it.\n std::cout &lt;&lt; dp_curr[w] &lt;&lt; std::endl;\n}\n\n</code></pre>\n<p>I do believe that it will be hard to find a solution that is notably faster than the code presented above without doing something clever with I/O. It uses no dynamic memory (other than what iostreams and the runtime needs), and performs minimal branching and a good compiler could eliminate the inner branch totally and use conditional move if it makes sense.</p>\n<p>Note for the curious, we use so little memory that everything will be permanently resident in the L1 data and instruction cache on the CPU and that there is so little branching that the CPU doesn't stall on misspredicted branches that often, this allows the very rapid computation of the result.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T01:22:03.857", "Id": "256554", "ParentId": "256303", "Score": "2" } } ]
{ "AcceptedAnswerId": "256554", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T17:21:25.120", "Id": "256303", "Score": "-1", "Tags": [ "c++", "performance", "dynamic-programming" ], "Title": "Grid Dynamic Programming" }
256303
<p>I have been doing testing to find the most efficient way to display numpy array images to a HTML, CSS, JS UI (specifically, with CEF Python).</p> <p>I mainly used the method explained <a href="https://stackoverflow.com/questions/61411456/receive-png-file-via-ajax-and-draw-to-canvas-with-flask-server?rq=1">here</a> to do the numpy array -&gt; html canvas code.</p> <p>In case anyone is wondering, this test code is based on the boilerplate code provided by <a href="https://github.com/Andrew-Shay/Neuron" rel="nofollow noreferrer">https://github.com/Andrew-Shay/Neuron</a> and the cef python stuff is exactly the same as in that repository.</p> <p>The goal here is to be able to edit images from the localhost web UI with a python backend for a desktop application. <strong>(Please note that this isn't a webapp -the goal is to be a desktop application using CEF Python)</strong></p> <p><em><strong>The main thing is that to display even a 2MB image it is quite slow.</strong></em> It seems that from my tests, the main bottleneck (understandably) is the transfer between python and js over localhost.</p> <p>So, what would be the most efficient way to do the transfer and should I use Flask's server to do this or use something else? <em>I am open to doing this another way as well, so don't be afraid to suggest a better alternative to this.</em></p> <p>Also, I would prefer to eliminate Python-Pillow (since it doesn't support 16-bit -which is required) and the need to specify the image format (JPEG, PNG, etc) from this code, if possible.</p> <p><em>app.py</em></p> <pre class="lang-py prettyprint-override"><code># Flask app that handles application logic import base64 import json import io import time from flask import Flask from flask import render_template from flask import request from neuron import get_root_path import numpy as np from PIL import Image import OpenImageIO as oiio from OpenImageIO import ImageBuf, ImageSpec, ImageBufAlgo # Put this here to simulate caching img_input = oiio.ImageInput.open(&quot;test.jpg&quot;) image = img_input.read_image(format=&quot;uint8&quot;) app = Flask(__name__, static_folder=get_root_path('static'), template_folder=get_root_path('templates')) @app.before_request def before_request(): pass @app.teardown_request def teardown_request(exception): pass @app.route('/', methods=['GET']) def index(): json_data = {} return render_template('index.html', json_data=json_data) @app.route('/get_img/', methods=['GET']) def get_image(): start_time = time.time() # Test flipping the image to simulate image editing img = np.fliplr(image) # Convert to base64 im = Image.fromarray(img.astype(&quot;uint8&quot;), mode='RGB') rawBytes = io.BytesIO() im.save(rawBytes, &quot;JPEG&quot;) rawBytes.seek(0) encoded_string = base64.b64encode(rawBytes.read()) print(time.time() - start_time) return encoded_string if __name__ == '__main__': app.run(host=&quot;localhost&quot;, port=5000, debug=True, use_reloader=True) </code></pre> <p><em>index.html</em></p> <pre class="lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt; &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt; &lt;meta name=&quot;author&quot; content=&quot;&quot;&gt; &lt;title&gt;Starter Template for Bootstrap&lt;/title&gt; &lt;!-- Bootstrap core CSS --&gt; &lt;link href=&quot;{{ url_for('static', filename='css/bootstrap.css') }}&quot; rel=&quot;stylesheet&quot;&gt; &lt;!-- Custom styles for this template --&gt; &lt;link href=&quot;{{ url_for('static', filename='css/starter-template.css') }}&quot; rel=&quot;stylesheet&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;nav class=&quot;navbar navbar-expand-md navbar-dark bg-dark fixed-top&quot;&gt; &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;Navbar&lt;/a&gt; &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarsExampleDefault&quot; aria-controls=&quot;navbarsExampleDefault&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt; &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt; &lt;/button&gt; &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarsExampleDefault&quot;&gt; &lt;ul class=&quot;navbar-nav mr-auto&quot;&gt; &lt;li class=&quot;nav-item active&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Home &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Link&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item&quot;&gt; &lt;a class=&quot;nav-link disabled&quot; href=&quot;#&quot;&gt;Disabled&lt;/a&gt; &lt;/li&gt; &lt;li class=&quot;nav-item dropdown&quot;&gt; &lt;a class=&quot;nav-link dropdown-toggle&quot; href=&quot;http://example.com&quot; id=&quot;dropdown01&quot; data-toggle=&quot;dropdown&quot; aria-haspopup=&quot;true&quot; aria-expanded=&quot;false&quot;&gt;Dropdown&lt;/a&gt; &lt;div class=&quot;dropdown-menu&quot; aria-labelledby=&quot;dropdown01&quot;&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;Action&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;Another action&lt;/a&gt; &lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot;&gt;Something else here&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;form class=&quot;form-inline my-2 my-lg-0&quot;&gt; &lt;input class=&quot;form-control mr-sm-2&quot; type=&quot;text&quot; placeholder=&quot;Search&quot; aria-label=&quot;Search&quot;&gt; &lt;button class=&quot;btn btn-outline-success my-2 my-sm-0&quot; type=&quot;submit&quot;&gt;Search&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/nav&gt; &lt;main role=&quot;main&quot; class=&quot;container&quot;&gt; &lt;div class=&quot;starter-template&quot;&gt; &lt;h1&gt;Bootstrap starter template&lt;/h1&gt; &lt;p class=&quot;lead&quot;&gt;Use this document as a way to quickly start any new project.&lt;br&gt; All you get is this text and a mostly barebones HTML document.&lt;/p&gt; &lt;button class=&quot;btn btn-success&quot; onclick=&quot;loadImage()&quot;&gt;Update Image&lt;/button&gt; &lt;canvas id=&quot;canvas&quot; width=&quot;400&quot; height=&quot;400&quot; style=&quot;border:1px solid #d3d3d3;&quot;&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;/main&gt;&lt;!-- /.container --&gt; &lt;script&gt; function loadImage() { var ajaxRequest; try { ajaxRequest = new XMLHttpRequest(); } catch (e) { alert(&quot;Server could not be reached.&quot;); return false; } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function() { if (ajaxRequest.readyState == 4) { // Get the data from the server's response var response = ajaxRequest.responseText; onDisplayImg(response); } } ajaxRequest.open(&quot;GET&quot;, &quot;/get_img&quot;, true); ajaxRequest.send(); } function onDisplayImg(input) { var canvas = document.getElementById(&quot;canvas&quot;); var ctx = canvas.getContext(&quot;2d&quot;); var image = new Image(); image.onload = function() { ctx.drawImage(image, 0, 0); }; image.src = &quot;data:image;base64,&quot;.concat(input); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T17:36:45.113", "Id": "256304", "Score": "0", "Tags": [ "javascript", "python-3.x", "json", "numpy", "flask" ], "Title": "Optimized method of transfering numpy image arrays over localhost to web-tech UI for desktop UI" }
256304
<p>My java code for CSES Introductory problem Number Spiral gives TLE for large inputs, like</p> <p>Input :</p> <p>100000<br /> 170550340 943050741<br /> 121998376 943430501<br /> 689913499 770079066<br /> 586095107 933655238 …<br /> (First line/number being the number of inputs)</p> <p>My code is as below:</p> <pre><code>import java.util.*; public class numberSpiral { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long testN = scanner.nextLong(); long r=0,c=0; while(testN-- &gt; 0){ r = scanner.nextLong(); c = scanner.nextLong(); if (c &gt; r) { if (c % 2 == 0) { System.out.println(((c - 1) * (c - 1)) + 1 + (r - 1)); } else System.out.println(((c) * (c)) - (r - 1)); } else { if(r % 2 == 0){ System.out.println(((r) * (r)) - (c - 1)); } else System.out.println(((r - 1) * (r - 1)) + 1 + (c - 1)); } } } } </code></pre> <p>It works for small inputs. I can't figure out how to optimize it better to reduce time. Time limit is: 1.00 s</p>
[]
[ { "body": "<p>I assume you refer to <a href=\"https://cses.fi/problemset/task/1071/\" rel=\"nofollow noreferrer\">https://cses.fi/problemset/task/1071/</a> .\nYour Algorithm itself is fine as far is i can tell.</p>\n<p>The Problem is the large amount of inputs that need to need to be read(Testcases=100000), which Scanner cant provide within the 1s time limit.\nA BufferedReader should offer the performance needed for this.(See <a href=\"https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/</a> for more information).\nThe same might apply to System.out.println in which case it would be better to use a BufferedWriter</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T23:17:31.117", "Id": "256316", "ParentId": "256305", "Score": "3" } }, { "body": "<p>usually calculation is faster than branching, so you may also try this:</p>\n<pre><code> if (c &gt; r) {\n int even = c % 2\n System.out.println(((c - 1*even) * (c - 1*even)) + 1*even + (r - 1));\n } else {\n int odd = 1-(r % 2)\n System.out.println(((r - 1*odd) * (r - 1*odd)) + 1*odd + (c - 1));\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T19:00:53.967", "Id": "256346", "ParentId": "256305", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T17:41:17.537", "Id": "256305", "Score": "2", "Tags": [ "java", "performance", "time-limit-exceeded" ], "Title": "CSES - Number Spiral - Java TLE" }
256305
<p>Please can you check if the code I have written follows 4 rules of OOP well enough, if there is anything that could be improved or is just wrong I am happy to change (very new to C# sorry if it's awful).</p> <p>The code implements the &quot;Dhond't Method&quot; which is a polling system. <a href="https://www.bbc.co.uk/news/uk-politics-27187434" rel="nofollow noreferrer">https://www.bbc.co.uk/news/uk-politics-27187434</a></p> <p>MAIN</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Voting_System { class Program { static void Main(string[] args) { // Establish the file path string filepath = @&quot;C:\Users\mathe\OneDrive\Documents\All Assignments\Voting System\input\data.txt&quot;; // Store values in a list of string List&lt;string&gt; file = File.ReadAllLines(filepath).ToList(); // Puts each party into a list of Party and display Name + Votes List&lt;Party&gt; partys = new List&lt;Party&gt;(); foreach (string line in file) { string[] items = line.Split(','); Party p = new Party(items[0], Convert.ToInt32(items[1])); partys.Add(p); } // Ask user for thresh hold and also calculate total votes Console.WriteLine(&quot;What is the threshold for partys (%) (round number) ?&quot;); int thresHold = Convert.ToInt32(Console.ReadLine()); // Ask user how many seats they want to allocate Console.WriteLine(&quot;\nHow many seats do you want to allocate in total? (round number)&quot;); int seatsCount = Convert.ToInt32(Console.ReadLine()); // Calcutions for Dhon't method int totalVotes = SumOfVotes(partys); DisplayPercentageVotes(partys, thresHold, totalVotes); CalculateDhondt(partys, seatsCount); DisplayWinningParties(partys); Console.ReadKey(); } // Print out all partys and there properties to user private static void DisplayWinningParties(List&lt;Party&gt; partys) { foreach (Party p in partys) { if (p.Seats &gt; 0) { Console.WriteLine(p); } } } // Find total votes private static int SumOfVotes(List&lt;Party&gt; partys) { int totalVotes = 0; foreach (Party p in partys) { totalVotes += p.Votes; } Console.WriteLine($&quot;\nTOTAL No OF COMBINED VOTES FOR ALL PARTIES 2020 : {totalVotes}\n&quot;); return totalVotes; } // Displays percent of votes for each party private static void DisplayPercentageVotes(List&lt;Party&gt; partys, int threshold, int totalvotes) { // Displays percent of votes for each party Console.WriteLine($&quot;PARTIES THAT MEET THE {threshold}% INPUTTED THRESHOLD:&quot;); foreach (Party p in partys) { if (p.PercentOfVotes(totalvotes) &gt; threshold) { Console.WriteLine($&quot;{p.Name} has {Math.Round(p.PercentOfVotes(totalvotes),2)} % of total votes.&quot;); } } } // Method to do the main caclutions of the Dhon't method private static void CalculateDhondt(List&lt;Party&gt; partys, int seatsCount) { // Find intial party with highest votes Party biggestVote = partys.Aggregate((v1, v2) =&gt; v1.Votes &gt; v2.Votes ? v1 : v2); biggestVote.Seats += 1; biggestVote.DivideParty(); // Keep looping through partys and applying dhond't method until all seats are taken int totalSeatsCount = 0; while (totalSeatsCount != seatsCount) { Party biggestVotes = partys.Aggregate((v1, v2) =&gt; v1.NewVotes &gt; v2.NewVotes ? v1 : v2); biggestVotes.Seats += 1; biggestVotes.DivideParty(); foreach (Party p in partys) { totalSeatsCount += p.Seats; } // If we havent reached desired seats count reset the total seats variable if (totalSeatsCount != seatsCount) { totalSeatsCount = 0; } } Console.WriteLine($&quot;\nWE HAVE {seatsCount} SEATS ALLOCATED:&quot;); } } } </code></pre> <p>PARTY CLASS</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Voting_System { class Party { // properties for each party public string Name { get; private set; } public int Votes { get; private set; } public int NewVotes { get; set; } public int Seats { get; set; } // Constructor for party class public Party(string name, int votes) { Name = name; Votes = votes; NewVotes = votes; } // Returns percentage of votes for your party public double PercentOfVotes(double totalVotes) =&gt; (Votes / totalVotes) * 100; // When ever you print the object of this class return this public override string ToString() { return $&quot;Name: {Name} Votes: {Votes} Seats: {Seats}&quot;; } // Applies Dhond't method of division public void DivideParty() { NewVotes = Votes / (1 + Seats); } } } </code></pre> <p>DATA INPUT FILE</p> <pre><code>Brexit Party,452321,BP1,BP2,BP3,BP4,BP5; Liberal Democrats,203989,LD1,LD2,LD3,LD4,LD5; Labour,164682,LAB1,LAB2,LAB3,LAB4,LAB5; Conservative,126138,CON1,CON2,CON3,CON4,CON5; Green,124630,GR1,GR2,GR3,GR4,GR5; UKIP,58198,UKP1,UKP2,UKP3,UKP4,UKP5; Change UK,41117,CUK1,CUK2,CUK3,CUK4,CUK5; Independent Network,7641,INET1,INET2,INET3,INET4,INET5; Independent,4511,IND1; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T08:01:44.637", "Id": "506026", "Score": "0", "body": "What do mean by this: *4 rules of encapsulation* ? Did you mean the four principles / pillars of Object Oriented Programming?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T09:01:09.050", "Id": "506033", "Score": "0", "body": "@PeterCsala yes do you think ive included the pillars well enough? if not any improvement tips? thanks alot" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T09:54:05.450", "Id": "506034", "Score": "0", "body": "Are you sure that you have applied any of the principles? This lengthy `Main` function does not indicate that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T10:11:53.810", "Id": "506035", "Score": "0", "body": "Please read [this article](https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/intro-to-csharp/object-oriented-programming)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T11:08:41.693", "Id": "506043", "Score": "0", "body": "@PeterCsala I have updated the main would this be better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T11:49:39.627", "Id": "506046", "Score": "1", "body": "Can you add the Party class please" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T14:20:25.223", "Id": "506058", "Score": "0", "body": "@AlanT Yeh sorry i added it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T14:24:10.160", "Id": "506059", "Score": "0", "body": "@PeterCsala Thanks for the explaination,so for me should i make a static method to sort out the file path, and another static method to put each party into a list of parties?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T14:36:13.300", "Id": "506061", "Score": "0", "body": "From your algorithm implementation perspective are these relevant? Probably not. From the algorithm point of view what matter is to receive the already parsed data. It does not matter that it comes from a json file or a database or via UDP messages. These are implementation details, so they should be handled inside the object itself." } ]
[ { "body": "<p>In this review I'll focus only on <strong>Abstraction</strong> and <strong>Encapsulation</strong> because the other two is not applicable in this scenario.</p>\n<hr />\n<p>Whenever we are talking about OOP then we usually refer to well-defined objects (with known responsibilities) which are communicating with each other to solve a greater problem.</p>\n<h3>Abstraction</h3>\n<p>We are decomposing the original problem into many smaller chunks. These can be solved either independently or via collaboration. If you implement a specific algorithm then usually there is a coordinator / orchestrator which conducts the communication between the objects.</p>\n<p>This coordinator role (logic) can reside inside your <code>Main</code> method:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main(string[] args)\n{\n var parameters = DhondtMethodAlgorithmParameters.GatherFromConsole();\n var inputData = DhondtMethodAlgorithmInput.LoadFromFile(inputFilePath);\n \n var algorithm = new DhondtMethodAlgorithm(parameters, inputData);\n var results = algorithm.PerformCalculation();\n \n DisplayResults(results);\n}\n</code></pre>\n<ul>\n<li>Here we have 3 different stages:\n<ul>\n<li>Gathering data and converting them to the desired shape</li>\n<li>Setting up the algorithm and calling it</li>\n<li>Showing the calculation's result</li>\n</ul>\n</li>\n</ul>\n<p>We have divided the original problem into smaller chunks where each does have a well-defined scope and responsibility. We have to continue this split until we reach a point from which we can't further divide.</p>\n<p>This exercise will help us to identify the objects and their exposed behavior.</p>\n<h3>Encapsulation</h3>\n<p>In order to properly use encapsulation we have to hide our implementation details behind the abstraction. In other words the abstraction should guarantee that the data is consistent all the time from the consumer point of view.</p>\n<p>For example, we are not creating an <code>DhondtMethodAlgorithmParameters</code> instance if the user provided data is malformed. We can early exit with an exception or we can retry to gather again the parameters from the user. Whenever we have passed the <code>GatherFromConsole</code> factory method then we can be sure that the returned <code>DhondtMethodAlgorithmParameters</code> contains only valid data.</p>\n<p>Same applies for <code>LoadFromFile</code>. There can be a lot of different problem (like the file does not exist, the data is corrupted, etc.) that the code may or may not tackle. But from the Abstraction and Encapsulation point of view whenever the function returns with the parsed and validated input data (<code>DhondtMethodAlgorithmInput</code> instance) then we can be sure that it is in a consistent state.</p>\n<p>From an algorithm point of view the encapsulation can mean that its input and parameters are immutable after creation. It does not expose any method or member with which the consumer of the algorithm instance can change the underlying data.</p>\n<hr />\n<p>So, in short:</p>\n<ol>\n<li>Identify objects and their responsibilities &lt;&lt; Abstractions</li>\n<li>Expose only those members that are needed for collaboration &lt;&lt; Encapsulation</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T12:41:59.260", "Id": "256334", "ParentId": "256309", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T18:22:50.890", "Id": "256309", "Score": "0", "Tags": [ "c#", "object-oriented", "classes" ], "Title": "C# code for Dhond't voting method UK Parliament" }
256309
<p>I am not doing anything fancy so not sure if there are any tricks to make it faster.</p> <p>It's a progress bar where I draw some numeric text on top. I only draw 1 pixel height image and then resize it. But not sure if there are better ways.</p> <p>Here is the code:</p> <pre><code> void DrawProgressBar ( PictureBox pb, int ratio, bool reverse, params string [ ] percentages ) { Color color1 = this.DarkRed; Color color2 = this.DarkGreen; if ( reverse ) { color1 = this.DarkGreen; color2 = this.DarkRed; } Bitmap bmp = new Bitmap ( 100, 1 ); using ( Graphics g = Graphics.FromImage ( bmp ) ) using ( SolidBrush brush = new SolidBrush ( color1 ) ) g.FillRectangle ( brush, 0, 0, 100, 1 ); for ( int i = 0 ; i &lt; ratio ; ++i ) bmp.SetPixel ( i, 0, color2 ); Bitmap result = new Bitmap ( pb.Width + 2, pb.Height ); Graphics g2 = Graphics.FromImage ( result ); g2.InterpolationMode = InterpolationMode.NearestNeighbor; g2.DrawImage ( bmp, 0, 0, result.Width, result.Height + 23 ); StringFormat strformat = new StringFormat ( ); strformat.Alignment = StringAlignment.Center; strformat.LineAlignment = StringAlignment.Center; SolidBrush br = new SolidBrush ( Color.White ); if ( percentages.Length &gt; 1 ) { decimal nratio = ratio / 100.0m; int w = ( int ) ( result.Width * nratio ); Rectangle rect = new Rectangle ( 0, 0, w, result.Height ); Rectangle rect2 = new Rectangle ( w, 0, ( int ) ( result.Width - w ), result.Height ); if ( ratio &gt; 5 ) g2.DrawString ( percentages [ 0 ], this.dataListView.Font, br, rect, strformat ); if ( 100 - ratio &gt; 5 ) g2.DrawString ( percentages [ 1 ], this.dataListView.Font, br, rect2, strformat ); } else { Rectangle rect = new Rectangle ( 0, 0, result.Width, result.Height ); g2.DrawString ( percentages [ 0 ], this.dataListView.Font, br, rect, strformat ); } pb.Image = result; } </code></pre> <p><a href="https://i.stack.imgur.com/GlCMI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GlCMI.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T21:05:49.693", "Id": "506001", "Score": "0", "body": "The answer could be funny: the better way is drop Winforms and use WPF :) Btw, you may calculate the final sizes of the image, rectangles, etc. to avoid resizing. Double Buffering may help too but i'm not sure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T21:08:39.123", "Id": "506002", "Score": "0", "body": "A possible tip: What version of .NET and Visual Studio are you using? I see ancient code style formatting. 2015? Consider to update to the latest one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T06:49:41.513", "Id": "506021", "Score": "0", "body": "I am using the latest one in the framework, 4 or 5? VS latest also. But the code itself was old." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T06:49:54.257", "Id": "506022", "Score": "0", "body": "@aepot: would it be faster in WPF?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T08:09:37.870", "Id": "506028", "Score": "1", "body": "Faster than what? WPF natively supports customising UI. It can be done purely in XAML markup with zero C# code lines. Btw, native `ProgressBar` already sopports fg and bg colors, to draw number just add `TextBlock` above it. It's enough fast. WPF uses DirectX to draw the UI. And finally, native transparency, or semi-transparency for everything supported. XAML markup is something like HTML markup. And more [effects available](https://ru.stackoverflow.com/a/1187535/373567) (Russian SO link)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T10:52:25.520", "Id": "506036", "Score": "0", "body": "@aepot Winforms, because this is winforms code. Yes I used wpf before but not sure how it would fare for this exact thing. I will see if I can configure ProgressBar to look the same. Because I need the same look. As for zero C# code, how can that be done? I see in the link there is a progressbar, is he just adding glow or making the entire thing in WPF? I might convert the entire thing to WPF. I just need to see how much work it will be for me. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T10:57:10.543", "Id": "506037", "Score": "1", "body": "`<Grid Width=\"...\" Height=\"...\"><ProgressBar Foreground=\"...\" Background=\"...\"/><TextBlock Text=\"...\" Foreground=\"...\" FontFamily=\"...\"/></Grid>` That's it. To make it manageable from C# code, say hello to [Data Bindings](https://docs.microsoft.com/en-us/dotnet/desktop/wpf/data/data-binding-overview?view=netdesktop-5.0)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T10:57:39.510", "Id": "506038", "Score": "0", "body": "Also another thing is I am aligning these progress bar bitmaps in code, but in WPF can I place the progressbar directly inside a listview cell? That would help me a lot also" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T10:59:09.583", "Id": "506039", "Score": "0", "body": "Also in my Winforms app because there are a lot of updates happening and some updates are UI based, it's laggy to move the UI because of this. Not sure how WPF handles the UI updates/binding changes so the UI is not \"locked\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T11:00:39.263", "Id": "506040", "Score": "1", "body": "In WPF you can put anything inside anything. In XAML. `<ListView><ListView.ItemTemplate><DataTemplate>...your controls to make an item in UI...</DataTemplate></ListView.ItemTemplate></ListView>`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T11:02:50.600", "Id": "506041", "Score": "0", "body": "Thanks I will look into converting my app into WPF today. But I remember back when I was making some WPF apps, to make a simple alternating colored listview, you had to subclass the default listview or something. Is this still the case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T11:05:06.800", "Id": "506042", "Score": "1", "body": "Read about what is MVVM programming pattern for WPF first (it's easy). And follow MVVM to rewrite the app. When you catch the idea, you'll find that Winforms was a pain." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T11:49:57.947", "Id": "506047", "Score": "0", "body": "Possibly useful for Winforms render performance - https://stackoverflow.com/a/3718648/12888024" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T17:44:14.437", "Id": "506074", "Score": "0", "body": "Have you tried filling 2 rectangles instead of resizing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T19:45:41.383", "Id": "506083", "Score": "0", "body": "@D.Jurcau No, how does it work? Like start with solid color and then fill an area?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T20:32:46.887", "Id": "256313", "Score": "0", "Tags": [ "c#", "performance", ".net", "graphics" ], "Title": "Is there a way to optimize this graphics/bitmap drawing code in C#?" }
256313
<p>the question is <a href="https://sqlpad.io/questions/37/most-popular-movie-category/" rel="nofollow noreferrer">here</a></p> <blockquote> <pre><code> Return the name of the category that has the most films. </code></pre> </blockquote> <p>There are 2 databases - film_category:</p> <pre><code>film_id category_id last_update 1 6 2017-02-15 10:07:09-08 2 11 2017-02-15 10:07:09-08 3 6 2017-02-15 10:07:09-08 4 11 2017-02-15 10:07:09-08 5 8 2017-02-15 10:07:09-08 </code></pre> <p>and category:</p> <pre><code>category_id name last_update 1 Action 2017-02-15 09:46:27-08 2 Animation 2017-02-15 09:46:27-08 3 Children 2017-02-15 09:46:27-08 </code></pre> <p>I have made it work, but I feel there is a way to refactor without 'limit'</p> <pre><code> select category.name from film_category inner join category on category.category_id = film_category.category_id group by category.name order by count(film_category.film_id) desc limit 1 </code></pre> <p>I dont know how to write it without 'limit 1'</p> <pre><code>select category.name from film_category inner join category on category.category_id = film_category.category_id group by category.name having count(film_category.film_id) &gt; (select max().... ) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-27T12:22:02.300", "Id": "506435", "Score": "2", "body": "The fact that no one has (yet) come up with a better query, probably indicates that yours is already quite good. Nothing wrong with a limit in a query." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-27T19:31:05.253", "Id": "506454", "Score": "0", "body": "@KIKOSoftware thx u so much.. for some reason i was thinking that using limit is quick and dirty ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-27T19:48:57.483", "Id": "506455", "Score": "2", "body": "Oh no, sorting and taking a `LIMIT 1` is just as valid an operation as any other. If you think about it, the `MAX()` function has to do, broadly speaking, the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-28T07:45:31.417", "Id": "506482", "Score": "0", "body": "@KIKOSoftware when i was doing some sql practice exercise - i was shown this 'pattern' that involved subquery calculating max and using just limit instead seemed to be 'quick and dirty' , ok thx for clarifying it for me" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-21T22:10:38.830", "Id": "256315", "Score": "0", "Tags": [ "sql", "mysql" ], "Title": "how to rewrite sql query with subquery to find max element without using limit?" }
256315
<p>I am styling my react native component according to some conditions, here the code, The question is how do I make this cleaner? functional style?</p> <pre><code>const configColors = (isSingle, isDarkMode) =&gt; { let colors = {}; if (isDarkMode){ colors = { ...colors, configAxisLabelColor : Colors.white, configAxisGridColor : Colors.gridLineGray } }else{ colors = { ...colors, configAxisLabelColor : Colors.lineGray, configAxisGridColor : Colors.transparent } } if (isSingle &amp;&amp; !isDarkMode) { return colors = { ...colors, configAxisColor: Colors.transparent, configLineColor: Colors.lineGreen, configTooltipBackground: Colors.lineGreen, } } if (isSingle &amp;&amp; isDarkMode) { return colors = { ...colors, configAxisColor: Colors.white, configLineColor: Colors.lineBlue, configTooltipBackground: Colors.lineBlue, } } if (!isSingle &amp;&amp; !isDarkMode) { return colors = { ...colors, configAxisColor: Colors.lightBarGray, configLineColor: Colors.lineGray, configTooltipBackground: Colors.lineBlue, } } } </code></pre> <p>Thanks in advance!</p>
[]
[ { "body": "<p>I think what you are looking for is a ternary operator.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const configColors = (isSingle, isDarkMode) =&gt; {\n return {\n configAxisLabelColor : isDarkMode ? Colors.white : Colors.lineGray,\n configAxisGridColor : isDarkMode ? Colors.gridLineGray : Colors.transparent\n configAxisColor: isSingle ? (isDarkMode ? Colors.white: Colors.transparent) : Colors.lightBarGray\n // so on\n }\n</code></pre>\n<p>Another option that reads better could be to create a separate config for each possible combination you want to return.</p>\n<pre><code>const configColors = (isSingle, isDarkMode) =&gt; {\n\n const configSingleDark = {\n configAxisLabelColor : Colors.white,\n configAxisGridColor : Colors.gridLineGray\n }\n\n if (isSingle &amp;&amp; isDarkMode) {\n return configSingleDark\n } else if (isSingle &amp;&amp; !isDarkMode) {\n return configSingleLight\n } else {\n //\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-05T23:29:05.700", "Id": "256783", "ParentId": "256318", "Score": "1" } } ]
{ "AcceptedAnswerId": "256783", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T00:28:49.867", "Id": "256318", "Score": "0", "Tags": [ "react.js", "react-native" ], "Title": "react native refactor theme handling" }
256318
<p>I have recently tried converting a singly linked list from a C program into my own python program. I have tested the code myself but I am still unsure if the program has been converted properly. I would like someone to peer review my code to see if there are any errors in methodology, too many methods, any missing methods, etc.</p> <p>I have tried implementing some of my own singly linked list operations based from the advice from this website: <a href="https://afteracademy.com/blog/types-of-linked-list-and-operation-on-linked-list" rel="nofollow noreferrer">https://afteracademy.com/blog/types-of-linked-list-and-operation-on-linked-list</a></p> <p>The original C Program: <a href="https://people.eng.unimelb.edu.au/ammoffat/ppsaa/c/listops.c" rel="nofollow noreferrer">https://people.eng.unimelb.edu.au/ammoffat/ppsaa/c/listops.c</a></p> <p>My own python code:</p> <pre><code>class Node(): # Node for a single linked list def __init__(self, data): self.data = data self.next = None class LinkedList(): def __init__(self): self.head = None self.foot = None def length(self): '''Returns the length of a linked list.''' current_node = self.head node_total = 0 while (current_node != None): node_total += 1 current_node = current_node.next return node_total def is_empty_list(self): '''Checks if a linked list is empty.''' return self.head == None def stack_insert(self, data): '''Inserts a node at the HEAD of the list; LIFO (Last In, First Out).''' new_node = Node(data) # Makes new_node.next point to next node (defualt None if 1st insertion) new_node.next = self.head # Makes the HEAD of linked list point to new node self.head = new_node if (self.foot == None): # First insertion into linked list; node becomes HEAD &amp; FOOT self.foot = new_node def queue_append(self, data): '''Appends a node at the FOOT of the list; FIFO (First In, First Out).''' new_node = Node(data) if (self.head == None): # First insertion into linked list; node becomes HEAD &amp; FOOT self.head = self.foot = new_node else: # Makes the original last node point to the newly appended node self.foot.next = new_node # Makes the newly appended list as the official FOOT of the linked list self.foot = new_node def insert_after(self, data, index): '''Inserts a NEW node AFTER a specific node indicated by index.''' # Need to ensure provided index is within range if (index &lt; 0): print(&quot;ERROR: 'insert_after' Index cannot be negative!&quot;) return elif (index &gt; (self.length() -1)): print(&quot;ERROR: 'insert_after' Index exceeds linked list range!&quot;) return # Use stack_insert to insert as first item elif (self.is_empty_list()) or (index == 0): self.stack_insert(data) return # Use queue_insert to append as last item elif (index == (self.length() -1)): self.queue_append(data) return new_node = Node(data) prior_node = self.head current_node = self.head search_index = 0 # Keep traversering through nodes until desired node while (search_index != index): prior_node = current_node current_node = current_node.next search_index += 1 # Makes prior node is point to target node prior_node = current_node # Makes current node point to the node AFTER target node (default None of last node) current_node = current_node.next # Makes target node point to newly added node prior_node.next = new_node # Makes newly added node point to original node that WAS AFTER target node new_node.next = current_node def delete_head(self): '''Deletes the HEAD node.''' # Linked list is empty if self.is_empty_list(): return old_head = self.head # Adjusts the head pointer to step past original HEAD self.head = self.head.next if (self.head == None): # The only node just got deleted self.foot = None def delete_foot(self): '''Deletes the FOOT node.''' # Linked list is empty if self.is_empty_list(): return old_foot = self.foot prior_node = self.head current_node = self.head # Need to keep cycling until final node is reached while (current_node.next != None): prior_node = current_node current_node = current_node.next # Adjust newly FOOT node to point to nothing prior_node.next = None # Makes linked list forget about original FOOT node self.foot = prior_node def delete_node(self, index): '''Deletes a target node via index.''' # Linked list is empty if self.is_empty_list(): return # Need to ensure index is within proper range elif (index &lt; 0): print(&quot;ERROR: 'delete_node' Index cannot be negative!&quot;) return elif (index &gt; (self.length() -1)): print(&quot;ERROR: 'delete_node' Index exceeds linked list range&quot;) return prior_node = self.head current_node = self.head search_index = 0 # Keep travsersing though nodes until desired node while (search_index != index): prior_node = current_node current_node = current_node.next search_index += 1 # Adjusts node PRIOR to target node to point to the node the AFTER target node prior_node.next = current_node.next def update_node(self, new_data, index): '''Updates target node data via index.''' # Linked list is empty if self.is_empty_list(): print(&quot;ERROR: 'update_node' Linked list is empty; no node data to update!&quot;) return # Need to ensure index is within proper range elif (index &lt; 0): print(&quot;ERROR: 'update_node' Index cannot be negative!&quot;) return elif (index &gt; (self.length() -1)): print(&quot;ERROR: 'update_node' Index exceeds linked list range!&quot;) current_node = self.head search_index = 0 # Keep traversing through nodes until desired node while (search_index != index): current_node = current_node.next search_index += 1 # Can now change data current_node.data = new_data def get_node_data(self, index): '''Extracts that data from a specific node via index.''' # Linked list is empty if self.is_empty_list(): print(&quot;ERROR: 'update_node' Linked list is empty; no node data to update!&quot;) return # Need to ensure index is within proper range elif (index &lt; 0): print(&quot;ERROR: 'update_node' Index cannot be negative!&quot;) return elif (index &gt; (self.length() -1)): print(&quot;ERROR: 'update_node' Index exceeds linked list range!&quot;) # Index matches HEAD or FOOT if (index == 0): return self.head.data elif (index == (self.length() -1)): return self.foot.data current_node = self.head search_index = 0 # Keep traversing though nodes until desired node while (search_index != index): current_node = current_node.next search_index += 1 return current_node.data </code></pre>
[]
[ { "body": "<p>Your code looks un-Pythonic because you are using methods like <code>length</code> rather dunder methods like <code>__len__</code>.</p>\n<h2>Node</h2>\n<p>Before that we can change <code>Node</code> to use <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\"><code>dataclasses</code></a>. <code>dataclasses</code> will automatically give your class some boiler-plate, like <code>__init__</code> and <code>__repr__</code>. To use <code>dataclasses.dataclass</code> you need to type your class. To type attributes we can use <code>attr: type</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Any\n\nclass Node:\n data: Any\n next: &quot;Node&quot;\n # ...\n</code></pre>\n<p>There are two important parts to note;</p>\n<ul>\n<li>you should try not to use <code>Any</code> as doing so destroys type information.\nHere we can instead use <a href=\"https://docs.python.org/3/library/typing.html#typing.TypeVar\" rel=\"nofollow noreferrer\"><code>typing.TypeVar</code></a> and <a href=\"https://docs.python.org/3/library/typing.html#typing.Generic\" rel=\"nofollow noreferrer\"><code>typing.Generic</code></a>. And</li>\n<li>we have encased the type <code>Node</code> in a string. Before Python 3.10 type annotations are eagerly evaluated. Since we're using the name <code>Node</code> before <code>Node</code> has been assigned, if we didn't the type would fail to resolve.\nWe can use <code>from __future__ import annotations</code> to make Python use lazy evalutaion automatically from Python 3.7+.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\n\nfrom typing import Generic, TypeVar\n\nT = TypeVar(&quot;T&quot;)\n\nclass Node(Generic[T]):\n data: T\n next: Node\n # ...\n</code></pre>\n<p>We can now change the class to use <code>dataclasses.dataclass</code>. Since we want to be able to not provide <code>next</code> in the <code>__init__</code> we can assign <code>None</code> to <code>next</code>, so that <code>next</code> defaults to <code>None</code> if nothing is provided.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import dataclasses\n\n@dataclasses.dataclass\nclass Node(Generic[T]):\n data: T\n next: Node = None\n\nll = Node(0, Node(1)) # example usage\nprint(ll)\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>Node(data=0, next=Node(data=1, next=None))\n</code></pre>\n<p>The nice output helps makes debugging much easier as now we can just print <code>self.head</code> (in the <code>LinkedList</code>) to be able to visually debug any incorrect states. The default <code>__repr__</code> also automatically handles recursion, to aide in debugging.</p>\n<pre class=\"lang-py prettyprint-override\"><code>ll.next.next = ll\nprint(ll)\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>Node(data=0, next=Node(data=1, next=...))\n</code></pre>\n<p><strong>Note</strong>: <code>...</code> just means there is recursion here, we would get the same output if we assigned <code>ll.next</code> rather than <code>ll</code>.</p>\n<h2>Linked List</h2>\n<h3>Iterating</h3>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>def length(self):\n '''Returns the length of a linked list.'''\n current_node = self.head\n node_total = 0\n while (current_node != None):\n node_total += 1\n current_node = current_node.next\n return node_total\n</code></pre>\n</blockquote>\n<p>There are some ways <code>length</code> is not Pythonic:</p>\n<ul>\n<li>\n<blockquote>\n<p><a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">For consistency, always use <code>&quot;&quot;&quot;triple double quotes&quot;&quot;&quot;</code> around docstrings.</a></p>\n</blockquote>\n</li>\n<li><p>You should use <code>is</code> when comparing to singletons like <code>None</code>.</p>\n</li>\n<li><p>Please don't use unneeded parentheses.</p>\n<pre class=\"lang-py prettyprint-override\"><code>while current_node is not None:\n</code></pre>\n</li>\n<li><p>Your method's name should be <code>__len__</code> as then you can use <code>len(obj)</code> rather than <code>obj.length()</code>. Doing so can help make <code>LinkedList</code> a drop in replacement for say <code>list</code>.</p>\n</li>\n<li><p>I would define a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator function</a> to iterate through the linked list. Using a generator function can make your code much simpler. We can then use standard iterator parts of Python like <code>for</code> and <code>sum</code> instead.</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def __iter__(self):\n curr = self.head\n while curr is not None:\n yield curr.data\n curr = curr.next\n\ndef __len__(self):\n &quot;&quot;&quot;Returns the length of a linked list.&quot;&quot;&quot;\n return sum(1 for _ in self)\n</code></pre>\n<h3>Inserting</h3>\n<p>Rather than defaulting <code>head</code>, and <code>foot</code>, to <code>None</code> we can default to <code>Node(None)</code>.\nWe can then make your code simpler by getting rid of all the <code>if self.head is None</code> code.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def queue_append(self, data):\n self.foot.next = Node(data)\n self.foot = self.foot.next\n</code></pre>\n<p><strong>Note</strong>: If you do add a default head then you'd need to change <code>__iter__</code> to not return the default head. However we wouldn't need to change <code>__len__</code>, because <code>__len__</code> is based off <code>__iter__</code>!</p>\n<p>Inserting into the head would also stay simple. The changes we made to <code>Node</code> can also make the code simpler.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def stack_insert(self, data):\n self.head.next = Node(data, self.head.next)\n if self.foot is self.head:\n self.foot = self.head.next\n</code></pre>\n<p>There are some change I'd make to <code>insert_after</code>:</p>\n<ul>\n<li><p>Rather than using <code>stack_insert</code> and <code>queue_append</code>, the code would be far simpler built from scratch.</p>\n</li>\n<li><p>Since <code>length</code>, or <code>__len__</code>, has to iterate through the linked list, calling the function isn't too helpful.</p>\n</li>\n<li><p>Any performance gain from <code>queue_append</code> is lost by using <code>length</code>.</p>\n</li>\n<li><p>By calling <code>stack_insert</code> with an input of 0 your code is prone to making bugs.</p>\n<pre class=\"lang-py prettyprint-override\"><code>ll = LinkedList()\nll.queue_append(&quot;a&quot;)\nll.insert_after(&quot;b&quot;, 0)\nll.insert_after(&quot;c&quot;, 1)\nprint(ll.head)\n</code></pre>\n<pre><code>Node(data='b', next=Node(data='a', next=Node(data='c', next=None)))\n</code></pre>\n</li>\n<li><p>Now that the linked list will always have a root <code>Node</code> we can easily change the function to insert before, rather than after.</p>\n</li>\n<li><p>You should <code>raise</code> errors not print.</p>\n</li>\n</ul>\n<p>In all I'd follow <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS</a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def insert(self, index, value):\n if index &lt; 0:\n raise IndexError(&quot;cannot work with negative indexes&quot;)\n curr = self.head\n for _ in range(index):\n curr = curr.next\n if curr is None:\n raise IndexError(f&quot;index, {index}, is out of range&quot;)\n curr.next = Node(value, curr.next)\n if curr is self.foot:\n self.foot = curr.next\n</code></pre>\n<p>Now <code>stack_insert</code> looks quite unneeded; we can just use <code>LinkedList.insert(0, ...)</code> instead.\nAlso if we changed <code>__len__</code> to return from a constant then we could change the code so there is no appreciable gain from <code>queue_append</code>.</p>\n<h3>Deleting</h3>\n<p>Rather than falling for the same problems as insert we should just ignore <code>delete_head</code> and <code>delete_foot</code>.</p>\n<p>Since the code for finding the current node, or previous node for delete, is exactly the same, we can make a function to return a desired node.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _index(self, index):\n if index &lt; 0:\n raise IndexError(&quot;cannot work with negative indexes&quot;)\n curr = self.head\n for _ in range(index):\n curr = curr.next\n if curr is None:\n raise IndexError(f&quot;index, {index}, is out of range&quot;)\n return curr\n</code></pre>\n<p>Now we just need to ensure the <em>next</em> value is is not <code>None</code> as the index would be out of range. And ensure we update <code>self.foot</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def delete_node(self, index):\n prev = self._index(index)\n if prev.next is None:\n raise IndexError(f&quot;index, {index}, is out of range&quot;)\n if prev.next is self.foot:\n self.foot = prev\n prev.next = prev.next.next\n</code></pre>\n<h3>Getting / Updating</h3>\n<p>There should be no suprise. We just call <code>self._index</code> and handle the node however is needed.</p>\n<h3>Pythonisms</h3>\n<ul>\n<li><p>We can use the <a href=\"https://docs.python.org/3/reference/datamodel.html#emulating-container-types\" rel=\"nofollow noreferrer\">container dunder methods</a>:</p>\n<ul>\n<li><code>get_node_data</code> -&gt; <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__getitem__\" rel=\"nofollow noreferrer\"><code>__getitem__</code></a></li>\n<li><code>update_node</code> -&gt; <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__setitem__\" rel=\"nofollow noreferrer\"><code>__setitem__</code></a></li>\n<li><code>delete_node</code> -&gt; <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__delitem__\" rel=\"nofollow noreferrer\"><code>__delitem__</code></a></li>\n</ul>\n</li>\n<li><p>A common Python idiom is negative numbers mean 'go from the end'.\nWe can easily change <code>_index</code> to handle negatives rather than error.</p>\n</li>\n<li><p>You should rename <code>is_empty_list</code> to <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__bool__\" rel=\"nofollow noreferrer\"><code>__bool__</code></a> to allow truthy testing your linked list.</p>\n</li>\n<li><p>You should mimic the names of existing datatypes, like <a href=\"https://docs.python.org/3/tutorial/datastructures.html\" rel=\"nofollow noreferrer\"><code>list</code></a> or <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>collections.deque</code></a>. <strong>Note</strong>: you should <em>not</em> mimic the names of <a href=\"https://docs.python.org/3/library/queue.html\" rel=\"nofollow noreferrer\"><code>queue.Queue</code></a> or <a href=\"https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Queue\" rel=\"nofollow noreferrer\"><code>multiprocessing.Queue</code></a>; both classes are used for a different pattern than your code is for.</p>\n<ul>\n<li><code>stack_insert</code> -&gt; <code>appendleft</code>.</li>\n<li><code>queue_append</code> -&gt; <code>append</code>.</li>\n<li><code>delete_head</code> -&gt; <code>popleft</code>.</li>\n<li><code>delete_foot</code> -&gt; <code>pop</code>.</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\n\nimport dataclasses\nfrom typing import Generic, TypeVar\n\nT = TypeVar(&quot;T&quot;)\n\n\n@dataclasses.dataclass\nclass Node(Generic[T]):\n data: T\n next: Node = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = self.foot = Node(None)\n self._length = 0\n \n def __iter__(self):\n curr = self.head.next\n while curr is not None:\n yield curr\n\n def __len__(self):\n return self._length\n\n def __bool__(self):\n return self.head.next is None\n\n # You don't need max if you don't want to make a doubly\n # linked list with a foot node like the head node\n def _norm_index(self, index, min=0, max=0):\n index += min if 0 &lt;= index else max\n index = len(self) + 1 + index if index &lt; 0 else index\n if index &lt; min:\n raise IndexError(&quot;out of range min&quot;)\n if len(self) + max &lt; index:\n raise IndexError(&quot;out of range max&quot;)\n return index\n\n def _index(self, index, min=0, max=0):\n try:\n _index = self._norm_index(index, min, max)\n if _index == len(self):\n return self.foot\n curr = self.head\n for _ in range(_index):\n curr = curr.next\n if curr is None:\n raise IndexError(&quot;curr is None&quot;)\n return curr\n except IndexError as e:\n raise IndexError(f&quot;index, {index}, is out of range&quot;).with_traceback(e.__traceback__) from None\n\n def __getitem__(self, index):\n return self._index(index, min=1).data\n\n def __setitem__(self, index, value):\n curr = self._index(index, min=1)\n curr.data = value\n\n def __delitem__(self, index):\n prev = self._index(index - 1 if index &lt; 0 else index)\n if prev.next is None:\n raise IndexError(f&quot;index, {index}, is out of range&quot;)\n if prev.next is self.foot:\n self.foot = prev\n self._length -= 1\n prev.next = prev.next.next\n\n def insert(self, index, value):\n curr = self._index(index)\n self._length += 1\n curr.next = Node(value, curr.next)\n if curr is self.foot:\n self.foot = curr.next\n\n def append(self, value):\n self.insert(-1, value)\n\n def appendleft(self, value):\n self.insert(0, value)\n\n def pop(self):\n del self[-1]\n\n def popleft(self):\n del self[0]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T20:11:22.703", "Id": "256351", "ParentId": "256319", "Score": "4" } } ]
{ "AcceptedAnswerId": "256351", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T00:53:28.823", "Id": "256319", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "linked-list" ], "Title": "singly linked list python code" }
256319
<p>Ubuntu and other Linux variants do not have a Windows like <code>CTRL + ALT + DEL</code> screen, so I figured I'll make one myself. My plan is to make a HTML version, render that with the PyQt Web engine, and then when the keys <code>CTRL + ALT + DEL</code> are pressed the program launches.</p> <p>Preview it: <a href="https://codepen.io/aangeletakis/pen/YzprZxX?editors=1100" rel="nofollow noreferrer">https://codepen.io/aangeletakis/pen/YzprZxX?editors=1100</a></p> <p>How could I improve on it before I start on the application portion?</p> <pre><code>&lt;style&gt; :root{ --interface-width:10%; --cancel-btn-border-width: 2px; --ui-text-color:white; outline: none; user-select: none; } body { background: #005A9E; padding: 0px; } .userInterface {color:var(--ui-text-color);} .center { width: var(--interface-width); transform: translate(-55%, -65%); position: absolute; top: 50%; left: 50%; overflow: auto; } .optionsList { color:var(--ui-text-color); list-style:none; } .optionsList li{margin-left: 0; padding-left: 0;} .optionsList li button{ border:none; color: inherit; background:none; outline: none; --optionPadding:25px; padding-top: var(--optionPadding); padding-bottem: var(--optionPadding); cursor: pointer; } .optionsList li button:hover{opacity: 0.75;} .cancelBtn { transform: translate(calc(50% - var(--interface-width) - 3%), 0%); border: var(--cancel-btn-border-width) solid transparent; background: #337BB1; color:var(--ui-text-color); margin-top:30px; --cancel-btn-lr-padding: 40px; padding-right: var(--cancel-btn-lr-padding); padding-left: var(--cancel-btn-lr-padding); padding-top: 7px; padding-bottom: 7px; outline: 0; } .cancelBtn:hover { border: var(--cancel-btn-border-width) solid lightblue; } &lt;/style&gt; &lt;body&gt; &lt;div class=&quot;userInterface center&quot;&gt; &lt;ul class=&quot;optionsList&quot;&gt; &lt;li&gt;&lt;button&gt;Lock&lt;/button&gt;&lt;/li&gt; &lt;li&gt;&lt;button&gt;Switch user&lt;/button&gt;&lt;/li&gt; &lt;li&gt;&lt;button&gt;Sign out&lt;/button&gt;&lt;/li&gt; &lt;li&gt;&lt;button&gt;System manager&lt;/button&gt;&lt;/li&gt; &lt;/ul&gt; &lt;button class=&quot;cancelBtn&quot;&gt;Cancel&lt;/button&gt; &lt;div&gt; &lt;/body&gt; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T05:40:53.163", "Id": "256323", "Score": "0", "Tags": [ "python", "html", "linux" ], "Title": "Windows Like Security Screen for Linux (mockup)" }
256323
<p>I'm trying to solve the LeetCode question where you need to find out the area of the <a href="https://leetcode.com/problems/container-with-most-water/" rel="nofollow noreferrer">container with the most water</a>. I have created the solution that seems to work in my testing but it fails for being too slow when I try to submit it on LeetCode.</p> <p>My idea is that I create a dictionary of (x, y) tuples from the input list and then for every item I need to find the maximum distance to any of other lines that are equal or taller than it and from here I can calculate what the maximum area is possible for this line.</p> <p>How else can I approach this to get it to run faster? (I can't submit solution successfully so can't see examples of answers by other users)</p> <pre><code>def max_area(height) -&gt; int: areas = [] coords = {x: (x, y) for x, y in enumerate(height)} for x in coords: higher = [k for k in coords if coords[k][1] &gt;= coords[x][1]] area = max(abs(coords[j][0] - coords[x][0]) for j in higher) * coords[x][1] areas.append(area) return max(areas) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T11:56:02.237", "Id": "506048", "Score": "0", "body": "Hello, to give a more detailed a more specific description of the problem you can add the `time-limit-exceeded` tag to your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T16:02:06.287", "Id": "506063", "Score": "0", "body": "*\"can't see examples of answers by other users\"* - Are you sure you're telling the truth? I can see [other people's solutions](https://leetcode.com/problems/container-with-most-water/discuss/?currentPage=1&orderBy=most_votes&query=) even when not logged in at all." } ]
[ { "body": "<p>My suggestion about your current solution:</p>\n<pre><code>def max_area(height) -&gt; int:\n areas = []\n coords = {x: (x, y) for x, y in enumerate(height)}\n for x in coords:\n higher = [k for k in coords if coords[k][1] &gt;= coords[x][1]]\n area = max(abs(coords[j][0] - coords[x][0]) for j in higher) * coords[x][1]\n areas.append(area)\n return max(areas)\n</code></pre>\n<ul>\n<li>Keep track of the biggest area so far, instead of using the list <code>areas</code>.</li>\n</ul>\n<pre><code>def max_area(height) -&gt; int:\n coords = {x: (x, y) for x, y in enumerate(height)}\n result = 0\n for x in coords:\n higher = [k for k in coords if coords[k][1] &gt;= coords[x][1]]\n area = max(abs(coords[j][0] - coords[x][0]) for j in higher) * coords[x][1]\n result = max(result, area)\n return result\n</code></pre>\n<p>This reduces memory usage but is not enough to pass the challenge.</p>\n<p>The solution can be considered a brute force approach which is typically not enough to solve medium/hard problems on LeetCode.</p>\n<p>The constraint is <span class=\"math-container\">\\$n &lt;= 3 * 10^4\\$</span>, where <span class=\"math-container\">\\$n\\$</span> is the length of the input list. Generally, with such constraint, we should look at a solution with a time complexity less than <span class=\"math-container\">\\$O(n^2)\\$</span>.</p>\n<p>Let's consider the example on LeetCode where the input list is:</p>\n<ul>\n<li>height = [1,8,6,2,5,4,8,3,7]</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/kFLMt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kFLMt.png\" alt=\"enter image description here\" /></a></p>\n<p>For each two bars, the biggest area is given by the lowest bar. In the example, the two bars are <code>8</code> and <code>7</code>, so the area is <code>7 * (8 - 1) = 49</code>. Note that <code>(8 - 1)</code> is the difference between the indices of the bars. This is an <span class=\"math-container\">\\$O(n)\\$</span> algorithm:</p>\n<pre><code>Initialize l to 0\nInitialize r to the right most index\nInitialize max_area to 0\nwhile l is lower than r\n find the area as: lowest bar * (r - l)\n update max_area\n increment l if points to the lower bar, else decrement r\nreturn max_area\n</code></pre>\n<p>Next time you can check the &quot;hints&quot; and the tab &quot;Discuss&quot; for help or alternative solutions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T15:32:05.320", "Id": "256338", "ParentId": "256326", "Score": "1" } }, { "body": "<p>Your question made me want to give it a shot, too. The solution ended up pretty much like the pseudo-code suggested by @Marc , and Python is of course pretty close in readability anyway. The below code passes on the site and runs (there is some deviation between runs) <strong>faster than c. 95%</strong> and at with less memory usage than c. <strong>75%</strong> of solutions. The code contains comments at the relevant positions. There's two extra optimizations, also explained there.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def max_area(height: list[int]) -&gt; int:\n n = len(height) - 1\n l = 0 # Index for left bar\n r = n # Index for right bar\n max_area = 0\n\n while True:\n # Give readable names:\n left = height[l]\n right = height[r]\n\n # Current area, constrained by lower bar:\n area = min(left, right) * (r - l)\n if area &gt; max_area:\n # Keep tabs on maximum, the task doesn't ask for any\n # more details than that.\n max_area = area\n\n # Move the smaller bar further inwards towards the center, expressed\n # as moving left, where *not* moving left implies moving right.\n # The smaller bar constrains the area, and we hope to get to a longer\n # one by moving inwards, at which point the other bar forms the constraint,\n # so the entire thing reverses.\n move_left = left &lt; right\n\n # Instead of only moving the smaller bar inward by one step, there's two\n # extra steps here:\n # 1. While moving the smaller bar inward, skip all bars that are\n # *even smaller*; those are definitely not the target, since both\n # their height and horizontal delta will be smaller.\n # 2. While skipping all smaller bars, we might hit the other bar:\n # there is a 'valley' or at least nothing higher in between.\n # Any more moving inwards would be a wasted effort, no matter the\n # the direction (from left or right). We can return the current\n # max. area.\n #\n # In the best case scenario, this may skip us right to the solution,\n # e.g. for `[10, 1, 1, 1, 1, 1, 10]`: only one outer loop is necessary.\n #\n # Both loops look very similar, maybe there's room for some indirection\n # here, although a function call would probably mess with the raw\n # performance.\n if move_left:\n while height[l] &lt;= left:\n if l == r:\n return max_area\n l += 1\n else:\n while height[r] &lt;= right:\n if r == l:\n return max_area\n r -= 1\n\n\n# Examples from the site\nprint(max_area([1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49)\nprint(max_area([2, 3, 10, 5, 7, 8, 9]) == 36)\nprint(max_area([1, 3, 2, 5, 25, 24, 5]) == 24)\n</code></pre>\n<hr />\n<p>As far as your code goes:</p>\n<ul>\n<li><p>The mapping</p>\n<pre class=\"lang-py prettyprint-override\"><code>coords = {x: (x, y) for x, y in enumerate(height)}\n</code></pre>\n<p>seems pretty odd. You're kind of mapping <code>x</code> to itself. I would say for the solution it's much simpler to not treat <code>x</code> as <code>x</code> in the &quot;2D math plot&quot; sense, but just as <code>i</code> in the array index sense. This saves us having to even declare <code>x</code>, we can just iterate using <code>i</code>.</p>\n</li>\n<li><p>You use <code>max</code> twice, which is a linear search operation each time. This is needlessly expensive, but probably not the bottleneck.</p>\n</li>\n<li><p>Any algorithm based on finding e.g. <em>all distances to every other item</em> for <em>every</em> item has explosive complexity. This is likely the bottleneck.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T21:20:08.643", "Id": "256353", "ParentId": "256326", "Score": "1" } } ]
{ "AcceptedAnswerId": "256353", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T06:07:36.507", "Id": "256326", "Score": "3", "Tags": [ "python", "algorithm", "time-limit-exceeded" ], "Title": "How to speed up the code for LeetCode \"Container with most water\" task?" }
256326
<p>This function adds up an array pairwise. It runs fast enough and appears cache-friendly; I've tested it for correct output. It's in C++ (farther down in the file there's a function that takes a vector), but looks like valid C as well (but I haven't tried it in C). How easy is it to understand?</p> <pre><code>double pairwisesum(double *a,unsigned n) { unsigned i,j,b; double sums[32],sum=0; for (i=0;i+7&lt;n;i+=8) { b=i^(i+8); if (b==8) sums[3]=(((a[i]+a[i+1])+(a[i+2]+a[i+3]))+((a[i+4]+a[i+5])+(a[i+6]+a[i+7]))); else { sums[3]+=(((a[i]+a[i+1])+(a[i+2]+a[i+3]))+((a[i+4]+a[i+5])+(a[i+6]+a[i+7]))); for (j=4;b&gt;&gt;(j+1);j++) sums[j]+=sums[j-1]; sums[j]=sums[j-1]; } } for (;i&lt;n;i++) { b=i^(i+1); if (b==1) sums[0]=a[i]; else { sums[0]+=a[i]; for (j=1;b&gt;&gt;(j+1);j++) sums[j]+=sums[j-1]; sums[j]=sums[j-1]; } } for (i=0;i&lt;32;i++) if ((n&gt;&gt;i)&amp;1) sum+=sums[i]; return sum; } </code></pre> <p>For comparison, here is the previous version, which was slower because it kept making the cache miss, and also clobbered the array:</p> <pre><code>double pairwisesum(double *a,unsigned n) // a is clobbered. { unsigned i,j; if (n) { for (i=1;i&lt;n;i*=2) for (j=0;j+i&lt;n;j+=2*i) a[j]+=a[j+i]; return a[0]; } else return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T22:00:06.917", "Id": "506093", "Score": "0", "body": "Just out of curiosity, what kind of data are you dealing with where summing the array this way improves precision?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T23:37:07.820", "Id": "506095", "Score": "1", "body": "*A power series, where the terms increase, then decrease. I could sort them by absolute value, then start adding the small ones, but sorting would take more time.\n*Matrix multiplication.\n*In future, computing volumes by adding lots of samples. One of the surfaces may be a road, whose alignment has an Euler spiral (computed by the above power series), which cannot be expressed in closed form, so the volume has to be computed by sampling (which will be low-discrepancy for faster convergence).\n*A set of floating-point checksums computed from the elevations of hundreds of millions of points." } ]
[ { "body": "<blockquote>\n<p>This function adds up an array pairwise.</p>\n</blockquote>\n<p>Not sure what that means.</p>\n<blockquote>\n<p>It runs fast enough and appears cache-friendly; I've tested it for correct output.</p>\n</blockquote>\n<p>Good so it works.</p>\n<blockquote>\n<p>It's in C++ (farther down in the file there's a function that takes a vector), but looks like valid C as well (but I haven't tried it in C).</p>\n</blockquote>\n<p>No its not.<br />\nIts C. You have just compiled it with a C++ compiler.</p>\n<p>Being C++ is not just about writing code that can be compiled by the C++ compiler. It is a style of writing code. This is a typical C style. It just happens to compile under C++ compiler but it's not C++.</p>\n<p>This interface:</p>\n<pre><code>double pairwisesum(double *a,unsigned n)\n</code></pre>\n<p>Couple of issues: We don't pass around pointers in C++ (we can but as a language we decided it was a bad idea as it does not show ownership). So we tend to use other techniques (i.e references or smart pointers).</p>\n<p>In this case its not just a pointer: it's an array. The trouble here is that the array has decayed so we can't actually tell that it is an array any more and just have to assume the caller has not done something stupid. In C++ we like to understand the object being passed so we can use it correctly.</p>\n<p>In C++ (up to C++17) we would normally represent this as iterators:</p>\n<pre><code> template&lt;typename T&gt;\n double pairwisesum(I begin, I end)\n {\n for(I loop = begin; loop != end; ++loop) {\n</code></pre>\n<p>From C++20 we would probably represent this by a range:</p>\n<pre><code> tempalte&lt;typename R&gt;\n double pairwisesum(R range)\n {\n for (auto const&amp; r: range) {\n</code></pre>\n<p>Note a <code>Range</code> basically supports <code>begin()</code> and <code>end()</code> and is interchangeable with a <code>View</code>. If I got that incorrect, then sorry: we are still getting used to these concepts as they are new to C++.</p>\n<hr />\n<blockquote>\n<p>How easy is it to understand?</p>\n</blockquote>\n<p>I have read this code a couple of times and have no idea what it is trying to achieve. So I don't think it is readable or understandable without some more explanation. Some comments on what was happening would have been good.</p>\n<h2>Code Review</h2>\n<p>Declare variables:</p>\n<ul>\n<li><p>As close to to the point of use as possible.</p>\n</li>\n<li><p>Declare one variable per line.</p>\n<pre><code>unsigned i,j,b;\ndouble sums[32],sum=0;\n</code></pre>\n</li>\n</ul>\n<p>What are you trying to achieve? Vertical space-saving is not a good style. Make it clear as possible to use.</p>\n<p>I know a lot of people use <code>i/j</code> for loop variables (especially coming from C or FORTRAN). But it is objectively a bad choice. Once you start adding comments to your code searching for <code>i</code> and <code>j</code> in the code gives you way too many false hits when trying to find all the use cases. So unless your loop is literally one line obvious and the loop variable is only used in one place don't do it. Even if all the above is true, don't do it because the code will change over time and writing it expressively now will save time later.</p>\n<hr />\n<p>You can declare your variable in the loop:</p>\n<pre><code> for (i=0;i+7&lt;n;i+=8)\n</code></pre>\n<p>Write like this:</p>\n<pre><code> for (unsigned loop = 0; loop + 7 &lt; mac; loop += 8) {\n</code></pre>\n<hr />\n<strike>\nThere is no precedence rules you are trying to get around here. Those extra braces are just adding noise to the code:\n<pre><code> sums[3]=(((a[i]+a[i+1])+(a[i+2]+a[i+3]))+((a[i+4]+a[i+5])+(a[i+6]+a[i+7])));\n</code></pre>\n<p>Why not:</p>\n<pre><code> sums[3]=a[i]+a[i+1]+a[i+2]+a[i+3]+a[i+4]+a[i+5]+a[i+6]+a[i+7];\n</code></pre>\n<p>Why not use a standard algorithm:</p>\n<pre><code> auto start = a + i;\n auto end = start + 8;\n sums[3] = std::accumulate(start, end, 0);\n</code></pre>\n</strike>\n<p>As it turns out the parentheses here is for a reason. Because we are dealing with doubles. The parentheses reduces the amount of error that creeps into the sum by making sure we do addition in a particular order.</p>\n<p>I would separate this additional line out into its own function (with a very explanation-based name) so it documents why you are adding this up in a particular order. This will be important for future maintainers as they may not immediately understand why all the braces are there (and do what I did and just remove them to make the code easy to read).</p>\n<pre><code>sums[3] = sumValuesBecauseOfSomeReasonIHaveThatReducesErrors(a + i)\n\ninline double sumValuesBecauseOfSomeReasonIHaveThatReducesErrors(double* a) {\n return (((a[0]+a[1])+(a[2]+a[3]))\n +((a[4]+a[5])+(a[6]+a[7])));\n}\n</code></pre>\n<hr />\n<p>That is unreadable:</p>\n<pre><code> for (j=4;b&gt;&gt;(j+1);j++)\n</code></pre>\n<p>What are you testing for in <code>b &gt;&gt; (j+1)</code>? Us a named function to make the meaning clear.</p>\n<pre><code> for (unsigned jLoop; insideReachValid(b, jLoop); ++jLoop) {\n</code></pre>\n<p>As a side note: prefer <code>++j</code> over <code>j++</code>. For integers there is no difference. But if you are looping with other types it can make a minor difference and the idea is that you want to be optimal whatever the loop type. A lot of C++ code is modified by simply changing the type of the objects and you don't want to change the type then go back and change how it used as well.</p>\n<hr />\n<p>Always add the braces around '{}` around sub blocks. Its not always clear with indentation (especially when it does badly) what is in the sub block. Make it explicit by using the braces.</p>\n<pre><code> for (unsigned jLoop; insideRacheValud(b, j); ++j) {\n sums[jLoop] += sums[jLoop - 1];\n }\n</code></pre>\n<hr />\n<p>This should be your comment above the code.</p>\n<pre><code>// This is the original implementation.\n// The code has been updated to prevent cache missing and optimize the\n// the performance of the operation.\n//\n// This code is deliberately left here as a comment to provide a reference\n// for generating unit tests and validation and to explain what the code\n// is actually trying to achieve (as the optimized version is non-trivial to understand).\n#if 0\ndouble pairwisesum(double *a,unsigned n)\n// a is clobbered.\n{\n unsigned i,j;\n if (n)\n {\n for (i=1;i&lt;n;i*=2)\n for (j=0;j+i&lt;n;j+=2*i)\n a[j]+=a[j+i];\n return a[0];\n }\n else\n return 0;\n}\n#endif\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T19:29:14.493", "Id": "506080", "Score": "0", "body": "I'm not sure what you mean by \"acoud\", but the parentheses are not there for noise. They're there to make the summation pairwise. Without them, the summation would have more error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T19:32:04.757", "Id": "506081", "Score": "0", "body": "@PierreAbbat: Of course we are adding doubles so the order does matter. That would be a good comment to add to the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T19:35:39.473", "Id": "506082", "Score": "0", "body": "So far I haven't seen a reason to go past C++17 (which introduced readers-writer locks, which I use).\n\nThe original version is no longer in the code; I had to dig in git. I'll put it back in." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T19:02:49.140", "Id": "256347", "ParentId": "256328", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T08:27:40.597", "Id": "256328", "Score": "2", "Tags": [ "c++" ], "Title": "Pairwise summation" }
256328
<p>Given a square grid of size N, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which the total cost incurred is minimum. From the cell (i,j) we can go (i,j-1), (i, j+1), (i-1, j), (i+1, j).</p> <p>Note: It is assumed that negative cost cycles do not exist in the input matrix.</p> <pre><code>Example 1: Input: grid = {{9,4,9,9},{6,7,6,4}, {8,3,3,7},{7,4,9,10}} Output: 43 Explanation: The grid is- 9 4 9 9 6 7 6 4 8 3 3 7 7 4 9 10 The minimum cost is- 9 + 4 + 7 + 3 + 3 + 7 + 10 = 43. </code></pre> <p><strong>My working code:</strong></p> <pre><code>global INT_MAX # value of n is passed by the driver along with the grid INT_MAX = 3 ** 38 class Solution: # &lt;- this returns the minVertex's co-orinates -&gt; def minimumVertex(self,distMat,visited): minVertexi = 0 minVertexj = 0 max1 = INT_MAX for i in range(n): for j in range(n): if distMat[i][j] &lt; max1 and visited[i][j] == False: max1 = distMat[i][j] minVertexi = i minVertexj = j return minVertexi, minVertexj def minimumCostPath(self, grid): # &lt;- visited matrix is created with all False -&gt; visited = [] for i in range(n): eachRow = [] for j in range(n): eachRow.append(False) visited.append(eachRow) # &lt;- distMat is created with all values initialized with INT_MAX -&gt; distMat = [] for i in range(n): eachRow1 = [] for j in range(n): eachRow1.append(INT_MAX) distMat.append(eachRow1) distMat[0][0] = grid[0][0] drow = [-1, 1, 0, 0] dcol = [0, 0, -1, 1] for _ in range(n): for currj in range(n): mini,minj = self.minimumVertex(distMat,visited) visited[mini][minj] = True for k in range(len(drow)): nbri = mini + drow[k] nbrj = minj + dcol[k] # print(&quot;outside nbri = &quot;,nbri,&quot;outside nbrj = &quot;,nbrj) if nbri &gt;=0 and nbrj &gt;= 0 and nbri &lt; n and nbrj &lt; n: if visited[nbri][nbrj] == False: # print(&quot;inside nbri = &quot;,nbri,&quot;inside nbrj = &quot;,nbrj) if distMat[nbri][nbrj] &gt; distMat[mini][minj] + grid[nbri][nbrj]: distMat[nbri][nbrj] = distMat[mini][minj] + grid[nbri][nbrj] return distMat[n-1][n-1] </code></pre> <p><strong>Expected Time Compelxity:</strong> O(n2*log(n))</p> <p><strong>Expected Auxiliary Space:</strong> O(n2)</p> <p><strong>Problem with my code:</strong></p> <p>My logic is alright however it is exceeding the time limit, how do I optimize it?</p> <p><strong>NOTE:</strong> The grid is always a square grid and N (dimension) is passed to the function along with the grid. I took N = 4 here because I was debugging the code for a single test case.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T20:54:23.297", "Id": "506087", "Score": "0", "body": "I believe this solution is O(n^4). `minimumVertex()` is O(n^2) and it is called n^2 times in the nested loops in `minimumCostPath()`. Try using a heap to keep track of the minimum vertex." } ]
[ { "body": "<h2>Actual time complexity</h2>\n<p>As you correctly state, the <em>expected</em> time complexity of Dijkstra's on a square matrix is <code>O(n^2 log n)</code>. However, your algorithm has a complexity of at least <code>O(n^4)</code> due to the way you locate the minimum vertex.</p>\n<pre><code>for _ in range(n):\n for currj in range(n):\n # &lt;--- executed n^2 times here\n mini,minj = self.minimumVertex(distMat,visited)\n ...\n\ndef minimumVertex(self,distMat,visited):\n minVertexi = 0\n minVertexj = 0\n max1 = INT_MAX\n for i in range(n):\n for j in range(n):\n # &lt;--- takes n^2 time\n ...\n</code></pre>\n<p>In fact, the algorithm you implemented isn't purely Dijkstra's, but a blend of <a href=\"https://en.wikipedia.org/wiki/Dijkstras_algorithm\" rel=\"nofollow noreferrer\">Dijkstra's algorithm</a> and <a href=\"https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm\" rel=\"nofollow noreferrer\">Floyd's algorithm</a>.\nYou should read through the links above, particularly the <em>Pseudocode</em> sections to understand how each of the algorithms works, and the parts that you're mixing up.</p>\n<h2>Dijkstra's algorithm</h2>\n<p>The key data structure which allows Dijkstra's algorithm to work in <code>O(n^2 log n)</code> time is a <a href=\"https://en.wikipedia.org/wiki/Priority_queue\" rel=\"nofollow noreferrer\"><strong>priority queue</strong></a> which allows you to insert elements and remove the top element in <code>O(log n)</code> time.\nThis data structure is commonly implemented using a <a href=\"https://en.wikipedia.org/wiki/Binary_heap\" rel=\"nofollow noreferrer\">binary heap</a>, and has a standard implementation in Python as the <a href=\"https://docs.python.org/3/library/heapq.html\" rel=\"nofollow noreferrer\"><code>heapq</code></a> library.</p>\n<p>You should adapt your code to use this data structure instead of the distance table as shown below.\nIt is important that the <strong>first</strong> field of the tuple is the distance, since this determines the sorting.</p>\n<pre><code>def minimumCostPath(self, grid):\n # definitions of n, visited, drow, dcol\n\n queue = [(grid[0][0], 0, 0)]\n while queue:\n dist, i, j = heapq.heappop(queue)\n\n if visited[i][j]:\n continue\n visited[i][j] = True\n \n if i == j == n - 1:\n return dist\n\n for k in range(len(drow)):\n ni = i + drow[k]\n nj = j + dcol[k]\n if 0 &lt;= ni &lt; n and 0 &lt;= nj &lt; n:\n heapq.heappush(queue, (dist + grid[ni][nj], ni, nj))\n\n assert False, &quot;queue is exhausted but we haven't reached the destination yet&quot;\n</code></pre>\n<h2>Benchmarking surprise</h2>\n<p>After writing all of this, I decided to quantify the improvement by benchmarking.\nThis is the code I used to see how my implementation compares against the original.</p>\n<pre><code>if __name__ == &quot;__main__&quot;:\n import time\n N = 100\n grid = [[j for _ in range(N)] for j in range(N)]\n solver = Solution()\n\n start = time.time()\n print(solver.minimumCostPath(grid))\n end = time.time()\n print(f&quot;Solved grid with size {N} in {1000*(end - start):.3f}ms&quot;)\n</code></pre>\n<p>To my surprise, your version was <em>actually faster</em>, but more importantly it gave <strong>incorrect</strong> results.</p>\n<blockquote>\n<p>My logic is alright</p>\n</blockquote>\n<p>No, it's not.\nThe issue is the usage of <code>n</code> in the <code>minimumVertex</code> function. Because you define <code>n = 4</code> as a global, this value is used instead of the actual size of the grid. This makes your algorithm appear fast, but actually be incorrect for <code>n &gt; 4</code>.</p>\n<h2>Conclusion</h2>\n<p>As it turns out, while the algorithm you (I imagine) intended to implement is <code>O(n^4)</code>, your code was actually <code>O(n^2)</code> all along. If this really resulted in TLE, Python is not going to be able to handle this question.\nWhat I find much more likely is that your code failed due to an incorrect response - using the correct implementation of Dijkstra's above is likely to fix this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T05:53:02.490", "Id": "506106", "Score": "0", "body": "This code was meant for an online judge and the reason I defined n = 4 because I was debugging the code for a single test case where N was 4. Now understand this, the grid is always a square grid (rows = columns) and the driver calls my function with the grid and N so that's really not an issue here, I hope you are getting what I am trying to say." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T07:13:20.740", "Id": "506108", "Score": "0", "body": "Also, no offence but refrain from saying the logic is wrong and try asking the OP or thinking the reason behind something." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T11:22:39.400", "Id": "506121", "Score": "0", "body": "@ShubhamPrashar Next time please include the whole code in the question. In `minimumCostPath` you calculate the correct n from the given grid, but the proceed to use a *different* n in `minimumVertex`. With the snippet provided there is no reasonable explanation other than a logic error. In fact, even if you define the global n to be the size of the grid, I would still consider this a logic error - you should either use the global n in both functions, or the calculated n in both functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T11:25:00.223", "Id": "506122", "Score": "0", "body": "Yeah, I totally agree with you here but what do you think about the complexity part? Everythings fine yet getting the TLE. How to optimize it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T11:32:49.527", "Id": "506124", "Score": "0", "body": "@ShubhamPrashar Re-read the first two sections of my answer, where I show that the complexity of your solution is actually `O(n^4)`. You should use [a correct implementation of Dijkstra's](https://en.wikipedia.org/wiki/Dijkstras_algorithm#Using_a_priority_queue), which will give you the desired complexity of `O(n^2 log n)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T11:34:31.460", "Id": "506125", "Score": "0", "body": "`your code was actually O(n^2)` and what about this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T11:40:15.693", "Id": "506126", "Score": "0", "body": "@ShubhamPrashar The code you *sent* was `O(n^2)` because of the global constant `n = 4`. If in the actual code you define the global correctly, the complexity will be `O(n^4)`. I'll edit the question later to make this more clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T11:40:57.120", "Id": "506127", "Score": "0", "body": "Alright got it now. Thanks!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T20:59:11.617", "Id": "256352", "ParentId": "256335", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T12:43:39.963", "Id": "256335", "Score": "3", "Tags": [ "performance", "algorithm", "python-3.x", "time-limit-exceeded", "graph" ], "Title": "Optimizing Dijkstra on grid Python (Microsoft Interview)" }
256335
<p>Module for generating a PWM signal. The req_value_i input gets a duration value of the signal. Furthermore, the module can be stopped by deassertion of the enable_i input.</p> <pre><code>`timescale 1ns / 1ps module pwm # ( parameter integer PWM_COUNTER_WIDTH = 8 ) ( input logic clk_i, input logic s_rst_n_i, input logic enable_i, input logic [PWM_COUNTER_WIDTH - 1 : 0] req_value_i, output logic channel_o ); logic [PWM_COUNTER_WIDTH - 1 : 0] counter; always_comb begin channel_o = (req_value_i != counter) ? 1'h1 : 1'h0; end always_ff @ (posedge clk_i) begin if (1'h0 == s_rst_n_i) begin counter &lt;= {PWM_COUNTER_WIDTH{1'h0}}; end else if (1'h1 == enable_i) begin counter &lt;= counter + 1'h1; end end endmodule </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T18:11:27.977", "Id": "506234", "Score": "1", "body": "I commend you for making the effort to make major edits to your question. Many people simply delete or abandon the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T10:58:32.667", "Id": "506271", "Score": "0", "body": "Definitely, I have known how right to publish posts and will try to do it in the future correctly. Thanks =)" } ]
[ { "body": "<p>The layout of your code is consistent and easy to read. I don't see any functional problems.</p>\n<p>One consideration for all digital logic is whether you can tolerate glitches on your outputs. If your PWM output is directly driving a load such as a power inverter, you likely want to avoid glitches. To avoid glitches, change your combinational output to a registered output:</p>\n<pre><code>always_ff @ (posedge clk_i) begin\n if (1'h0 == s_rst_n_i) begin\n channel_o &lt;= 1'h0;\n end\n else begin\n channel_o &lt;= (req_value_i != counter);\n end\nend\n</code></pre>\n<p>I also simplified the expression by removing the ternary code <code>? 1'h1 : 1'h0</code>. But, this is just a matter of coding style preference.</p>\n<p>Another consideration is whether to use a synchronous reset (as you have) or an asynchronous reset. The advantage of asynchronous is that you don't need to have the clock toggling in order to reset your logic. For asynchronous, you would use:</p>\n<pre><code>always_ff @ (posedge clk_i or negedge s_rst_n_i) begin\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T11:06:20.590", "Id": "506272", "Score": "1", "body": "your comments still are accurate and useful. I am grateful you for your time and helping my evolving." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T17:49:59.027", "Id": "256419", "ParentId": "256337", "Score": "2" } } ]
{ "AcceptedAnswerId": "256419", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T14:37:27.173", "Id": "256337", "Score": "2", "Tags": [ "reinventing-the-wheel", "verilog", "hdl" ], "Title": "Pulse-width modulation module" }
256337
<pre><code>//Program To Input Values Into An Array And Sort Them In Ascending Order #include&lt;stdio.h&gt; //Function To Print The Array Values void print(int tab[],int n) { int i; printf(&quot;The Values Are : \n&quot;); for(i=0;i&lt;n;i++) { printf(&quot;%d &quot;,tab[i]); } printf(&quot;\n&quot;);//Line Jumping For Better Output } //Function To Swap The Values In The Array void swap(int* x,int* y) { int temp=*x; *x=*y; *y=temp; } //Function To Sort The Values In The Array By Using Previous Function void sort(int tab[],int n) { int i,j; for(i=0;i&lt;n-1;i++) { for(j=i+1;j&lt;n;j++) { if(tab[i]&gt;tab[j]) { swap(&amp;tab[i],&amp;tab[j]);//Swaps The Value Of Index i With The Value Of Index j In The Array } } } } //Main Code int main() { int i,n,tab[100]; printf(&quot;Give The Number Of Elements In The Array:&quot;); scanf(&quot;%d&quot;,&amp;n); while(n&lt;=0) { printf(&quot;The Number Of Elements MUST Be Superior To 0!\n&quot;); printf(&quot;Give The Number Of Elements In The Array:&quot;); scanf(&quot;%d&quot;,&amp;n); } printf(&quot;Insert %d Values :\n&quot;,n); for(i=0;i&lt;n;i++) { scanf(&quot;%d&quot;,&amp;tab[i]); } print(tab,n);//Prints The Values In The Array sort(tab,n);//Sorts The Values In The Array printf(&quot;SORTING....\n&quot;); print(tab,n);//Prints The Values In The Array return 0; } </code></pre>
[]
[ { "body": "<h1>General Observations</h1>\n<p>Good job creating functions and the naming of the functions. The naming of the variables could probably be improved, for instance <code>n</code> could be renamed to <code>item_count</code> or <code>array_element_count</code>.</p>\n<p>The indentation is inconsistent. This could lead issues during maintenance of the code.</p>\n<h1>Missing Function</h1>\n<p>As stated above you did a pretty good job of creating functions, but you missed one, the input of the array should be a function as well.</p>\n<h1>Logical Order of Printing</h1>\n<p>Put <code>printf(&quot;SORTING...\\n&quot;);</code> before the call to the <code>sort()</code> function.</p>\n<h1>Comments</h1>\n<p>Since you did a good job of naming the functions most of your comments are unnecessary. For instance <code>//Swaps The Value Of Index i With The Value Of Index j In The Array</code> really doesn't add anything.</p>\n<h1>Arguments for Swap Function</h1>\n<p>Rather than passing in 2 pointers to values and swapping the values I might pass in the array and the 2 indexes and use array notation in the swap function to relocate the values.</p>\n<h1>Missing Error Check</h1>\n<p>The code to input the array properly checks to see that the value of the size of the array is greater than 0, but it doesn't check that the size of the array is less than than the maximum size.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T10:30:08.350", "Id": "506118", "Score": "0", "body": "I would prefer `void swap(int* x, int* y)` or more general `void swap(void* x, void* y, size_t n)`. As `void swap(int* a, int x, int y)` is too specified and not quite useful. (Just my prefer.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T16:40:43.767", "Id": "256341", "ParentId": "256339", "Score": "1" } }, { "body": "<p>What you have implemented is called <s><em>Bubble Sort</em></s> <em>Insertion Sort</em> (If I've read it correctly); it's worth mentioning that in the comment of <code>sort()</code> to help readers. Otherwise, they may easily misunderstand the algorithm, as I did!</p>\n<hr />\n<blockquote>\n<pre><code>int main()\n</code></pre>\n</blockquote>\n<p>Not bad, but we can be a little more specific by showing that the <code>main()</code> takes no arguments:</p>\n<pre><code>int main(void)\n</code></pre>\n<hr />\n<p>We have a problem here:</p>\n<blockquote>\n<pre><code>int n;\nscanf(&quot;%d&quot;,&amp;n);\nwhile(n&lt;=0)\n</code></pre>\n</blockquote>\n<p>If <code>scanf()</code> is unable to convert the input as a decimal (e.g. if user writes <code>four</code> as input), then <code>n</code> will be <em>uninitialized</em>. That's bad, as it means your program has Undefined Behaviour, which in turn means it could do <em>anything at all</em>.</p>\n<p>However, we are able to detect that. <code>scanf()</code> returns the number of successful conversions it managed, so we just need to use that return value to determine whether <code>n</code> holds a valid value:</p>\n<pre><code>if (scanf(&quot;%d&quot;, &amp;n) != 1) {\n fputs(&quot;Not a valid number!\\n&quot;, stderr);\n return 1;\n}\n</code></pre>\n<p>We could avoid worrying about negative <code>n</code> by using an unsigned type (<code>unsigned int</code>, probably).</p>\n<p>It's a design decision, but I think you should allow a zero-length (empty) array as input. It's really easy to sort! And with unsigned <code>n</code>, means that all values are valid.</p>\n<p>Obviously the other <code>scanf()</code> needs its return value checking, too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T14:32:13.593", "Id": "506279", "Score": "1", "body": "It's neither bubble sort nor insertion sort but rather an overly eager version of selection sort. (The inner loop puts the smallest remaining value at `tab[i]`, but always swaps immediately instead only finding the smallest remaining value and then swapping only once.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T17:22:56.287", "Id": "256343", "ParentId": "256339", "Score": "1" } }, { "body": "<p><strong>Tidy up printing</strong></p>\n<p>White-space lurking between the last number and the <code>'\\n'</code> is a surprising occurrence and in my experience a source of annoying issues with cut/paste of output.</p>\n<p><strong><code>const *</code></strong></p>\n<p>Use <code>const</code> for wider function usage. Function can now also get called with a <code>const</code> array.</p>\n<p><strong>Parameter order</strong></p>\n<p>Consider <a href=\"https://en.wikipedia.org/wiki/C2x#Features\" rel=\"nofollow noreferrer\">order of parameters in function ... size ... before the array</a></p>\n<p><strong>Consider <code>size_t</code></strong></p>\n<p><code>int</code> may be too small for <em>large</em> arrays. Could use <code>size_t</code>.</p>\n<hr />\n<p>Put this together</p>\n<pre><code>void print(size_t n, const int tab[]) {\n printf(&quot;The Values Are :\\n&quot;); // No space before \\n\n const char *sep = &quot;&quot;;\n for (size_t i=0; i&lt;n; i++) {\n printf(&quot;%s%d &quot;, sep, tab[i]); // Space not after the number.\n sep = &quot; &quot;;\n }\n printf(&quot;\\n&quot;);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T00:00:02.610", "Id": "256423", "ParentId": "256339", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T15:36:28.077", "Id": "256339", "Score": "2", "Tags": [ "beginner", "c", "sorting" ], "Title": "Read and sort an array of integers" }
256339
<p>I am practicing Rust by creating data structures, such as this N-dimensional array. The purpose of this structure is to easily define and address into arbitrarily-deeply nested arrays without having to write out <code>Vec&lt;Vec&lt;Vec&lt;T&gt;&gt;&gt;</code> and incur the performance penalty coming from this (although performance is not a priority).</p> <p>I am looking for feedback on how idiomatic the interface and implementation are, as well as how to improve my tests since I don't think they're very robust.</p> <pre><code>use std::ops::{Index, IndexMut}; #[derive(Debug, Clone)] pub struct NdArray&lt;T, const N: usize&gt; { dim: [usize; N], data: Vec&lt;T&gt;, } impl&lt;T, const N: usize&gt; NdArray&lt;T, N&gt; { fn calculate_capacity(dim: &amp;[usize; N]) -&gt; usize { let mut cap = 1; for &amp;x in dim { cap = usize::checked_mul(cap, x).expect(&quot;vector capacity overflowed usize&quot;); } cap } pub fn new(dim: [usize; N], default: T) -&gt; Self where T: Clone, { let cap = Self::calculate_capacity(&amp;dim); NdArray { dim, data: vec![default; cap], } } pub fn new_with(dim: [usize; N], generator: impl FnMut() -&gt; T) -&gt; Self { let cap = Self::calculate_capacity(&amp;dim); NdArray { dim, data: { let mut v = Vec::new(); v.resize_with(cap, generator); v }, } } fn get_flat_idx(&amp;self, idx: &amp;[usize; N]) -&gt; usize { let mut i = 0; for d in 0..self.dim.len() { assert!( idx[d] &lt; self.dim[d], &quot;index {} is out of bounds for dimension {} with size {}&quot;, idx[d], d, self.dim[d], ); // This cannot overflow since we already checked product of all dimensions fits usize // and idx &lt; self.dim. i = i * self.dim[d] + idx[d]; } i } } impl&lt;T, const N: usize&gt; Index&lt;&amp;[usize; N]&gt; for NdArray&lt;T, N&gt; { type Output = T; fn index(&amp;self, idx: &amp;[usize; N]) -&gt; &amp;T { &amp;self.data[self.get_flat_idx(idx)] } } impl&lt;T, const N: usize&gt; IndexMut&lt;&amp;[usize; N]&gt; for NdArray&lt;T, N&gt; { fn index_mut(&amp;mut self, idx: &amp;[usize; N]) -&gt; &amp;mut T { let i = self.get_flat_idx(idx); &amp;mut self.data[i] } } #[cfg(test)] mod tests { use super::*; use std::panic::catch_unwind; #[test] fn nd_array_1d() { let mut array = NdArray::new_with([10], || 1); assert_eq!(array[&amp;[0]], 1); assert_eq!(array[&amp;[9]], 1); assert!(catch_unwind(|| array[&amp;[10]]).is_err()); array[&amp;[5]] = 99; assert_eq!(array[&amp;[4]], 1); assert_eq!(array[&amp;[5]], 99); assert_eq!(array[&amp;[6]], 1); } #[test] fn nd_array() { let mut array = NdArray::new([2, 3, 4], 0); array[&amp;[1, 2, 3]] = 10; assert_eq!(array[&amp;[1, 2, 3]], 10); assert_eq!(array[&amp;[1, 0, 0]], 0); assert!(catch_unwind(|| array[&amp;[2, 0, 0]]).is_err()); assert_eq!(array[&amp;[0, 2, 0]], 0); assert!(catch_unwind(|| array[&amp;[0, 3, 0]]).is_err()); assert_eq!(array[&amp;[0, 0, 3]], 0); assert!(catch_unwind(|| array[&amp;[0, 0, 4]]).is_err()); } #[test] fn nd_array_overflow() { // Panics at the allocator code since sizeof(usize) &gt; 2 // NdArray::new([usize::MAX / 2], 0); assert!(catch_unwind(|| NdArray::new([usize::MAX / 2 + 1, 2], 0)).is_err()); assert!(catch_unwind(|| NdArray::new( [usize::MAX / 3, usize::MAX / 3, usize::MAX / 3 + 1], 0 )) .is_err()); } } </code></pre>
[]
[ { "body": "<p>Nice example of const generics! In general your code is well organized and idiomatic. Some comments:</p>\n<ul>\n<li><p>In your <code>new()</code> function, you are using an argument as a default value. It's more idiomatic to use the <code>Default</code> trait for this:</p>\n<pre><code>pub fn new(dim: [usize; N]) -&gt; Self\nwhere\n T: Clone + Default,\n{\n let cap = Self::calculate_capacity(&amp;dim);\n NdArray {\n dim,\n data: vec![Default::default(); cap],\n }\n}\n</code></pre>\n<p>In some of your unit tests this means you have to use the turbofish to initialize: e.g. <code>NdArray::new</code> becomes <code>NdArray::&lt;usize, 2&gt;::new</code>. However, this only occurs when the user does not access / modify anything in the <code>NdArray</code>, and if they do that then type inference kicks in. So I recommend providing both options to the user, say <code>NdArray::new(dim: ...)</code> for <code>T: Default</code> and <code>NdArray::new_fillwith(dim: ..., default: T)</code> if the user wants to specify their own default value.</p>\n</li>\n<li><p>Your structure could use some more functionality. For any collection of <code>T</code>, <code>.len()</code> and <code>.iter()</code> would be the minimum:</p>\n<pre><code>pub fn len(&amp;self) -&gt; usize {\n self.data.len()\n}\n\npub fn iter(&amp;self) -&gt; impl Iterator&lt;Item = &amp;T&gt; {\n self.data.iter()\n}\n</code></pre>\n<p>What about adding two nd-arrays? Multiplying by a constant? Concatenating them along a certain dimension? Generalized matrix multiplication? Some of these will probably require certain utility functions.</p>\n<ul>\n<li>For example the following would probably be quite useful and a good exercise to write: iteration along a sub-dimensional slice of the array, like <code>pub fn iter_subarray(&amp;self, coords: &amp;[Option&lt;usize&gt;; N]) -&gt; impl Iterator&lt;Item = &amp;T&gt;</code> where if the coord is <code>None</code> then you iterate along all coordinates in that dimension, but if it's <code>Some(x)</code> then that coordinate is fixed.</li>\n</ul>\n</li>\n<li><p>You probably want to <code>#[derive(PartialEq, Eq)]</code> in addition to <code>Clone</code> and <code>Debug</code>.</p>\n</li>\n<li><p>Both the implementation and unit tests could use some handling of edge cases, in particular when the dimension is empty and when any of the dimension lengths is zero. Whether you allow these cases is up to you; I would personally allow the former but not the latter. Here's a unit test:</p>\n<pre><code>#[test]\nfn nd_array_edgecases() {\n let array_dim0 = NdArray::&lt;usize, 0&gt;::new([]);\n assert_eq!(array_dim0.len(), 1);\n assert_eq!(array_dim0[&amp;[]], 0);\n let array_dim1 = NdArray::&lt;usize, 1&gt;::new([0]);\n assert_eq!(array_dim1.len(), 0);\n assert!(catch_unwind(|| array_dim1[&amp;[0]]).is_err());\n}\n</code></pre>\n</li>\n<li><p>Great job with the unit tests for vector overflow, that is super useful.</p>\n</li>\n<li><p>In <code>get_flat_idx</code>, Clippy recommends: <code>for (d, &amp;dlen) in self.dim.iter().enumerate()</code> (then use <code>dlen</code> instead of <code>self.dim[d]</code>). I agree, though in this case we still have to use <code>d</code> to index into <code>idx</code>.</p>\n</li>\n<li><p>In your implementation, the field <code>.data</code> is not intended to dynamically change size. For this reason, you could initialize with <code>Vec::with_capacity(n)</code> instead of <code>Vec::new()</code> in your <code>new_with()</code> function. You might also consider using a fixed-size or fixed-capacity array implementation, for example the <a href=\"https://docs.rs/arrayvec/0.5.2/arrayvec/struct.ArrayVec.html\" rel=\"nofollow noreferrer\">ArrayVec</a> crate.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T14:42:56.037", "Id": "506280", "Score": "0", "body": "For the naming of `new`/`new_with` I followed the interface of [`Vec::resize`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.resize) which explicitly doesn't make `Default` special, but I agree with all of the other feedback. Thanks for the review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T17:54:06.190", "Id": "506292", "Score": "0", "body": "@apilat That is fair. Perhaps `new` for your version and `new_default` for the `Default` version would be the best names." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T17:16:58.970", "Id": "256383", "ParentId": "256345", "Score": "3" } } ]
{ "AcceptedAnswerId": "256383", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T18:16:54.950", "Id": "256345", "Score": "6", "Tags": [ "array", "rust" ], "Title": "N-dimensional array in Rust" }
256345
<p>I am implementing a class to mimic dynamic array as a part of my learning process of data structures. I have written the following class which works as a dynamic array data structure.</p> <p>I have gone through some video tutorials and also read some code from Java's <code>ArrayList</code> implementation to understand how to code it in a simple manner. I would like to get the code reviewed from the following perspective:</p> <ol> <li>Is there any design pattern that I should be following</li> <li>Improvements like removing compile time warning related to generics.</li> <li>Any tips on including test cases that can expose hidden issues in the code</li> <li>Any other tips that will make it a better code like improve its performance or make it more modular.</li> </ol> <pre><code>import java.util.Arrays; import java.util.Iterator; public class DynamicArray&lt;T&gt; implements Iterable&lt;T&gt; { private Object[] elements; private int length = 0; private int capacity = 0; public DynamicArray() { this(10); } public DynamicArray(int capacity) { this.capacity = capacity; this.length = 0; this.elements = new Object[capacity]; } public int size() { return length; } public boolean isEmpty() { return size() &gt; 0; } public T get(int index) { validateIndexValue(index); return (T)elements[index]; } public void set(int index, T element) { validateIndexValue(index); elements[index] = element; } public void clear() { for(int i = 0; i &lt; length; i++) { elements[i] = null; } length = 0; } public boolean add(T element) { ensureCapacity(length + 1); elements[length++] = element; return true; } public T removeAt(int index) { validateIndexValue(index); T element = (T) elements[index]; removeElement(index); return element; } public boolean remove(T element) { if(element == null) { for(int i = 0; i &lt; length; i++) { if(elements[i] == null) { removeElement(i); return true; } } } else { for(int i = 0; i &lt; length; i++) { if(element.equals(elements[i])) { removeElement(i); return false; } } } return false; } public int indexOf(T element) { if(element == null) return -1; for(int i = 0; i &lt; length; i++) { if(element.equals(elements[i])) { return i; } } return -1; } public boolean contains(T element) { return indexOf(element) &gt; -1; } public java.util.Iterator&lt;T&gt; iterator() { return new java.util.Iterator&lt;T&gt;() { int index = 0; public boolean hasNext() { return index &lt; length; } public T next() { return (T) elements[index++]; } }; } private void removeElement(int index) { int elementsToMove = length - index - 1; if(elementsToMove &gt; 0) { System.arraycopy(elements, index + 1, elements, index, elementsToMove); } elements[--length] = null; } private void ensureCapacity(int minSize) { if(minSize &gt;= capacity) { capacity *= 2; elements = Arrays.copyOf(elements, capacity); } } private void validateIndexValue(int index) { if(index &gt;= length || index &lt; 0) { throw new IllegalArgumentException(&quot;Bad index value passed : &quot; + index); } } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T23:20:37.273", "Id": "506094", "Score": "0", "body": "`element.equals(elements[i] == null)` - do you really mean it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T03:02:29.860", "Id": "506101", "Score": "0", "body": "Sorry @vnp , missed it while adding the code in the question. Changed it now" } ]
[ { "body": "<h1>Unit testing</h1>\n<p>Definitely write some test cases for your code. JUnit would be one possibility, but there are many test frameworks to choose from.</p>\n<p>With any test framework, and <strong><em>at least</em></strong> one test per public method, this goof would have been immediately apparent:</p>\n<pre class=\"lang-java prettyprint-override\"><code> public boolean isEmpty() {\n return size() &gt; 0;\n }\n</code></pre>\n<p>As Timothy Truckle points out in a comment below, one test per public method is not enough.</p>\n<h1>Misleading method argument name/implementation</h1>\n<p>While the way that you used <code>ensureCapacity(length + 1)</code> will work, it hides a subtle bug.</p>\n<pre class=\"lang-java prettyprint-override\"><code> private void ensureCapacity(int minSize) {\n if(minSize &gt;= capacity) {\n capacity *= 2;\n elements = Arrays.copyOf(elements, capacity);\n }\n }\n</code></pre>\n<p>Consider if you exposed the method <code>ensureCapacity(int minSize)</code> as a public method, like the standard library's <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/ArrayList.html#ensureCapacity(int)\" rel=\"nofollow noreferrer\"><code>ArrayList#ensureCapacity</code></a> method. A caller might use:</p>\n<pre class=\"lang-java prettyprint-override\"><code> var container = new DynamicArray&lt;Integer&gt;();\n container.ensureCapacity(10000);\n // ...\n</code></pre>\n<p>The first statement creates the container, with an initial capacity of 10. The next statement looks to resize the container to hold 10000 integers, but what actually happens is, since 10000 is larger than the current capacity, the capacity is doubled to 20.</p>\n<p>Instead of <code>capacity *= 2;</code> perhaps you would want something more along the lines of:</p>\n<pre class=\"lang-java prettyprint-override\"><code> private void ensureCapacity(int minSize) {\n if(minSize &gt;= capacity) {\n capacity = Math.max(capacity * 2, minSize);\n elements = Arrays.copyOf(elements, capacity);\n }\n }\n</code></pre>\n<h1>Initial Capacity</h1>\n<p>Even without exposing <code>ensureCapacity(int minSize)</code> as a public function, the following test will cause the bug to appear in a different way, causing a <code>ArrayIndexOutOfBounds</code> exception:</p>\n<pre class=\"lang-java prettyprint-override\"><code> var container = new DynamicArray&lt;Integer&gt;(0);\n container.add(10);\n</code></pre>\n<p>The initial capacity is zero. In attempting to add an item, the <code>length + 1</code> will exceed the capacity of zero, so the capacity will be doubled from zero to ... zero! Then, <code>elements[length++] = element;</code> will access the first element from an array of length 0. Oops.</p>\n<p>You could prevent this with validation in the constructor ...</p>\n<pre class=\"lang-java prettyprint-override\"><code> if(capacity &lt;= 0)\n throw new IllegalArgumentException(&quot;Capacity must be positive&quot;);\n</code></pre>\n<p>With the <code>capacity = Math.max(capacity * 2, minSize);</code> fix, this could be relaxed to allow an initial capacity of zero:</p>\n<pre class=\"lang-java prettyprint-override\"><code> if(capacity &lt; 0)\n throw new IllegalArgumentException(&quot;Capacity cannot be negative&quot;);\n</code></pre>\n<h1>Iteration</h1>\n<p>You define an <code>Iterator</code> for your <code>DynamicArray</code>, but if the array is modified while your iterator is in flight over the list, odd things may happen.</p>\n<p>For example: If you have a <code>DynamicArray&lt;String&gt;</code> containing <code>&quot;foo&quot;</code>, <code>&quot;bar&quot;</code> and <code>&quot;baz&quot;</code>, you might create the iterator and retrieve the first item: <code>&quot;foo&quot;</code>. If you then performed <code>.removeElement(0)</code>, the next element returned by the iterator would be <code>&quot;baz&quot;</code>, not <code>&quot;bar&quot;</code>!</p>\n<p>The standard collections will raise a <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/ConcurrentModificationException.html\" rel=\"nofollow noreferrer\"><code>ConcurrentModificationException</code></a> in these cases. They achieve this by maintaining a <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/AbstractList.html#modCount\" rel=\"nofollow noreferrer\"><code>modCount</code></a> in the container. Each <code>.add()</code> or <code>.remove()</code> operation would increment this by one. When the iterator is created, it captures the current <code>modCount</code> value for the container. On every iterator operation, it checks to see if the <code>modCount</code> has unexpectedly changed, and if so, raise the exception.</p>\n<h1>Compile time warnings related to generics</h1>\n<p>You can add <code>@SuppressWarnings(&quot;unchecked&quot;)</code> annotation to a statement, method, or an entire class. Ideally, you should apply the annotations to the smallest possible scopes to avoid accidentally suppressing warnings you didn't intend to.</p>\n<p>See <a href=\"https://stackoverflow.com/a/1129812/3690024\">this answer</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T18:37:04.437", "Id": "506164", "Score": "2", "body": "I strongly agree to the suggestion to write *unittests*, But instead of focusing on the code by *\"writing one test method per public method\"* we write *\"one test method per atomic **expectation** about the units **behavior**\"*. The difference is, that with the *behavior driven approach* you have to justify with a test, that a (public) method is needed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T06:03:28.960", "Id": "256362", "ParentId": "256348", "Score": "2" } }, { "body": "<pre class=\"lang-java prettyprint-override\"><code>return size() &gt; 0;\n</code></pre>\n<p>Typo, should be (less than or) equal zero.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for(int i = 0; i &lt; length; i++) {\n elements[i] = null;\n }\n length = 0;\n</code></pre>\n<p>It might be interesting to actually throw the array away and get a clean one in place, for example if this list was previously filled with 100 million entries.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public boolean add(T element) {\n ensureCapacity(length + 1);\n elements[length++] = element;\n return true;\n }\n</code></pre>\n<p>Given that this can never return <code>false</code>, it might be interesting to return a more meaningful value instead, for example the current instance. That would allow a fluent use when adding multiple values:</p>\n<pre class=\"lang-java prettyprint-override\"><code>dynamicArray\n .add(someObject)\n .add(anotherObject)\n .add(yetAnotherObject);\n</code></pre>\n<hr />\n<p>Your <code>remove</code> accepts <code>null</code>, <code>indexOf</code> does not. Both should accept <code>null</code>, then you can also use <code>indexOf</code> in <code>remove</code>.</p>\n<pre class=\"lang-java prettyprint-override\"><code> public boolean remove(T element) {\n int index = indexOf(element);\n \n if (index &gt;= 0) {\n removeElement(index);\n \n return true;\n } else {\n return false;\n }\n }\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> private void ensureCapacity(int minSize) {\n if(minSize &gt;= capacity) {\n capacity *= 2;\n elements = Arrays.copyOf(elements, capacity);\n }\n }\n</code></pre>\n<p>Depending on the use-case, this might be overkill. Maybe a little bit more flatter, conservative curve might be appropriate.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> private void validateIndexValue(int index) {\n if(index &gt;= length || index &lt; 0) {\n throw new IllegalArgumentException(&quot;Bad index value passed : &quot; + index);\n }\n }\n</code></pre>\n<p>Split it into two exception, one for negative values and one for too large values, to make it easier to debug.</p>\n<hr />\n<p>You stuck to the conventions already established in the Java world, that's great, so is your naming of things for the most part. I'd rename <code>validateIndexValue</code> to <code>verifyIndex</code> or <code>assertIndex</code>, though, &quot;assert&quot; might yield the wrong message.</p>\n<hr />\n<p>As far as I can see, you can infer <code>capacity</code> from the array size.</p>\n<hr />\n<p>Overall, looks quite well. Javadoc is missing, you should write one, it's a good exercise and will make you recheck your implementation.</p>\n<p>Let's talk API design.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class DynamicArray&lt;T&gt; implements Iterable&lt;T&gt; {\n private Object[] elements;\n private int length = 0;\n private int capacity = 0;\n\n public DynamicArray();\n public DynamicArray(int capacity);\n public int size();\n public boolean isEmpty();\n public T get(int index);\n public void set(int index, T element);\n public void clear();\n public boolean add(T element);\n public T removeAt(int index);\n public boolean remove(T element);\n public int indexOf(T element);\n public boolean contains(T element);\n public java.util.Iterator&lt;T&gt; iterator();\n \n private void removeElement(int index);\n private void ensureCapacity(int minSize);\n private void validateIndexValue(int index);\n}\n</code></pre>\n<p>Your class is only extensible as far as the <code>public</code> methods go. If I wanted to extend this class and implement a <code>swap</code> method, I will have a hard time doing that. Implementing a different size strategy will basically mean rewriting methods. Now, how could we improve that situation? The easiest is to make the internal properties <code>protected</code>, it's not exactly a neat or fancy solution, but if somebody wants to implement additional methods, they will have all the necessary access.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class DynamicArray&lt;T&gt; implements Iterable&lt;T&gt; {\n protected Object[] elements;\n protected int length = 0;\n protected int capacity = 0;\n\n // public SNIP\n \n protected void removeElement(int index);\n protected void ensureCapacity(int minSize);\n protected void validateIndexValue(int index);\n}\n</code></pre>\n<p>That gives every extending class the same access as you had, meaning that implementing a swap method or different strategy will be easy to do. But many people will now start ranting about how that is bad design (I disagree on that matter, but let's leave it at that). So we arrive at the question: Can we give an extending class enough access to implement additional functionality, but also protect base functionality? For example, now <code>elements</code> could be <code>null</code> after any call.</p>\n<p>We can, we can guard our <code>elements</code> array behind some functions that ensure its well being:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class DynamicArray&lt;T&gt; implements Iterable&lt;T&gt; {\n private Object[] elements;\n private int length = 0;\n \n protected final Object[] getElements[] {\n return elements;\n }\n \n protected final int getLength() {\n return length;\n }\n \n protected final setElements(Object[] elements, int length) {\n requireNotNull(elements);\n requireZeroOrPositive(length);\n requireLessThan(length, elements.length);\n \n this.elements = elements;\n this.length = length;\n }\n \n protected final setLength(int length) {\n requireZeroOrPositive(length);\n requireLessThan(length, elements.length);\n \n this.length = length;\n }\n \n // SNIP methods as above\n}\n</code></pre>\n<p>Neatish, I'd say. This allows us to make fair assumptions about the internal state. It also gives the extending class any freedom to access and modify the array, without the possibility to nulling the reference. Note that modifying the array directly is still possible, and I'd argue that that should stay that way, because the extending class must be able to modify it. Forcing the extending class to retrieve a copy of the array, modify that copy and set it back will do nothing but waste memory and processing power.</p>\n<p>With that in place, a swapping method in an extending class can look like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public void swap(int firstIndex, int secondIndex) {\n validateIndexValue(firstIndex);\n validateIndexValue(secondIndex);\n \n Object[] elements = getElements();\n \n T firstElement = elements[firstIndex];\n T secondElement = elements[secondIndex];\n \n elements[firstIndex] = secondElement;\n elements[secondIndex] = firstElement;\n}\n</code></pre>\n<p>Which is as simple as it can get.</p>\n<p>Of course, the internal state can still be &quot;corrupted&quot; to a certain part, by setting a &quot;wrong&quot; <code>length</code> value, but I'd argue that that is the problem of the extending class. After all, the extending class could also override <code>add</code> to perform a division with zero. We can't and <em>should not</em> guard against anything, otherwise you'll have a too restrictive API/class design which will make it impossible to extend your classes. In the real world, that means to either throw out your class, or copy and modify the code of the class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T16:20:39.697", "Id": "506147", "Score": "0", "body": "\"return size() > 0;\" Typo, should be less than zero. Really?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T16:28:00.533", "Id": "506149", "Score": "0", "body": "@MarkBluemel Well, what can I say, was a typo...thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T16:11:50.377", "Id": "256381", "ParentId": "256348", "Score": "2" } } ]
{ "AcceptedAnswerId": "256381", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T19:16:08.233", "Id": "256348", "Score": "4", "Tags": [ "java", "performance", "array" ], "Title": "Dynamic Array in java" }
256348
<p>You probably know the following problem: You have written a small program that runs in your console and want the user to enter something. of course, it is very inconvenient when the user types the wrong things, so we have to prepare for any small child hacking like a madman on the keyboard.</p> <p>Most functions wait for a valid input, which results in the problem that nasty line breaks occur when the user ONLY presses the enter key.</p> <p>the problem is also normally easy to solve under Linux: read a character with <code>getchar</code>, determined the position of the cursor with the ANSI escape sequences and provided the whole thing with a do while loop.</p> <p>BUT: I was not able to find a simple function to read in numbers in the same elegant way. The function must be able to read in numbers, but also be able to prevent line breaks. to achieve this, I used <code>getchar</code> and store the characters in a char array, whose indices I then convert to the corresponding numbers, which I then add to the actual number.</p> <p>But maybe there is an easier way? or you have ideas how to optimize the function?</p> <pre><code>#include &lt;iostream&gt; #include &quot;TheGameHeaders.h&quot; #define CLEAR_LINE printf(&quot;\033[K&quot;) #define POSITION(Ze, Sp) printf(&quot;\033[%d;%dH&quot;, Ze, Sp) #define CLEAR printf(&quot;\033[2J&quot;) int getint(int pos_ze, int pos_sp, int qntty_of_incs) { int i = 0; char fake_nbr; char fake_nbrs[qntty_of_incs]; int real_nbr = 0; int real_nbrs[qntty_of_incs]; do { POSITION(pos_ze, pos_sp); while((fake_nbr = getchar()) != '\n') { if(fake_nbr == '0' || fake_nbr == '1' || fake_nbr == '2' || fake_nbr == '3' || fake_nbr == '4' || fake_nbr == '5' || fake_nbr == '6' || fake_nbr == '7' || fake_nbr == '8' || fake_nbr == '9') { if(i &lt;= (qntty_of_incs-=1)) { fake_nbrs[i] = fake_nbr; i++; qntty_of_incs++; } else { return 1; } } else { return 0; } } } while(i &lt; 1); for(int a = 0; a &lt; i; a++) { fake_nbrs[a] -= '0'; real_nbrs[a] = fake_nbrs[a]; } int i_fix = i; int i_fix_2 = i-=1; for(int a = 0; a &lt; i_fix; a++) { i = i_fix_2; real_nbrs[a] *= pow(10, i-=a); } for(int a = 0; a &lt; i_fix; a++) { real_nbr += real_nbrs[a]; } return real_nbr; } </code></pre> <p>oh and <code>pow</code> is a simple function:</p> <pre><code>int pow(int base, int exponent) { if(exponent == 0) { return 1; } exponent -= 1; int fixBase = base; for(int i = 0; i &lt; exponent; i++) { fixBase *= base; } return fixBase; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T01:44:57.953", "Id": "506097", "Score": "1", "body": "This is not C++. This is C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T07:46:39.467", "Id": "506111", "Score": "1", "body": "maybe it looks like c because i learned some c before i started with c++ but this is definitely c++" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T11:14:50.510", "Id": "506119", "Score": "1", "body": "No, it’s definitely C. It’s not just “bad-C++-that-looks-like-C”, it’s C; it won’t even compile in a C++ compiler without C extensions. It’s just C code with `#include <iostream>` at the top (for no good reason anyway, because it’s never used). You might as well put `import sys` at the top and call it Python." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T18:09:05.580", "Id": "506162", "Score": "1", "body": "Have to agree this is C code. It may happen to compile with a lenient C++ compiler but that does not change it from C code that happens to use some C++ features accidently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T21:06:25.817", "Id": "506243", "Score": "1", "body": "@Lui stop treating c++ like c. If you’re going to learn c++ you must learn modern c++ (otherwise there’s no point you are just using the c part of c++). Modern c++ and c having nothing in common (except like curly braces). To get you started on modern c++ learn about oop, smart pointers and the stl. Trust me, c++ and c are completely different (look at template meta programming if you don’t believe me)." } ]
[ { "body": "<h2>Overview</h2>\n<p>Looks like you are reading data from the standard input and converting to a number. There is already code for that:</p>\n<pre><code>int val;\nstd::cin &gt;&gt; val;\n</code></pre>\n<p>You use C functionality throughout this code (printf/arrays/getchar) where there are better C++ alternatives (std::cout/vector/std::cin). A lot of this work can be delegated to standard functions.</p>\n<h2>Code Review</h2>\n<pre><code>#include &lt;iostream&gt;\n</code></pre>\n<p>What are these headers and what do they define?</p>\n<pre><code>#include &quot;TheGameHeaders.h&quot;\n</code></pre>\n<hr />\n<p>This is very terminal specific.</p>\n<pre><code>#define CLEAR_LINE printf(&quot;\\033[K&quot;)\n#define POSITION(Ze, Sp) printf(&quot;\\033[%d;%dH&quot;, Ze, Sp)\n#define CLEAR printf(&quot;\\033[2J&quot;)\n</code></pre>\n<p>A lot of terms might support this but it is not universal. Have a look at ncurses library; that will provide a terminal-neutral way to achieve all this. ncurses, and curses before it, look up these control characters from their terminal databases and retrieve the terminal-specific escape codes.</p>\n<hr />\n<p>This is not standard C++:</p>\n<pre><code> char fake_nbrs[qntty_of_incs];\n</code></pre>\n<p>If you want dynamic (run time sized) arrays, then you should be using <code>std::vector&lt;&gt;</code></p>\n<hr />\n<p>We have standard functions for checking for numbers:</p>\n<pre><code> while((fake_nbr = getchar()) != '\\n')\n {\n if(fake_nbr == '0' || fake_nbr == '1' || fake_nbr == '2' || fake_nbr == '3' || fake_nbr == '4' || fake_nbr == '5' || fake_nbr == '6' || fake_nbr == '7' || fake_nbr == '8' || fake_nbr == '9')\n</code></pre>\n<p>Have a look at:</p>\n<pre><code> std::isdigit()\n</code></pre>\n<hr />\n<p>Returning valid integer numbers to indicate failure conditions is probably not a good idea.</p>\n<pre><code> else\n {\n return 1;\n }\n }\n else\n {\n return 0;\n }\n</code></pre>\n<p>How can the user of your code tell if this is real user input or an error?</p>\n<hr />\n<p>You use several loops to convert the each number to its correct value. Why not do this in a single loop?</p>\n<pre><code> for(int a = 0; a &lt; i; a++)\n {\n fake_nbrs[a] -= '0';\n real_nbrs[a] = fake_nbrs[a];\n }\n\n int i_fix = i;\n int i_fix_2 = i-=1;\n\n for(int a = 0; a &lt; i_fix; a++)\n {\n i = i_fix_2;\n real_nbrs[a] *= pow(10, i-=a);\n }\n\n for(int a = 0; a &lt; i_fix; a++)\n {\n real_nbr += real_nbrs[a];\n }\n</code></pre>\n<p>Seems simpler like this:</p>\n<pre><code> int result = 0\n for(int a = j; a &gt; 0; a--) {\n result = (result * 10) + (fake_nbrs[a - 1] - '0');\n }\n</code></pre>\n<hr />\n<p>There already exists a standard power function in the maths library.</p>\n<pre><code>int pow(int base, int exponent)\n</code></pre>\n<hr />\n<p>Nice touch. Most people forget this part.</p>\n<pre><code> if(exponent == 0)\n {\n return 1;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T18:23:09.837", "Id": "256386", "ParentId": "256349", "Score": "2" } }, { "body": "<p><strong>OP's <code>pow()</code> inefficient</strong></p>\n<p>Rather than iterate <code>n</code> times, form the power by <a href=\"https://en.wikipedia.org/wiki/Exponentiation_by_squaring#Basic_method\" rel=\"nofollow noreferrer\">squaring</a> and iterate <code>log2(n)</code> times.</p>\n<pre><code>// Shown without overflow protection for brevity.\nint pow_i(int base, int expo) {\n assert(expo &gt;= 0); // Leave expo &lt; 0 as TBD code\n\n int ipow = 1;\n while (expo &gt; 0) {\n if (expo % 2) {\n ipow *= base;\n }\n base *= base;\n expo /= 2;\n }\n return ipow;\n}\n</code></pre>\n<p><strong>OP's <code>pow()</code> not needed</strong></p>\n<p>Alternate algorithm</p>\n<pre><code>sum = 0\nwhile (isdigit((c = get_next_character)\n sum = sum * 10 + (c - '0')\n</code></pre>\n<p><strong>Ten test cases not needed</strong></p>\n<p><code>'0'</code> .. <code>'9'</code> are <em>always</em> consecutive integer values.</p>\n<pre><code> // if(fake_nbr == '0' || fake_nbr == '1' || fake_nbr == '2' || fake_nbr == '3' || fake_nbr == '4' || fake_nbr == '5' || fake_nbr == '6' || fake_nbr == '7' || fake_nbr == '8' || fake_nbr == '9')\n if(fake_nbr =&gt; '0' &amp;&amp; fake_nbr &lt;= '9')\n</code></pre>\n<p>Or use <code>isdgit()</code> - be sure to avoid negative <code>char</code> values.</p>\n<pre><code> if (isdigit( (unsigned char)fake_nbr )) \n</code></pre>\n<p><strong>No protection against overflow</strong></p>\n<p><code>int getint()</code> should detect potential <code>int</code> overflow and return a well defined result.</p>\n<p><strong>A little documentation goes a long way</strong></p>\n<p><code>int getint(int pos_ze, int pos_sp, int qntty_of_incs)</code> lacks description of functionality and parameters uses.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T07:22:30.233", "Id": "257712", "ParentId": "256349", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T19:22:52.280", "Id": "256349", "Score": "0", "Tags": [ "c++", "performance", "beginner" ], "Title": "getint-like function" }
256349
<p>I am working on a Reinforcement learning project, where I have to gather a lot of data using a TensorFlow model. During the data gathering, the weights of the model do not change. So, I am using <code>concurrent.futures.ProcessPoolExecutor</code> to parallelize this work-flow. The following is an MWE of my implementation.</p> <pre><code>import tensorflow as tf from tensorflow import keras import numpy as np import concurrent.futures import time def simple_model(): model = keras.models.Sequential([ keras.layers.Dense(units = 10, input_shape = [1]), keras.layers.Dense(units = 1, activation = 'sigmoid') ]) model.compile(optimizer = 'sgd', loss = 'mean_squared_error') return model def clone_model(model): model_clone = tf.keras.models.clone_model(model) model_clone.set_weights(model.get_weights()) return model_clone def work(model_path, seq): # model = clone_model(model)# model_list[model_id] # print(model) # import tensorflow as tf model = tf.keras.models.load_model(model_path) return model.predict(seq) def workers(model, num_of_seq = 4): seqences = np.arange(0,num_of_seq*10).reshape(num_of_seq, -1) model_savepath = './simple_model.h5' model.save(model_savepath) path_list = [model_savepath for _ in range(num_of_seq)] with concurrent.futures.ProcessPoolExecutor(max_workers=None) as executor: t0 = time.perf_counter() # model_list = [clone_model(model) for _ in range(num_of_seq)] index_list = np.arange(1, num_of_seq) # [clone_model(model) for _ in range(num_of_seq)] # print(model_list) future_to_samples = {executor.submit(work, path, seq): seq for path, seq in zip(path_list,seqences)} Seq_out = [] for future in concurrent.futures.as_completed(future_to_samples): out = future.result() Seq_out.append(out) t1 = time.perf_counter() print(t1-t0) return np.reshape(Seq_out, (-1, )), t1-t0 if __name__ == '__main__': model = simple_model() num_of_seq = 400 out = workers(model, num_of_seq=num_of_seq) print(out) </code></pre> <p>Are there any better approaches to this problem?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-22T19:29:03.217", "Id": "256350", "Score": "3", "Tags": [ "python", "multithreading", "multiprocessing", "tensorflow" ], "Title": "Assigning parallel workers to predict from keras model using concurrent.futures" }
256350
<p>I created the following function, <code>permutations</code>, to produce all permutations of a <code>List[A]</code>.</p> <p>Example:</p> <pre><code>scala&gt; net.Permutations.permutations(&quot;ab&quot;.split(&quot;&quot;).toList) res3: List[List[String]] = List(List(a, b), List(b, a)) </code></pre> <p>Code:</p> <pre><code>object Permutations { def permutations[A](str: List[A]): List[List[A]] = str match { case Nil =&gt; List(Nil) case list @ _ :: _ =&gt; val shifteds: List[List[A]] = shiftN(list, list.length) shifteds.flatMap { case head :: tail =&gt; permutations(tail).map { lists: List[A] =&gt; head :: lists } case Nil =&gt; Nil } } private def shiftN[A](list: List[A], n: Int): List[List[A]] = { if (n &lt;= 0) Nil else { val shifted: List[A] = shift(list) shifted :: shiftN(shifted, n - 1) } } private def shift[A](arr: List[A]): List[A] = arr match { case head :: tail =&gt; tail ++ List(head) case Nil =&gt; Nil } } </code></pre> <p>I think it's correct since the following property-based check succeeds:</p> <pre><code>import munit.ScalaCheckSuite import org.scalacheck.Prop._ import org.scalacheck.Gen class PermutationsSpec extends ScalaCheckSuite { private val listGen: Gen[List[Int]] = for { n &lt;- Gen.choose(0, 7) list &lt;- Gen.listOfN(n, Gen.posNum[Int]) } yield list property(&quot;permutations works&quot;) { forAll(listGen) { list: List[Int] =&gt; val mine: List[List[Int]] = Permutations.permutations(list) val stdLib: List[List[Int]] = list.permutations.toList assert(stdLib.diff(mine).isEmpty) } } } </code></pre> <p>Please evaluate for correctness, concision and performance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T04:39:24.700", "Id": "506193", "Score": "0", "body": "Your definition of _permutation_ differs from that of the Scala standard library: `permutations(List(1,2,2)).length` vs `List(1,2,2).permutations.length`. Is that intentional?" } ]
[ { "body": "<p>Here is a another solution using fold that has the similar performance characteristics. One difference is that it doesn't have to compute the linear List Length</p>\n<pre><code>\n def inserts[A](x: A): List[A] =&gt; List[List[A]] =\n ls =&gt;\n ls match {\n case Nil =&gt; List(List(x))\n case (y :: ys) =&gt; (x :: y :: ys) :: (inserts(x)(ys)).map( y :: _)\n }\n def permutations[A](ls: List[A]): List[List[A]] =\n ls.foldRight(List(List[A]()))((x, xss) =&gt; xss.flatMap(inserts(x)))\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T09:16:24.100", "Id": "506208", "Score": "1", "body": "Welcome to CodeReview@SE. I see an independent solution proposed. `doesn't have to compute [list length]` is a bit thin on [*insight about the code presented for review*](https://codereview.stackexchange.com/help/how-to-answer) - CR is *not* about *insight about the problem the code presented is to solve*." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T06:36:23.577", "Id": "256399", "ParentId": "256359", "Score": "-1" } }, { "body": "<p>The code looks to be correct, yes, the testing looks good too. I was\nthinking whether <code>List(List())</code> for the input <code>List()</code> makes sense, but\nit seems like that's a sensible output.</p>\n<p>For the code readability I'd rename <code>str</code>, especially since it's not\nreally a string, but a <code>list</code>. The complicated match expression in\n<code>permutations</code> can just be simplified to <code>case _</code> and in the body the\noriginal argument can be reused again.</p>\n<p>I'd also inline <code>shifteds</code> value since it's just a single call and the\nname doesn't really tell me anything. On that note, docstrings for the\nfunctions might be a nice touch, especially for the <code>shift</code> and <code>shiftN</code>\nmethods.</p>\n<p>The unused case labels can also just be <code>_</code> everywhere. Depends of\ncourse, for me this makes it clearer that really there's always just two\ncases, either matching an empty list, or a non-empty one, there's no\nthird case.</p>\n<p>Would look like this then:</p>\n<pre class=\"lang-scala prettyprint-override\"><code>object Permutations {\n def permutations[A](list: List[A]): List[List[A]] =\n list match {\n case Nil =&gt; List(Nil)\n case _ =&gt;\n shiftN(list, list.length).flatMap {\n case head :: tail =&gt;\n permutations(tail).map(head :: _)\n case _ =&gt; Nil\n }\n }\n\n def shiftN[A](list: List[A], n: Int): List[List[A]] = {\n if (n &lt;= 0) Nil\n else {\n val shifted: List[A] = shift(list)\n shifted :: shiftN(shifted, n - 1)\n }\n }\n\n def shift[A](list: List[A]): List[A] = list match {\n case head :: tail =&gt; tail ++ List(head)\n case _ =&gt; Nil\n }\n}\n</code></pre>\n<p>Lastly, performance-wise it depends what your constraints are: For\n<code>List</code> input and <code>List</code> output, restricting it to single linked lists,\nthis is fine, though I haven't benchmarked them of\ncourse. Potentially converting the <code>shifted :: shiftN(...)</code> call into\nusing an accumulator might be worth a bit, instead of having a deep call\nstack, but again, it'll probably only matter for longer inputs.</p>\n<p>But there are way quicker algorithms, though you might want to copy the\ninput into a vector that can be accessed in constant time for each\nindex. (I found the\n<a href=\"https://www.baeldung.com/cs/array-generate-all-permutations\" rel=\"nofollow noreferrer\">QuickPerm algorithm, as explained here</a>\nabsolutely straightforward to implement from scratch.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T10:03:36.543", "Id": "256402", "ParentId": "256359", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T04:15:36.220", "Id": "256359", "Score": "1", "Tags": [ "scala", "combinatorics" ], "Title": "Find All Permutations of String in Scala" }
256359
<p>I am working on a part of an IoT project where I have been given a task to develop a mechanism to store data locally when there is no network coverage or if the network is down for some reason. Our application is architected such that, every hour we store the feed/sensor data to a bucket i.e.local storage and we have a network task that constantly checks for data in the bucket. If there is data, then it transmits all the data to the server. I have developed this software component and performed some unit tests. So far everything seems to work fine and I don't see any obvious issues with it. However, I believe there may be loopholes that I am overseeing and loads of scope for improvements in terms of the code structure and logic. Hence, I'd like to present you with all my code and seek your expert advice, and review feedbacks. Thank you for your time and patience.</p> <p>Below is the header file.</p> <pre><code>/* * Bucket.h * * Created: 17/12/2020 12:57:45 PM * Author: Vinay Divakar */ #ifndef BUCKET_H_ #define BUCKET_H_ #define BUCKET_SIZE 32 // Range 10-32000 Memory in bytes allocated to bucket for edge storage #define BUCKET_MAX_FEEDS 32 // Range 2-64 Number of unique feeds the bucket can hold #define BUCKET_MAX_VALUE_SIZE 64 // Maximum value string length // Values passed via void pointer so this is needed so functions know how to use the void pointer typedef enum { UINT16, STRING } cvalue_t; // Used to register feeds to the bucket and for passing sensor data to the bucket typedef struct { const char* key; // MUST BE CONST, since the feeds reference key will never change. cvalue_t type; // Data type void* value; // Value uint32_t unixTime; // Timestamp } cbucket_t; int8_t BucketRegisterFeed(cbucket_t *feed); int8_t BucketPut(const cbucket_t *data); int8_t BucketGet( char *keyOut, char *dataOut, uint32_t *timestampOut); uint8_t BucketNumbOfRegisteredFeeds(void); void BucketZeroize(void); //Debug functions void DebugPrintRegistrationData(void); void DebugPrintBucket(void); void DebugPrintBucketTailToHead(void); #endif /* BUCKET_H_ */ </code></pre> <p>Below is the source code.</p> <pre><code>/* * Bucket.c * * Created: 17/12/2020 12:57:31 PM * Author: Vinay Divakar * Description: This module is used to accumulate data when the network is down or unable to transmit data due to poor signal quality. It currently supports uint16_t and string data types. The bucket is designed to maximize the amount of data that can be stored in a given amount of memory for typical use. The feeds must be registered before they can be written to or read from the bucket. The BucketPut API writes the feed to the bucket. E.g. 1: If the BucketPut sees that consecutive feeds written have the same timestamp, then it writes the data as shown below. This is done to save memory. [Slot] [Data] [Slot] [Data] [Slot] [Data]...[Timestamp] E.g. 2: If the BucketPut sees that consecutive feeds written have different timestamps, then it writes the data as shown below. [Slot] [Data] [Timestamp] [Slot] [Data] [Timestamp] [Slot] [Data] [Timestamp]... E.g. 3: If the BucketPut sees a mixture of above, then it writes the data as shown below. [Slot] [Data] [Slot] [Data] [Slot] [Data] [Timestamp] [Slot] [Data] [Timestamp] [Slot] [Data] [Slot] [Data] [Timestamp] The BucketGet API reads the feed in the following format. [Key] [Value] [Timestamp] * Notes: 1. Module hasn't been tested for the STRING data type. */ /* *==================== * Includes *==================== */ #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &quot;atmel_start.h&quot; #include &quot;Bucket.h&quot; //#include &quot;INIconfig.h&quot; /* For debug purposes */ const char* cvaluetypes[] = {&quot;UINT16&quot;, &quot;STRING&quot;}; /* *==================== * static/global vars *==================== */ // Stores the registered feed cbucket_t *registeredFeed[BUCKET_MAX_FEEDS]; const uint8_t unixTimeSlot = 0xFF; //virtual time slot // Bucket memory for edge storage and pointers to keep track or reads and writes uint8_t cbucketBuf[BUCKET_SIZE]; uint8_t *cBucketBufHead = &amp;cbucketBuf[0]; uint8_t *cBucketBufTail = &amp;cbucketBuf[0]; /* *==================== * Fxns *==================== */ int8_t _RegisteredFeedFreeSlot(void); void _PrintFeedValue(cbucket_t *feed); /**************************************************************** * Function Name : BucketZeroize * Description : Zeroize the bucket * Returns : None. * Params :None. ****************************************************************/ void BucketZeroize(void){ memset(cbucketBuf, 0, sizeof(cbucketBuf)); } /**************************************************************** * Function Name : BucketRegisterFeed * Description : Links cbucket structures from the main application to the bucket (Used to encode/decode data in/out of the bucket) * Returns : true on success else negative. * Params @feed :Feed to register ****************************************************************/ int8_t BucketRegisterFeed(cbucket_t *feed) { int8_t slot = _RegisteredFeedFreeSlot(); int8_t registrationSucess = -1; if (slot != -1) { registeredFeed[slot] = feed; registrationSucess = 0; } return registrationSucess; } /**************************************************************** * Function Name : BucketGetRegisteredFeedSlot * Description : Gets slot index of the registered feed * Returns : !0 on OK, -ve on error * Params @data: points to the feed struct ****************************************************************/ int8_t BucketGetRegisteredFeedSlot(const cbucket_t *data){ int8_t slotIdx = -1; /* Check if the feed had been previously registered */ for(int i = 0 ; i &lt; BUCKET_MAX_FEEDS ; i++) { //found it? if(data == registeredFeed[i]) { //Get the slot index slotIdx = i; i = BUCKET_MAX_FEEDS; } } return(slotIdx); } /**************************************************************** * Function Name : BucketCheckDataAvailable * Description : Checks for data in the bucket * Returns : false on empty else true. * Params None. ****************************************************************/ int8_t BucketCheckDataAvailable(void){ //Bucket is empty? if(cBucketBufTail == cBucketBufHead){ return(false); } return(true); } /**************************************************************** * Function Name : BucketGetTimeStamp * Description : Gets the timestamp for the specific key * Returns : true on OK, false on empty, -1 on error * Params : None. ****************************************************************/ int8_t BucketPutGetTimeStamp(uint32_t *timestamp){ int8_t status = false; //There's no data left to be read from the bucket i.e. tail = head if(BucketCheckDataAvailable() == false){ return(false); } //Attempt looking for the time slot, uint8_t *cBucketBufHeadTmp = cBucketBufHead; //Iterate through the cells while handling wraparounds for(int i = 0 ; i &lt; 5 ; i++){ if(cBucketBufHeadTmp == &amp;cbucketBuf[0]){ //if head points to start of bucket, wrap to end of the bucket cBucketBufHeadTmp = &amp;cbucketBuf[BUCKET_SIZE]; } //Step back one address cBucketBufHeadTmp--; } //Now, we should be pointing to the virtual time slot i.e. 0xff if(*cBucketBufHeadTmp == unixTimeSlot){ //Check if head points to the end of the bucket, wrap to start of the bucket if(cBucketBufHeadTmp == &amp;cbucketBuf[BUCKET_SIZE]){//if the last cell in the bucket is the time slot, skip it by wrapping around to point to the start of the bucket cBucketBufHeadTmp = &amp;cbucketBuf[0]; }else{//Inc address to skip the virtual time slot i.e. 0xFF cBucketBufHeadTmp++; } //load the timestamp *timestamp = 0; for(int i = 0 ; i &lt; sizeof(uint32_t) ; i++, cBucketBufHeadTmp++){ //Now if head points to end of bucket, read that value and wrap to start of bucket if(cBucketBufHeadTmp == &amp;cbucketBuf[BUCKET_SIZE]){//Handle if head needs to be wrapped around to read the timestamp cBucketBufHeadTmp = &amp;cbucketBuf[0]; //point to start of the bucket to continue reading the timestamp if(i == 0){ *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF); }else if(i == 1){ *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 8; }else if(i == 2){ *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 16; }else if(i == 3){ *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 24; } }else{//read value as is if(i == 0){ *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF); }else if(i == 1){ *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 8; }else if(i == 2){ *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 16; }else if(i == 3){ *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 24; } }//else }//for //we found it! status = true; }else{ //Did not find? likely to be the first write } return(status); } /**************************************************************** * Function Name : BucketGetDataSize * Description : Gets the size of the item * Returns : false on error, true on OK * Params @data :points to feed struct ****************************************************************/ uint8_t BucketGetDataSize(const cbucket_t *data){ uint8_t dataSizeOut = 0; if(data-&gt;type == UINT16) { //Total data size = 2 bytes i.e. 16 bit unsigned dataSizeOut = sizeof(uint16_t); }else if(data-&gt;type == STRING) { //Total data size = length of the string until null terminated. Now get the length of the string by looking upto '\0' const uint8_t *bytePtr = (uint8_t*)data-&gt;value; for(int i = 0; i &lt; BUCKET_MAX_VALUE_SIZE; i++, bytePtr++) { if(*bytePtr == '\0') { i = BUCKET_MAX_VALUE_SIZE; //Include the '\0' to be written. This will be used to indicate the end of string while reading dataSizeOut++; continue; } dataSizeOut++; } } else { return (false); } // invalid data type, discard it! return(dataSizeOut); } /**************************************************************** * Function Name : BucketWriteData * Description : Writes the item to the bucket * Returns : false on error or No. of bytes written. * Params @slotIdx = slot index of the feed. @dataSizeIn = size of the item. @bucketHeadPtr = ptr to ptr to bucket head. @data = ptr to feed struct. ****************************************************************/ uint8_t BucketWriteData(int8_t slotIdx, uint8_t dataSizeIn, const cbucket_t *data){ //Do a sanity check for the right data type if(data-&gt;type == UINT16){ } else if(data-&gt;type == STRING){ }else{ return(false); } if(cBucketBufHead &gt;= &amp;cbucketBuf[BUCKET_SIZE]) cBucketBufHead = &amp;cbucketBuf[0]; //Write the slot index to the bucket *cBucketBufHead++ = slotIdx; //Point to the value to be read byte by byte, in this case, data type of the value doesn't matter uint8_t *bytePtr = (uint8_t*)data-&gt;value; //By now we must have the right data size to be written. Write the item to the bucket for(uint8_t i = 0 ; i &lt; dataSizeIn ; i++, cBucketBufHead++) { if(cBucketBufHead &gt;= &amp;cbucketBuf[BUCKET_SIZE]) cBucketBufHead = &amp;cbucketBuf[0]; *cBucketBufHead = bytePtr[i]; } //Write the virtual address of the time slot. This address is used to identify the start of timestamp data i.e. 4 bytes. if(cBucketBufHead &gt;= &amp;cbucketBuf[BUCKET_SIZE]) cBucketBufHead = &amp;cbucketBuf[0]; *cBucketBufHead++ = unixTimeSlot; //Write the timestamp to the bucket corresponding to the above slot address uint32_t unixTimeTmp = data-&gt;unixTime; printf(&quot;[BucketWriteData], unixTimeTmp: %lu\r\n&quot;, unixTimeTmp); for(int i = 0; i &lt; sizeof(data-&gt;unixTime); i++, cBucketBufHead++){ if(cBucketBufHead &gt;= &amp;cbucketBuf[BUCKET_SIZE]) cBucketBufHead = &amp;cbucketBuf[0]; *cBucketBufHead = unixTimeTmp &amp; 0xFF; unixTimeTmp &gt;&gt;= 8; } return(true); } /**************************************************************** * Function Name : BucketPut * Description : writes to the bucket * Returns : true on success else negative.. * Params @data :points to struct to be written ****************************************************************/ int8_t BucketPut(const cbucket_t *data) { int8_t slot = 0; uint8_t dataSize = 0; //Find the slot for this feed slot = BucketGetRegisteredFeedSlot(data); if(slot &lt; 0){ printf(&quot;[BucketPut], Error, feed not registered\r\n&quot;); return(-1); } //Get th size of the item and handle storing as appropriate dataSize = BucketGetDataSize(data); if(dataSize == false){ printf(&quot;[BucketPut], Error, invalid feed type\r\n&quot;); return(-2); } //Get the amount space left in the bucket printf(&quot;[BucketPut], dataSize = %u\r\n&quot;, dataSize); int remaining = (cBucketBufTail + BUCKET_SIZE - cBucketBufHead-1) % BUCKET_SIZE; printf(&quot;bucket size = %d remaining = %hu \r\n&quot;, (int)BUCKET_SIZE, remaining); //Get the timestamp from the unix time slot i.e. special virtual slot to hold the timestamp uint32_t lastStoredTime = 0; if(BucketPutGetTimeStamp(&amp;lastStoredTime) == false){//last stored time slot not found?, likely because there was no data left to read and this is the first write after bucket empty //Check if there is enough space in the bucket for storing the current feed data. Total size to account for = slot size + data size + unix timestamp size + unix time slot size . uint8_t totalItemSize = dataSize + sizeof(slot) + sizeof(data-&gt;unixTime) + sizeof(unixTimeSlot); if(totalItemSize &gt; remaining) { printf(&quot;[BucketPut], Error, no space available, space = %hu, item size = %hu\r\n&quot;, remaining, totalItemSize); return(-4); }else{ printf(&quot;[BucketPut], available space = %hu total item size = %hu\r\n&quot;, remaining, totalItemSize); } }else{//last stored timestamp found, likely because there was some previous data in there if(lastStoredTime == data-&gt;unixTime){//last stored timestamp matches the current feeds timestamp printf(&quot;[BucketPut] Last stored timestamp[%lu] = Current feed timestamp[%lu]\r\n&quot;, lastStoredTime, data-&gt;unixTime); uint8_t totalItemSize = dataSize + sizeof(slot); if(totalItemSize &gt; remaining) { printf(&quot;[BucketPut], Error, no space available, space = %hu, item size = %hu\r\n&quot;, remaining, totalItemSize); return(-5); }else{ printf(&quot;[BucketPut], available space = %hu total item size = %hu\r\n&quot;, remaining, totalItemSize); } //Get total size of the time frame uint8_t stepOffset = sizeof(slot) + sizeof(data-&gt;unixTime); //move the head ptr backwards by size of time slot index + size of timestamp i.e. 5 bytes for(int i = 0 ; i &lt; stepOffset ; i++){ if(cBucketBufHead &lt;= &amp;cbucketBuf[0]){//if head points to start of the bucket, wrap to the end of the bucket and continue writing the value from there. cBucketBufHead = &amp;cbucketBuf[BUCKET_SIZE]; } cBucketBufHead--; //dec head by one } //Now, overwrite from here the new data and append with the new feeds timestamp which would be the same as the last stored timestamp. This is done to save memory. }else{//last stored timestamp is different from the current feeds timestamp printf(&quot;[BucketPut] Last stored timestamp[%lu] != Current feed timestamp[%lu]\r\n&quot;, lastStoredTime, data-&gt;unixTime); //Perform a usual write while appending the new timestamp for the current feed.Check if there is enough space in the bucket for storing the current feed data //Total size to account for = slot size + data size + unix timestamp size + unix time slot size . uint8_t totalItemSize = dataSize + sizeof(slot) + sizeof(data-&gt;unixTime) + sizeof(unixTimeSlot); if(totalItemSize &gt; remaining) { printf(&quot;[BucketPut], Error, no space available, space = %hu, item size = %hu\r\n&quot;, remaining, totalItemSize); return(-6); }else{ printf(&quot;[BucketPut], available space = %hu total item size = %hu\r\n&quot;, remaining, totalItemSize); } } }//else //If we have reached here, means all checks have passed and its safe to write the item to the bucket uint8_t status = BucketWriteData(slot, dataSize, data); if(status == false){//check if the passed type is supported printf(&quot;[BucketPut], Error, invalid data type\r\n&quot;); return(-4); } return(true); } /**************************************************************** * Function Name : BucketGetTimestampForFeed * Description : Gets the timestamp for the feed * Returns : false on error else true. * Params @timestamp: feeds timestamp ****************************************************************/ int8_t BucketGetTimestampForFeed(uint32_t *timestamp){ int8_t status = false; *timestamp = 0; if(cBucketBufTail &gt;= &amp;cbucketBuf[BUCKET_SIZE]){//if tail points to end of bucket or beyond cBucketBufTail = &amp;cbucketBuf[0];//wrap around to point start of the bucket and continue reading } //Check if tail is pointing to the virtual time slot if(*cBucketBufTail == unixTimeSlot){//If so, read the timestamp printf(&quot;[BucketGetTimestampForFeed], tail pointing to time slot, read it.\r\n&quot;); *cBucketBufTail++ = 0; //Skip the virtual timeslot and point to the timestamp for(int i = 0 ; i &lt; sizeof(uint32_t) ; i++){ if(cBucketBufTail &gt;= &amp;cbucketBuf[BUCKET_SIZE]){//if tail points to end of bucket or beyond cBucketBufTail = &amp;cbucketBuf[0];//wrap around to point start of the bucket and continue reading } //read the timestamp if(i == 0){ *timestamp |= (*cBucketBufTail &amp; 0xFF); }else if(i == 1){ *timestamp |= (*cBucketBufTail &amp; 0xFF) &lt;&lt; 8; }else if(i == 2){ *timestamp |= (*cBucketBufTail &amp; 0xFF) &lt;&lt; 16; }else if(i == 3){ *timestamp |= (*cBucketBufTail &amp; 0xFF) &lt;&lt; 24; } *cBucketBufTail++ = 0; }//for status = true; }else{//timeslot not found? //means the next byte is the slot index for the next feed which is not what we are looking for. //Lets look beyond, it must be there! - if not, then there's something seriously wrong with the code uint8_t *cBucketBufTailTmp = cBucketBufTail; //Iterate and look for the time slot while(cBucketBufTailTmp++ &lt; &amp;cbucketBuf[BUCKET_SIZE]){ if(cBucketBufTailTmp &gt;= &amp;cbucketBuf[BUCKET_SIZE]){//Check if tail reached or beyond the bucket's end. cBucketBufTailTmp = &amp;cbucketBuf[0];//Wrap around to point to the start of the bucket and continue to read. printf(&quot;[BucketGetTimestampForFeed], reached end of bucket, wrapping around...\r\n&quot;); } //Check if we are pointing to the virtual time slot, we should find it at some point. if(*cBucketBufTailTmp == unixTimeSlot){//yes!, found it. printf(&quot;[BucketGetTimestampForFeed], yes!, time slot has been found.\r\n&quot;); cBucketBufTailTmp++;//Skip the virtual timeslot and point to the start of the timestamp for(int i = 0 ; i &lt; sizeof(uint32_t) ; i++, cBucketBufTailTmp++){ if(cBucketBufTailTmp &gt;= &amp;cbucketBuf[BUCKET_SIZE]){//Check if tail reached or beyond the bucket's end. cBucketBufTailTmp = &amp;cbucketBuf[0];//Wrap around to point to the start of the bucket and continue to read. } //Read the time stamp if(i == 0){ *timestamp |= (*cBucketBufTailTmp &amp; 0xFF); }else if(i == 1){ *timestamp |= (*cBucketBufTailTmp &amp; 0xFF) &lt;&lt; 8; }else if(i == 2){ *timestamp |= (*cBucketBufTailTmp &amp; 0xFF) &lt;&lt; 16; }else if(i == 3){ *timestamp |= (*cBucketBufTailTmp &amp; 0xFF) &lt;&lt; 24; } }//for status = true; break; }//timeslot }//while }//else return(status); } /**************************************************************** * Function Name : BucketGetReadData * Description : Reads the key and value for that feed/slot. * Returns : false error, true on success. * Params @key: key to be populated(static). @value: value read from the bucket. ****************************************************************/ int8_t BucketGetReadData(char *key, char *value){ int8_t slotIdx; //Check if the tail is pointing to the end of the bucket or beyond, wrap around to start of bucket to continue reading if(cBucketBufTail &gt;= &amp;cbucketBuf[BUCKET_SIZE]) cBucketBufTail = &amp;cbucketBuf[0]; //Read the slot index for the feed slotIdx = *cBucketBufTail; //this is an int8_t type, if greater, will lead to undefined behavior. *cBucketBufTail++ = 0; if(slotIdx &gt; BUCKET_MAX_FEEDS){ printf(&quot;[BucketGetReadData], Error, Slot[%u] index is out of bounds\r\n&quot;, slotIdx); return(false); }else{ printf(&quot;[BucketGetReadData], Slot[%d] = 0x%x\r\n&quot;, slotIdx, (uint32_t)&amp;registeredFeed[slotIdx]-&gt;key); } //Copy the key for the corresponding slot strncpy(key, registeredFeed[slotIdx]-&gt;key, strlen(registeredFeed[slotIdx]-&gt;key)); //If the feed is of type UINT16_t if(registeredFeed[slotIdx]-&gt;type == UINT16){ uint16_t dataU16 = 0; for(int i = 0 ; i &lt; sizeof(uint16_t) ; i++){//Read 2 bytes if(cBucketBufTail &gt;= &amp;cbucketBuf[BUCKET_SIZE])//Check if we are pointing to the end of the bucket cBucketBufTail = &amp;cbucketBuf[0];//Wrap around to point to the start of the bucket to continue reading if(i == 0){ dataU16 |= (*cBucketBufTail &amp; 0xFF); }else if(i == 1){ dataU16 |= (*cBucketBufTail &amp; 0xFF) &lt;&lt; 8; } *cBucketBufTail++ = 0; }//for printf(&quot;[BucketGetReadData] dataU16 = %hu [0x%X]\r\n&quot;, dataU16, dataU16); sprintf(value, &quot;%hu&quot;, dataU16); //convert the u16 into string } else if(registeredFeed[slotIdx]-&gt;type == STRING){//If the feed is of type string (UNTESTED!) uint8_t i = 0; printf(&quot;[BucketGetReadData] dataStr = &quot;); while(*cBucketBufTail != '\0'){ if(cBucketBufTail &gt;= &amp;cbucketBuf[BUCKET_SIZE])//Check if we are pointing to the end of the bucket cBucketBufTail = &amp;cbucketBuf[0];//Wrap around to point to the start of the bucket to continue reading printf(&quot;0x%x &quot;, *cBucketBufTail); value[i++] = *cBucketBufTail; *cBucketBufTail++ = 0; }//copy data until end of string is reached //copy the null terminated character and point to start of the next address value[i] = *cBucketBufTail; *cBucketBufTail++ = 0; printf(&quot;\r\n&quot;); }else{ printf(&quot;[BucketGetReadData], Error, invalid read type Slot[%d]\r\n&quot;, slotIdx); return(false); } return(true); } /**************************************************************** * Function Name : BucketGet * Description :Gets the data * Returns : true on success else negative.. * Params @keyOut :contains the key @dataOut:contains the value @timestampOut: contains the timestamp ****************************************************************/ int8_t BucketGet( char *keyOut, char *dataOut, uint32_t *timestampOut) { //Check if theres anything in the bucket printf(&quot;&lt;==============================================================================&gt;\r\n&quot;); if(BucketCheckDataAvailable() == false){ printf(&quot;[BucketGet], AlLERT, Bucket is empty, no more data left to read.\r\n&quot;); //cBucketBufHead = &amp;cbucketBuf[0]; cBucketBufTail = &amp;cbucketBuf[0]; return(-1); } //Read the key-value for the corresponding feed/slot if(BucketGetReadData(keyOut, dataOut) == false){ printf(&quot;[BucketGet], Error, bucket read failed\r\n&quot;); return(-2); } //Read the timestamp corresponding to this feed if(BucketGetTimestampForFeed(timestampOut) == false){ printf(&quot;[BucketGet], Error, feed timestamp read failed\r\n&quot;); return(-3); } //All good, dump the key-value and associated timestamp printf(&quot;[Bucket Get] timestamp = %lu [0x%X]\r\n&quot;, *timestampOut, *timestampOut); printf(&quot;[Bucket Get] key = %s\r\n&quot;, keyOut); printf(&quot;[Bucket Get] value = %s\r\n&quot;, dataOut); printf(&quot;&lt;==============================================================================&gt;\r\n&quot;); return(true); } /**************************************************************** * Function Name : _RegisteredFeedFreeSlot * Description :Returns first free slot(index) found, returns -1 if no free slots available * Returns : slot on success else negative.. * Params None. ****************************************************************/ int8_t _RegisteredFeedFreeSlot(void) { int8_t slot; //Check for slots sequentially, return index of first empty one (null pointer) for(slot = 0; slot&lt;BUCKET_MAX_FEEDS; slot++) { if(registeredFeed[slot] == 0) return slot; } //All slots full return -1; } /**************************************************************** * Function Name : BucketNumbOfRegisteredFeeds * Description : Gets the num of registered feeds * Returns : No. of registered feeds * Params None. ****************************************************************/ uint8_t BucketNumbOfRegisteredFeeds(void) { uint8_t counts = 0; // Check for slots sequentially, return index of first empty one (null pointer) for(uint8_t slot = 0; slot&lt;BUCKET_MAX_FEEDS; slot++) { if(registeredFeed[slot] == 0) slot = BUCKET_MAX_FEEDS; else counts++; } // All slots full return counts; } /**************************************************************** * Function Name : _PrintFeedValue * Description :Prints feed data value via void pointer and corrects for type FLOAT AND DOUBLE DONT PRINT ON WASPMOTE BUT NO REASON TO BELIEVE THEY ARE WRONG * Returns : None. * Params @feed: Points to the feed to be printed ****************************************************************/ void _PrintFeedValue(cbucket_t *feed) { if (feed-&gt;type == UINT16) printf(&quot;%d&quot;,*(uint16_t*)feed-&gt;value); else if (feed-&gt;type == STRING) printf(&quot;%s&quot;,(char*)feed-&gt;value); else printf(&quot;%s&quot;,&quot;UNSUPPORTED TYPE&quot;); } /* *==================== * Debug Utils *==================== */ /**************************************************************** * Function Name : _DebugPrintRegistrationData * Description :Prints all registered feeds and their details * Returns : None. * Params None. ****************************************************************/ void DebugPrintRegistrationData(void) { int8_t slot; printf(&quot;********************** Current Bucket Registration Data **************************\r\n&quot;); printf(&quot;slot\taddress\tkey\ttype\tvalue\tunixtime\r\n&quot;); for(slot = 0; slot&lt;BUCKET_MAX_FEEDS; slot++) { printf(&quot;%d\t&quot;, slot); // Print index if (registeredFeed[slot] != NULL) { printf(&quot;0x%x\t&quot;,(uint32_t)&amp;registeredFeed[slot]-&gt;key); // Print structure address printf(&quot;%s\t&quot;,registeredFeed[slot]-&gt;key); // Print key printf(&quot;%s\t&quot;,cvaluetypes[registeredFeed[slot]-&gt;type]); // Print type _PrintFeedValue(registeredFeed[slot]); // Print value printf(&quot;\t%lu\r\n&quot;,registeredFeed[slot]-&gt;unixTime); // Print time } else printf(&quot;--\t--\tEMPTY\t--\t--\r\n&quot;); } } /**************************************************************** * Function Name : _DebugPrintBucket * Description :Prints all bucket memory, even if empty * Returns : None. * Params None. ****************************************************************/ void DebugPrintBucket(void) { uint16_t readIndex = 0; printf(&quot;\r\n********************* BUCKET START ********************\r\n&quot;); while(readIndex &lt; BUCKET_SIZE) { printf(&quot;0x%04X &quot;, readIndex); for (uint8_t column = 0; column &lt; 16; column++) { if(readIndex &lt; BUCKET_SIZE) printf(&quot;%02X &quot;,cbucketBuf[readIndex]); readIndex++; //delayMicroseconds(78); // Wait for a byte to send at 115200 baud //delay(0.1); } printf(&quot;\r\n&quot;); } printf(&quot;********************** BUCKET END *********************\r\n&quot;); } /**************************************************************** * Function Name : _DebugPrintBucket * Description : Prints bucket memory that has data * Returns : None. * Params None. ****************************************************************/ void DebugPrintBucketTailToHead(void) { uint8_t *cBucketBufHeadTemp = cBucketBufHead; uint8_t *cBucketBufTailTemp = cBucketBufTail; uint16_t index; printf(&quot;\n*************** BUCKET START FROM TAIL ****************\n&quot;); // Label and indent first line if ((cBucketBufTailTemp - &amp;cbucketBuf[0]) % 16 != 0) { printf(&quot; &quot;); for (index = (cBucketBufTailTemp - &amp;cbucketBuf[0]) % 16; index &gt; 0; index--) { printf(&quot; &quot;); } } // Print rest of data while(cBucketBufTailTemp != cBucketBufHeadTemp) { // Increment read address if(cBucketBufTailTemp &gt;= &amp;cbucketBuf[BUCKET_SIZE]) cBucketBufTailTemp = &amp;cbucketBuf[0]; // Handle wraparound index = cBucketBufTailTemp - &amp;cbucketBuf[0]; // Get current index in buffer if (index % 16 == 0) printf(&quot;\n0x%04X &quot;, cBucketBufTailTemp - &amp;cbucketBuf[0]); // New line every 0x00n0 printf(&quot;%02X &quot;, *cBucketBufTailTemp); cBucketBufTailTemp++; // Print data in buffer } printf(&quot;\n***************** BUCKET END AT HEAD ******************\n&quot;); } </code></pre> <p>Below is the test code.</p> <pre><code>//&lt;===============================Bucket Test================================&gt; char sensorValStr1[] = &quot;aaaaaaaaaaaaaa&quot;; char sensorKey1[] =&quot;sensorRef1&quot;; cbucket_t sensor1 = {sensorKey1, STRING, sensorValStr1, 1613343689}; uint16_t sensorValU16_2 = 0xAAAA; char sensorKey2[] =&quot;sensorRef2&quot;; cbucket_t sensor2 = {sensorKey2, UINT16, (uint8_t*)&amp;sensorValU16_2, 1613343689}; uint16_t sensorValU16_3 = 0xBBBB; char sensorKey3[] =&quot;sensorRef3&quot;; cbucket_t sensor3 ={sensorKey3, UINT16, (uint8_t*)&amp;sensorValU16_3, 1613343689}; uint16_t sensorValU16_4 = 0xCCCC; char sensorKey4[] =&quot;sensorRef4&quot;; cbucket_t sensor4 ={sensorKey4, UINT16, (uint8_t*)&amp;sensorValU16_4, 1613343691}; //&lt;===============================Bucket Test================================&gt; int main(void) { atmel_start_init(); /* Initialize the drivers */ //&lt;=================Bucket Test===================&gt; BucketRegisterFeed(&amp;sensor1); BucketRegisterFeed(&amp;sensor2); BucketRegisterFeed(&amp;sensor3); BucketRegisterFeed(&amp;sensor4); DebugPrintRegistrationData(); char keyOutT[32] = {0}; char valOutT[32] = {0}; uint32_t timeStmp = 0; for(int i = 0 ; i &lt; 3 ; i++){ //sensor2.unixTime +=1; BucketPut(&amp;sensor2); } DebugPrintBucket(); BucketGet(keyOutT, valOutT, &amp;timeStmp); DebugPrintBucket(); BucketGet(keyOutT, valOutT, &amp;timeStmp); DebugPrintBucket(); BucketGet(keyOutT, valOutT, &amp;timeStmp); DebugPrintBucket(); BucketGet(keyOutT, valOutT, &amp;timeStmp); for(int i = 0 ; i &lt; 8 ; i++){ BucketPut(&amp;sensor3); } DebugPrintBucket(); while(BucketGet(keyOutT, valOutT, &amp;timeStmp) == true); DebugPrintBucket(); for(int i = 0 ; i &lt; 8 ; i++){ BucketPut(&amp;sensor4); } DebugPrintBucket(); while(BucketGet(keyOutT, valOutT, &amp;timeStmp) == true); //&lt;===================Bucket Test====================&gt; while (true) { } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T07:36:43.230", "Id": "506109", "Score": "0", "body": "([oversee vs. overlook](https://grammarist.com/usage/oversee-vs-overlook) (and I'm kind of used to *room* for improvement))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T07:42:59.283", "Id": "506110", "Score": "1", "body": "This is quite a lot of code: Consider providing a \"road map\". I prefer *in the code*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T07:53:46.787", "Id": "506114", "Score": "0", "body": "@greybeard - that's a rare observation that can both be a comment to improve the question, or a review to improve the code! :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T10:43:08.190", "Id": "506337", "Score": "0", "body": "Welcome to Code Review! Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-27T07:05:19.677", "Id": "506425", "Score": "1", "body": "@TobySpeight, alright. I will post it as a new question including a few extra changes I have made." } ]
[ { "body": "<p>We're missing an include of <code>&lt;stdint.h&gt;</code> in the header, and <code>&lt;stdbool.h&gt;</code> in the implementation.</p>\n<p>Some parts of the code are hard to read. In particular, I think this comment should be wrapped at a more conventional line length:</p>\n<blockquote>\n<pre><code>/*\n * Description: This module is used to accumulate data when the network is down or unable to transmit data due to poor signal quality. It currently supports uint16_t and string data types. The bucket is designed to maximize the amount of data that can be stored in a given amount of memory for typical use. The feeds must be registered before they can be written to or read from the bucket.\n */\n</code></pre>\n</blockquote>\n<p>We should compile with more warnings enabled. With <code>gcc -std=c17 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wstrict-prototypes -Wconversion</code>, I get warnings about narrowing conversions:</p>\n<pre class=\"lang-none prettyprint-override\"><code>256360.c:151:23: warning: conversion from ‘int’ to ‘int8_t’ {aka ‘signed char’} may change value [-Wconversion]\n 151 | slotIdx = i; i = BUCKET_MAX_FEEDS;\n | ^\n256360.c:506:28: warning: conversion from ‘int’ to ‘uint16_t’ {aka ‘short unsigned int’} may change value [-Wconversion]\n 506 | dataU16 |= (*cBucketBufTail &amp; 0xFF);\n | ^\n256360.c:508:28: warning: conversion from ‘int’ to ‘uint16_t’ {aka ‘short unsigned int’} may change value [-Wconversion]\n 508 | dataU16 |= (*cBucketBufTail &amp; 0xFF) &lt;&lt; 8;\n | ^\n256360.c:682:22: warning: conversion from ‘long int’ to ‘uint16_t’ {aka ‘short unsigned int’} may change value [-Wconversion]\n 682 | for (index = (cBucketBufTailTemp - &amp;cbucketBuf[0]) % 16; index &gt; 0; index--) {\n | ^\n256360.c:689:17: warning: conversion from ‘long int’ to ‘uint16_t’ {aka ‘short unsigned int’} may change value [-Wconversion]\n 689 | index = cBucketBufTailTemp - &amp;cbucketBuf[0]; // Get current index in buffer\n | ^~~~~~~~~~~~~~~~~~\n</code></pre>\n<p>conversions between signed and unsigned:</p>\n<pre class=\"lang-none prettyprint-override\"><code>256360.c:292:25: warning: conversion to ‘uint8_t’ {aka ‘unsigned char’} from ‘int8_t’ {aka ‘signed char’} may change the sign of the result [-Wsign-conversion]\n 292 | *cBucketBufHead++ = slotIdx;\n | ^~~~~~~\n256360.c:489:15: warning: conversion to ‘int8_t’ {aka ‘signed char’} from ‘uint8_t’ {aka ‘unsigned char’} may change the sign of the result [-Wsign-conversion]\n 489 | slotIdx = *cBucketBufTail; //this is an int8_t type, if greater, will lead to undefined behavior.\n | ^\n256360.c:520:30: warning: conversion to ‘char’ from ‘uint8_t’ {aka ‘unsigned char’} may change the sign of the result [-Wsign-conversion]\n 520 | value[i++] = *cBucketBufTail;\n | ^\n256360.c:524:24: warning: conversion to ‘char’ from ‘uint8_t’ {aka ‘unsigned char’} may change the sign of the result [-Wsign-conversion]\n 524 | value[i] = *cBucketBufTail;\n | ^\n</code></pre>\n<p>comparisons between signed and unsigned:</p>\n<pre class=\"lang-none prettyprint-override\"><code>256360.c:207:27: warning: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’ [-Wsign-compare]\n 207 | for(int i = 0 ; i &lt; sizeof(uint32_t) ; i++, cBucketBufHeadTmp++){\n | ^\n256360.c:309:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’ [-Wsign-compare]\n 309 | for(int i = 0; i &lt; sizeof(data-&gt;unixTime); i++, cBucketBufHead++){\n | ^\n256360.c:420:27: warning: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’ [-Wsign-compare]\n 420 | for(int i = 0 ; i &lt; sizeof(uint32_t) ; i++){\n | ^\n256360.c:451:36: warning: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’ [-Wsign-compare]\n 451 | for(int i = 0 ; i &lt; sizeof(uint32_t) ; i++, cBucketBufTailTmp++){\n | ^\n256360.c:502:27: warning: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’ [-Wsign-compare]\n 502 | for(int i = 0 ; i &lt; sizeof(uint16_t) ; i++){//Read 2 bytes\n | ^\n</code></pre>\n<p>and use of the wrong conversion specifier:</p>\n<pre class=\"lang-none prettyprint-override\"><code>256360.c:360:57: warning: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘uint32_t’ {aka ‘unsigned int’} [-Wformat=]\n 360 | printf(&quot;[BucketPut] Last stored timestamp[%lu] = Current feed timestamp[%lu]\\r\\n&quot;, lastStoredTime, data-&gt;unixTime);\n | ~~^ ~~~~~~~~~~~~~~\n | | |\n | long unsigned int uint32_t {aka unsigned int}\n256360.c:360:87: warning: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 3 has type ‘uint32_t’ {aka ‘const unsigned int’} [-Wformat=]\n 360 | printf(&quot;[BucketPut] Last stored timestamp[%lu] = Current feed timestamp[%lu]\\r\\n&quot;, lastStoredTime, data-&gt;unixTime);\n | ~~^ ~~~~~~~~~~~~~~\n | | |\n | long unsigned int uint32_t {aka const unsigned int}\n256360.c:380:57: warning: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘uint32_t’ {aka ‘unsigned int’} [-Wformat=]\n 380 | printf(&quot;[BucketPut] Last stored timestamp[%lu] != Current feed timestamp[%lu]\\r\\n&quot;, lastStoredTime, data-&gt;unixTime);\n | ~~^ ~~~~~~~~~~~~~~\n | | |\n | long unsigned int uint32_t {aka unsigned int}\n\n256360.c:380:88: warning: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 3 has type ‘uint32_t’ {aka ‘const unsigned int’} [-Wformat=]\n 380 | printf(&quot;[BucketPut] Last stored timestamp[%lu] != Current feed timestamp[%lu]\\r\\n&quot;, lastStoredTime, data-&gt;unixTime);\n | ~~^ ~~~~~~~~~~~~~~\n | | |\n | long unsigned int uint32_t {aka const unsigned int}\n256360.c:560:41: warning: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘uint32_t’ {aka ‘unsigned int’} [-Wformat=]\n 560 | printf(&quot;[Bucket Get] timestamp = %lu [0x%X]\\r\\n&quot;, *timestampOut, *timestampOut);\n | ~~^ ~~~~~~~~~~~~~\n | | |\n | | uint32_t {aka unsigned int}\n | long unsigned int\n256360.c:641:25: warning: format ‘%lu’ expects argument of type ‘long unsigned int’, but argument 2 has type ‘uint32_t’ {aka ‘unsigned int’} [-Wformat=]\n 641 | printf(&quot;\\t%lu\\r\\n&quot;,registeredFeed[slot]-&gt;unixTime); // Print time\n | ~~^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | long unsigned int uint32_t {aka unsigned int}\n256360.c:690:45: warning: format ‘%X’ expects argument of type ‘unsigned int’, but argument 2 has type ‘long int’ [-Wformat=]\n 690 | if (index % 16 == 0) printf(&quot;\\n0x%04X &quot;, cBucketBufTailTemp - &amp;cbucketBuf[0]); // New line every 0x00n0\n | ~~~^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n | | |\n | unsigned int long int\n</code></pre>\n<p>These are all easy to fix, and just indicate sloppiness. (Remember that the format string for <code>uint32_t</code> is <code>PRIi32</code>, defined in <code>&lt;inttypes.h&gt;</code>).</p>\n<hr />\n<p>It's good to see tests included, though I did need to remove the call to undefined function <code>atmel_start_init()</code> to enable it to compile. That didn't seem to be required, so probably shouldn't have been in the test suite.</p>\n<p>Tests are better if they are self-checking, rather than relying on visual inspection of output - how often are you likely to look closesly enough to spot a regression?</p>\n<p>I would like to see some tests of the limit cases (such as creating <code>BUCKET_MAX_FEEDS</code> feeds, and then creating one more, and checking it's properly handled).</p>\n<p>I had to remove the unfinished final test (<code>while (true) {}</code>), as that was preventing the tests completing on my system.</p>\n<p>There's a couple of empty loops in the test, of this form:</p>\n<blockquote>\n<pre><code>while(BucketGet(keyOutT, valOutT, &amp;timeStmp) == true);\n</code></pre>\n</blockquote>\n<p>We should probably be actually checking the values, rather than just discarding, but as a general principle, I like to write the body of the loop (<code>;</code>) on its own line, where it's less easily missed than at the end of line like that.</p>\n<hr />\n<p>Do the debug strings need to be in release builds? I'd rewrite like this:</p>\n<pre><code>#ifndef NDEBUG\nconst char* cvaluetypes[] = {&quot;UINT16&quot;, &quot;STRING&quot;};\n#endif\n</code></pre>\n<p>Similarly for all the other debug code.</p>\n<hr />\n<p>There are a lot of functions in the implementation that are not in the public interface - they all ought to be declared with static linkage, to reduce namespace pollution.</p>\n<hr />\n<p>Instead of manipulating the loop index to finish a loop:</p>\n<blockquote>\n<pre><code>for(int i = 0 ; i &lt; BUCKET_MAX_FEEDS ; i++) {\n //found it?\n if(data == registeredFeed[i]) {\n //Get the slot index\n slotIdx = i; i = BUCKET_MAX_FEEDS;\n }\n}\n</code></pre>\n</blockquote>\n<p>The conventional, well-understood means is to use a <code>break</code> statement:</p>\n<pre><code>for(int i = 0 ; i &lt; BUCKET_MAX_FEEDS ; i++) {\n //found it?\n if(data == registeredFeed[i]) {\n //Get the slot index\n slotIdx = i;\n break;\n }\n}\n</code></pre>\n<p>In this case, it's probably best to simply <code>return</code> from the function instead.</p>\n<hr />\n<blockquote>\n<pre><code>int8_t BucketCheckDataAvailable(void){\n //Bucket is empty?\n if(cBucketBufTail == cBucketBufHead){\n return(false); \n }\n return(true);\n}\n</code></pre>\n</blockquote>\n<p>The patter <code>if (c) return true; else return false;</code> is over complex - just return the condition directly (and why are we returning a bool as <code>int8_t</code>?):</p>\n<pre><code>bool BucketCheckDataAvailable(void)\n{\n // Bucket is not empty?\n return cBucketBufTail != cBucketBufHead;\n}\n</code></pre>\n<p>Also, no need for redundant comparisons against <code>false</code>:</p>\n<blockquote>\n<pre><code>if(BucketCheckDataAvailable() == false){\n return(false);\n}\n</code></pre>\n</blockquote>\n<p>becomes simply</p>\n<pre><code>if (!BucketCheckDataAvailable()) {\n return false;\n}\n</code></pre>\n<hr />\n<p>What's going on here?</p>\n<blockquote>\n<pre><code>/****************************************************************\n * Function Name : BucketGetTimeStamp\n * Params : None.\n ****************************************************************/\nint8_t BucketPutGetTimeStamp(uint32_t *timestamp){\n</code></pre>\n</blockquote>\n<p>That's one reason not to repeat code information in comments!</p>\n<hr />\n<p>Here's a loop that has a lot of duplication:</p>\n<blockquote>\n<pre><code> for(int i = 0 ; i &lt; sizeof(uint32_t) ; i++, cBucketBufHeadTmp++){\n //Now if head points to end of bucket, read that value and wrap to start of bucket\n if(cBucketBufHeadTmp == &amp;cbucketBuf[BUCKET_SIZE]){//Handle if head needs to be wrapped around to read the timestamp\n cBucketBufHeadTmp = &amp;cbucketBuf[0]; //point to start of the bucket to continue reading the timestamp\n if(i == 0){\n *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF);\n }else if(i == 1){\n *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 8;\n }else if(i == 2){\n *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 16;\n }else if(i == 3){\n *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 24;\n }\n }else{//read value as is\n if(i == 0){\n *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF);\n }else if(i == 1){\n *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 8;\n }else if(i == 2){\n *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 16;\n }else if(i == 3){\n *timestamp |= (*cBucketBufHeadTmp &amp; 0xFF) &lt;&lt; 24;\n }\n }//else\n }//for\n</code></pre>\n</blockquote>\n<p>The common code can be moved outside the <code>if</code>/<code>else</code>, and the <code>if (i==</code> chain (which looks like a candidate for <code>switch</code>/<code>case</code>) can be eliminated using simple arithmetic:</p>\n<pre><code> for (int i = 0; i &lt; sizeof (uint32_t); ++i, ++cBucketBufHeadTmp) {\n if (cBucketBufHeadTmp == &amp;cbucketBuf[BUCKET_SIZE]) {\n // wrap to start of the bucket to continue reading the timestamp\n cBucketBufHeadTmp = &amp;cbucketBuf[0];\n }\n *timestamp |= *cBucketBufHeadTmp &lt;&lt; (8 * i);\n }\n</code></pre>\n<p>I also removed the pointless <code>&amp; 0xff</code> (since <code>*cBucketBufHeadTmp</code> is a <code>uint8_t</code>, it has no effect).</p>\n<p>Looking at this more broadly, the code to wrap around is repeated quite a lot, and would be better factored out into a function.</p>\n<hr />\n<p><code>BucketGetDataSize()</code> has this loop:</p>\n<blockquote>\n<pre><code> const uint8_t *bytePtr = (uint8_t*)data-&gt;value;\n for(int i = 0; i &lt; BUCKET_MAX_VALUE_SIZE; i++, bytePtr++) {\n if(*bytePtr == '\\0') {\n i = BUCKET_MAX_VALUE_SIZE;\n //Include the '\\0' to be written. This will be used to indicate the end of string while reading\n dataSizeOut++;\n continue;\n }\n dataSizeOut++;\n }\n</code></pre>\n</blockquote>\n<p><code>dataSizeOut++; continue;</code> is pointless, as that's exactly what would happen if we omitted those two statements. But the whole loop is pointless, since we should just use <code>strlen()</code> and have no need to write a loop here.</p>\n<p>Also, I'd prefer to see the testing of <code>data-&gt;type</code> using a <code>switch</code>, to make it easier to maintain (a decent compiler will warn if you miss a <code>case</code> when switching on an enum, for example).</p>\n<hr />\n<blockquote>\n<pre><code>/*\n * Function Name : BucketPut\n * Returns : true on success else negative..\n */\n</code></pre>\n</blockquote>\n<p>That's confusing, since negative values are all true in C.</p>\n<p>I don't see why this function needs to be so chatty (and why are errors printed to <code>stdout</code> instead of <code>stderr</code> as one would expect?).</p>\n<hr />\n<p>I only skim-read from here on, but saw many repeats of the same items already mentioned. It's probably time to address those comments, and return for another review when that's done.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T14:16:55.163", "Id": "506140", "Score": "0", "body": "I took too long to write my answer -- you addressed everything I did and did it well. Good job!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T03:10:26.183", "Id": "506190", "Score": "0", "body": "Any ideas on how best to factor the wraparounds into functions without complicating too much? as I use cBucketBufHeadTmp in BucketPutGetTimeStamp( ) and cBucketBufTailTmp in BucketGetTimestampForFeed( )." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T07:48:35.377", "Id": "506198", "Score": "1", "body": "Edward's answer has a suggestion for that - you probably just need to pass a pointer to the variable you're updating. Or perhaps a different interface where you write `cBucketBufHeadTmp = next_element(cBucketBufHeadTmp);` or similar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T07:53:55.540", "Id": "506329", "Score": "0", "body": "@VinayDivakar These reviews here are good, I'd encourage you to modify the source to fix the mentioned problems then post it again as a new question. There's various other details I'd like remark about, but you should get the code cleaned up a bit first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T08:52:01.877", "Id": "506332", "Score": "0", "body": "@Lundin, could you please clarify what you mean by \"code cleaned up a bit first\"? is it the way I have indented or the overall structure of the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T09:12:06.020", "Id": "506336", "Score": "0", "body": "@VinayDivakar I was mostly referring to the numerous warnings about \"sloppy typing\" - that is wildly mixing various integer types together in the same expression, or using `int` etc instead of the stdint.h types. Though now I just noticed that you have edited the question after reviews... that's a very bad thing, because there's no making sense of the answers after that. If you wish to post the code after changes it should be an answer, or a new question. Leave the original code as it was before reviews." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-28T19:48:03.403", "Id": "506527", "Score": "0", "body": "@Lundin, Ok, that has been sorted now. The question has been rolled back to its original by Toby. I will be posting my code updates soon as a new question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T03:12:03.297", "Id": "506541", "Score": "1", "body": "@Lundin and Toby, I have posted my updated code [here](https://codereview.stackexchange.com/questions/256556/embedded-iot-local-data-storage-updated)" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T08:40:11.017", "Id": "256367", "ParentId": "256360", "Score": "9" } }, { "body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Use the required <code>#include</code>s</h2>\n<p>The code uses <code>uint8_t</code> and <code>uint32_t</code> which means that it should <code>#include &lt;stdint.h&gt;</code>. It also uses <code>true</code> and <code>false</code> so it should <code>#include &lt;stdbool.h&gt;</code>. It was not difficult to infer, but it helps reviewers if the code is complete.</p>\n<h2>Don't make non-portable size assumptions</h2>\n<p>The code includes a number of dubious casts like this one:</p>\n<pre><code>printf(&quot;[BucketGetReadData], Slot[%d] = 0x%x\\r\\n&quot;, slotIdx, (uint32_t)&amp;registeredFeed[slotIdx]-&gt;key);\n</code></pre>\n<p>That's dubious because it casts a pointer to the <code>key</code> (which is declared as <code>const char*</code>) into a 32-bit quantity. That will absolutely fail on a 64-bit machine like the one I'm currently using. You might say that you only ever intend to run this code on a 32-bit machine, which is fine, but then make these assuptions <em>explicit</em> somewhere in the code such that the validity of the assumption is checked at compile time and an error is emitted if the assumption is not true. In this case, I'd suggest omitting the cast and instead using the <code>%p</code> format specifier which is an implementation-defined character sequence for a pointer. It is often exactly the kind of hexadecimal representation you seek.</p>\n<h2>Be careful with signed and unsigned</h2>\n<p>In a number of cases in the code we have something like this:</p>\n<pre><code>for(int i = 0 ; i &lt; sizeof(uint32_t) ; i++, cBucketBufHeadTmp++){\n</code></pre>\n<p>The problem is that the code compares an <code>int i</code> to a <code>size_t</code> from <code>sizeof</code>, but <code>size_t</code> is unsigned and <code>int</code> is signed. Instead, <code>i</code> as a <code>size_t</code> type.</p>\n<p>Also, the <code>_RegisteredFeedFreeSlot()</code> routine returns <code>-1</code> if there is no free slot. This implies that the maximum number of slots is 254 because 255 would be encoded exactly the same way as -1 in an <code>int8_t</code>. Worse, because you're using it as an array index into the <code>registeredFeed</code> array, any number greater than 127 will be interpreted as a negative number and absolutely wreak havoc as that would be <em>undefined behavior</em> in this context. (See <a href=\"https://stackoverflow.com/questions/3473675/are-negative-array-indexes-allowed-in-c\">this question</a> for more on negative numbers for array indices.) This means that the maximum legal value for <code>BUCKET_MAX_FEEDS</code> is 127. The code comment indicates that the maximum value is 64, but that should be enforced, as with the previous suggestion, and generate a compile-time error message if the value is not in range.</p>\n<h2>Declare non-interface functions and data <code>static</code></h2>\n<p>The interface is apparently completely defined in the <code>Bucket.h</code> file which is good. That's exactly the way it should be. However, all of the extra functions in <code>Bucket.c</code>, such as <code>_RegisteredFeedFreeSlot()</code> should be <code>static</code> so they cannot be used outside of that context. However, see the next suggestion.</p>\n<h2>Don't use leading underscores in names</h2>\n<p>Anything with a leading underscore is a <em>reserved name</em> in C (and in C++). See <a href=\"http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">this question</a> for details.</p>\n<h2>Simplify your code</h2>\n<p>This is a peculiar construction:</p>\n<pre><code>int8_t BucketCheckDataAvailable(void){\n //Bucket is empty?\n if(cBucketBufTail == cBucketBufHead){\n return(false); \n }\n return(true);\n}\n</code></pre>\n<p>In addition to the messy and inconsistent indentation, this is a convoluted way to do this. Instead, you could write this:</p>\n<pre><code>return cBucketBufTail != cBucketBufHead;\n</code></pre>\n<p>Note that <code>return</code> is a keyword, not a function, and it does not require and should not have parentheses.</p>\n<h2>Consider restructuring the code</h2>\n<p>Right now there is a lot of code within multiple functions that deal with the circular buffer wrapping around. I would isolate that to two helper functions like this:</p>\n<pre><code>bool CircularBufferWrite(size_t size, const void *data);\nbool CircularBufferRead(size_t size, void *data);\n</code></pre>\n<p>These two would be the only functions that actually write to or read from the circular buffer directly, freeing the other code to be much simpler. The <code>bool</code> return value indicates success or failure.</p>\n<h2>Use consistent formatting</h2>\n<p>The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently. The good part is that the function comments are generally pretty good. The bad is that some of the lines are almost 200 characters long. This impairs readability, even on large screens. I'd suggest a limit of 80 characters.</p>\n<h2>Consider isolating <code>printf</code> statements</h2>\n<p>Since this is on an embedded platform, it's unlikely that the <code>printf</code> statements are going to be particularly useful when the device is deployed. For that reason, I'd suggest providing a debug print that compiles to nothing unless it is a debug build. See <a href=\"https://en.cppreference.com/w/c/error/assert\" rel=\"noreferrer\">assert.h</a> for inspiration on how to do that.</p>\n<h2>Make the tests work for humans</h2>\n<p>Right now, an expert needs to examine the test output to determine if the results are as intended or not. Rather than making the human work for the machine, make the tests work for the human: have the program evaluate its own test results and print a simple pass/fail message for each. Unit testing is a widely used and very helpful technique when done well. You're already partway there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T14:31:26.307", "Id": "506142", "Score": "1", "body": "Oh yes, I meant to specifically mention `%p` but it slipped my mind. Glad you caught it. As always, we pick up a lot of the same things, but it still can be useful to see the points presented in different ways!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T14:11:53.977", "Id": "256375", "ParentId": "256360", "Score": "6" } } ]
{ "AcceptedAnswerId": "256367", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T04:18:51.307", "Id": "256360", "Score": "6", "Tags": [ "c", "database", "circular-list", "embedded" ], "Title": "Embedded IoT: local data storage when no network coverage" }
256360
<p>I've created program like in the title. Actually I know I could use regex to create pattern and then do some actions from it, but I think my code is clear enough (at least for me :P). There is a little thing to correct which is InputMismatch exception that isn't handled. What do you think about my code?</p> <pre><code>import java.util.Scanner; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class PasswordGenerator { //arrays with optional symbols private final char [] symbols = {'~', '`', '!', '@', '#' , '$', '%', '^', '&amp;', '*', '(', ')', '_', '-', '=', '+', '[', '{', ']', '}', '\\', '|', ';', ':', '\'', '&quot;', ',', '&lt;', '.', '&gt;', '/', '?'}; private final char [] lowerCaseChars = {'a' , 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q' , 'r', 's', 't', 'u', 'v', 'w', 'x', 'y' , 'z'}; private final char [] upperCaseChars = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; private final char [] numbers = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; //methods asking about external symbols private static boolean wantsSymbols(String kind, String example) { Scanner input = new Scanner(System.in); System.out.print(&quot;Do you want &quot; + kind + &quot; in password like &quot; + example + &quot;?(Y/N) &quot;); char in = input.next().charAt(0); return in == 'Y' || in == 'y'; } //return random value from specified array private static char randValue(char[] arr) { Random rand = new Random(); return arr[rand.nextInt(arr.length)]; } //combine the random values private static char[] combineRandomValues(int length, char[] array) { char [] returnedArray = new char[length]; for(int i = 0; i &lt; length; ++i) { returnedArray[i] = randValue(array); } return returnedArray; } //combine arrays private static char[] combineArrays(char[]arr1, char[]arr2, char[]arr3, char[]arr4) { StringBuilder sb = new StringBuilder(); if(arr1.length &gt; 0) sb.append(arr1); if(arr2.length &gt; 0) sb.append(arr2); if(arr3.length &gt; 0) sb.append(arr3); if(arr4.length &gt; 0) sb.append(arr4); return sb.toString().toCharArray(); } //from long array take random value private static char pickRandomValuesFromLongArray(char[] longArray) { int randomNumber = ThreadLocalRandom.current().nextInt(0, longArray.length); return longArray[randomNumber]; } private static String generatePassword(boolean inclSymbols, boolean inclLower, boolean inclUpper, boolean inclNumbers, int length) { //created object to use the arrays with values PasswordGenerator obj = new PasswordGenerator(); //using string builder to create password StringBuilder sb = new StringBuilder(); //arrays for random values char [] sArray = new char[0]; char [] lArray = new char[0]; char [] uArray = new char[0]; char [] nArray = new char[0]; //take first letters of bool char symbolsBool = String.valueOf(inclSymbols).toLowerCase().charAt(0); char lowerBool = String.valueOf(inclLower).toLowerCase().charAt(0); char upperBool = String.valueOf(inclUpper).toLowerCase().charAt(0); char numbersBool = String.valueOf(inclNumbers).toLowerCase().charAt(0); if(!inclLower &amp;&amp; !inclNumbers &amp;&amp; !inclUpper &amp;&amp; !inclSymbols) { System.out.println(&quot;You've to at least include one type of symbol&quot;); System.exit(0); } if(symbolsBool == 't') { sArray = combineRandomValues(length, obj.symbols); } if(lowerBool == 't') { lArray = combineRandomValues(length, obj.lowerCaseChars); } if(upperBool == 't') { uArray = combineRandomValues(length, obj.upperCaseChars); } if(numbersBool == 't') { nArray = combineRandomValues(length, obj.numbers); } //combine array 4 arrays from before char[] combinedArray = combineArrays(sArray, lArray, uArray, nArray); for(int i = 0; i &lt; length; ++i) sb.append(pickRandomValuesFromLongArray(combinedArray)); return sb.toString(); } public static void main(String[] args) { Scanner input = new Scanner(System.in); int lengthOfPass; //variables specifying the complexity of password boolean inclSymbols, inclLowercaseChars, inclUppercaseChars, inclNumbers; while (true) { System.out.print(&quot;Password length from 6 to 128: &quot;); lengthOfPass = input.nextInt(); if (lengthOfPass &gt;= 6 &amp;&amp; lengthOfPass &lt;= 128) { break; } else { System.out.println(&quot;Try again&quot;); } } System.out.println(); //questions about symbols inclSymbols = wantsSymbols(&quot;symbols&quot;, &quot;$,#,@ etc.&quot;); //lowercaseCharacters inclLowercaseChars = wantsSymbols(&quot;lowercase characters&quot;, &quot;a,b,c...&quot;); //uppercaseCharacters inclUppercaseChars = wantsSymbols(&quot;uppercase characters&quot;, &quot;A,B,C...&quot;); //numbers inclNumbers = wantsSymbols(&quot;numbers&quot;, &quot;0,1,2,3...&quot;); //initialize and output password String password = generatePassword(inclSymbols, inclLowercaseChars, inclUppercaseChars, inclNumbers, lengthOfPass); System.out.printf(&quot;\n%s&quot;, password); System.out.println(); } } </code></pre> <p>Also I know that I don't hold same structure (e.g. char [] ... and char[] ...)</p>
[]
[ { "body": "<p>Your program is not bad. So, please don't see my comments as criticism, but as hints for improvement.</p>\n<h2>Syntax</h2>\n<p>With</p>\n<pre><code> if(arr1.length &gt; 0)\n sb.append(arr1);\n</code></pre>\n<p>it's much too easy to mistakenly add another line as in</p>\n<pre><code> if(arr1.length &gt; 0)\n sb.append(arr1);\n haveAppended = true;\n</code></pre>\n<p>which seems to add the line to the conditional part, but in fact sets the variable unconditionally.</p>\n<p>I'd prefer to see</p>\n<pre><code> if(arr1.length &gt; 0) {\n sb.append(arr1);\n }\n</code></pre>\n<p>to avoid that risk.</p>\n<p>Otherwise: your indentation is fine, I'd only look at a more consistent insertion of space characters.</p>\n<p>Your comments like</p>\n<pre><code>//return random value from specified array\n</code></pre>\n<p>describe the methods that follow. That's a very good habit, to document what a method does. Only, there's a Java standard (&quot;Javadoc&quot;) way how to format such comments, supported by many tools from the Java world. That would look like</p>\n<pre><code>/**\n * Return random value from specified array.\n * @param arr character array to draw character from\n * @return a random character from the specified array\n */\n</code></pre>\n<p>and a template can be generated by any decent Java IDE from your method header (e.g. in Eclipse, type &quot;/**&quot; and ENTER above the method header, and you get it).</p>\n<h2>Simplifications</h2>\n<p>Instead of</p>\n<pre><code> char numbersBool = String.valueOf(inclNumbers).toLowerCase().charAt(0);\n [...]\n if(numbersBool == 't') {\n [...]\n }\n</code></pre>\n<p>you can omit the complicated translation to a single character, and simply write</p>\n<pre><code> if(inclNumbers) {\n [...]\n }\n</code></pre>\n<p>Your methods <code>randValue()</code> and <code>pickRandomValuesFromLongArray()</code> do the same thing: return a random character from a given character array. So, you can eliminate one of them. By the way, in the two methods, you use two different random generating classes, and I don't see a reason why.</p>\n<pre><code> PasswordGenerator obj = new PasswordGenerator();\n</code></pre>\n<p>You never use that <code>PasswordGenerator</code> instance. Your IDE should have flagged that as an unused variable. As long as all you methods are static, there's no point in creating an instance, so you can simply omit that line. In other words, your solution isn't object-oriented yet.</p>\n<h2>Logic</h2>\n<p>If the user requests a 100-character password with all components, you first create four 100-character arrays, filled with random characters of one of the four types, meaning you create 400 random characters, then you randomly draw 100 characters from the concatenated array, meaning that at least 300 of the random characters have been useless. Why not concatenate the original arrays like <code>lowerCaseChars</code> and do 100 random draws from that place?</p>\n<p>In generatePassword(), you have</p>\n<pre><code> System.exit(0);\n</code></pre>\n<p>What's good about that code part is that you check for insane conditions there and react instead of blindly running into some problems later. But you should do <code>System.exit(0);</code> if you are absolutely sure that your code will never run in a bigger context. That immediately stops any work in any other part of your bigger program just because in a single situation one password's parameters were not as expected.</p>\n<p>The recommended way to deal with such sanity checks is to throw an <code>IllegalArgumentException</code> in this case.</p>\n<p>You'd might to read up on exceptions before doing that transition, and be careful, there's a lot of sources talking plain nonsense about the proper usage of exceptions.</p>\n<h2>Structure</h2>\n<p>Your code isn't object oriented. How to get there?</p>\n<p>What is a <code>PasswordGenerator</code>? It's a thing that, once initialized and parameterized, can generate passwords, so it should have a method</p>\n<pre><code> public String generatePassword() {\n [...]\n return result;\n }\n</code></pre>\n<p>In my opinion, aspects like password length and character types look like parameters of a specific <code>PasswordGenerator</code> instance, so that one instance can be parameterized to provide passwords according to one site's rules, while a second one satisfies a different site. Then you can do:</p>\n<pre><code> PasswordGenerator siteAGenerator = \n new PasswordGenerator(true, true, false, true, 32);\n PasswordGenerator siteBGenerator = \n new PasswordGenerator(true, false, false, true, 16);\n [...]\n String siteAPassword = siteAGenerator.generatePassword();\n String siteBPassword = siteBGenerator.generatePassword();\n</code></pre>\n<p>Rules of thumb:</p>\n<ul>\n<li>Avoid the <code>static</code> keyword. That forces you to (at least syntactically) use the object-oriented approach.</li>\n<li>Decide what the objects are that you want to deal with. In this process, write down some descriptive sentences, and watch your usage of articles (works at least in English). &quot;A&quot; is a hint that the following noun might become a class, while &quot;the&quot; hints at an instance of such a class.</li>\n<li>Decide what the objects should &quot;do&quot;, if asked for by someone outside. That translates to public methods.</li>\n<li>Decide which information describes a given instance, and which information will be supplied with every single usage. In my example, I made the decision that a single generator will always produce passwords along the same pattern, so you supply that pattern information when constructing the instance (and the instance holds it in private fields), and when requesting new passwords, you don't need to repeat that.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T09:21:10.253", "Id": "506268", "Score": "0", "body": "Wow, I didn't expect such a excellent and detailed response! Thank you very much! To the point, I used two different generating options to make it even more random than it could be (to be honest I don't know if it does it). I did not know about Java comment standard so again Thank You. Actually I didn't want to use OOP, since I wanted all in one class. After reviewing my code I saw that creating an object was quite useless, so I'll change it later and remove one method with random class. Also thanks to you I realize that some parts could be significantly simplified. I appreciate your answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T09:38:22.067", "Id": "506269", "Score": "0", "body": "@ElPatronSalan You're welcome, that's what Code Review is meant to provide. Regarding OOP, I'd really encourage you to embrace that concept. From 40+ years of programming experience using lots of different paradigms, I can tell you, it's really worth it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-04T08:23:10.620", "Id": "506893", "Score": "0", "body": "Hi again, I've a silly question. I've created another program - now it's about (S(NTP)) and could I get your contact info or something for you to review it? I made it a bit object oriented ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-04T08:26:37.867", "Id": "506894", "Score": "0", "body": "Also I fixed a little password generator" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-04T09:37:42.460", "Id": "506898", "Score": "0", "body": "@ElPatronSalan I'm not into free private coaching, but always feel free to ask new questions on this site, where everybody can learn from questions and answers." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T14:22:01.633", "Id": "256376", "ParentId": "256363", "Score": "3" } } ]
{ "AcceptedAnswerId": "256376", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T06:24:19.580", "Id": "256363", "Score": "1", "Tags": [ "java", "generator" ], "Title": "Strong password generator with symbols that user definies" }
256363
<p>I'm a beginner programmer and i'm looking for interesting projects to improve my low skills. I tried one day to improve my skills by trying to create a small game in which a user owns a cat, and has to feed it and clean it. My main aim of the game(which yet has many illogical things like the never decreasing happiness and cleanness level) was to try and keep my code as clean and presentable as possible. The game is made in 4 different files, and I will paste them all below. I will be happy if anyone could give me help on understanding where should I improve.</p> <p>Lets go into the code:</p> <p>main.cpp</p> <pre><code>#include &quot;Cat.h&quot; #include &quot;pet game.h&quot; #include &lt;iostream&gt; using namespace std; int main() { //Create the user's profile //User(); //Welcome messages cout &lt;&lt; &quot;Welcome to Unga bonga! Here you buy pets and raise them as your kids, and try to level up, in order to finish the game!&quot; &lt;&lt; endl; showHelp(); //Command execution do { commandIdentify(); } while (true); } Cat cat; //User user; void showHelp() { cout &lt;&lt; &quot;The commands in this game are:&quot; &lt;&lt; endl &lt;&lt; &quot;1. to feed your cat, type f&quot; &lt;&lt; endl &lt;&lt; &quot;2. to clean your cat, type c&quot; &lt;&lt; endl &lt;&lt; &quot;3. to check your cat's happiness, type h&quot; &lt;&lt; endl &lt;&lt; &quot;4. to check your cash balance, type m&quot; &lt;&lt; endl &lt;&lt; &quot;5. to check your level status, type l&quot; &lt;&lt; endl &lt;&lt; &quot;6. to display this help message, type ?&quot; &lt;&lt; endl &lt;&lt; &quot;7. to exit, type e&quot; &lt;&lt; endl &lt;&lt; &quot;8. Finally, to play this game, enjoy!&quot; &lt;&lt; endl; } void commandIdentify() { //take input cin &gt;&gt; command; //identify and execute switch (command) { case 'f': feedCat(); break; case 'c': cleanCat(); break; case 'h': checkHappiness(); break; case '?': showHelp(); break; case 'e': exit(); default: cout &lt;&lt; &quot;That's not a command -yet (probably)&quot; &lt;&lt; endl; } } void feedCat() { cout &lt;&lt; &quot;Time for food!!!&quot; &lt;&lt; endl; cat.feed(); } void cleanCat() { cout &lt;&lt; &quot;Let's take a bath!!!&quot; &lt;&lt; endl; cat.clean(); } void checkHappiness(){ cat.checkHappiness(); } int exit() { exit(0); return 0; } </code></pre> <p>pet game.h:</p> <pre><code> #ifndef PET_GAME_H_ #define PET_GAME_H_ #include &lt;iostream&gt; #include &quot;Cat.h&quot; //#include &quot;User.h&quot; using namespace std; //Global variables char command; int exit(); //functions void commandIdentify(); void buyNextCat(); void showHelp(); void tutorial(); void feedCat(); void cleanCat(); void checkHappiness(); //functions defined for a future use but they cause problems right now void checkMoney(); void checkLevel(); #endif /* PET_GAME_H_ */ </code></pre> <p>Cat.cpp:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &quot;Cat.h&quot; using namespace std; Cat::Cat(){ happiness = 1; cleanness = 1; } void Cat::feed(){ cout &lt;&lt; &quot;Yummy!!&quot; &lt;&lt; endl; Cat::happiness = Cat::happiness + 0.2; } void Cat::clean(){ cout &lt;&lt; &quot;So soupy!!&quot; &lt;&lt; endl; Cat::cleanness = Cat::cleanness + 0.2; } </code></pre> <p>Cat.h:</p> <pre><code>#ifndef CAT_H_ #define CAT_H_ #include &lt;iostream&gt; using namespace std; class Cat { private: int happiness; bool happy = happiness &gt;= 0.6; int cleanness; bool isClean = cleanness &gt;= 0.6; public: Cat(); void feed(); void clean(); void checkHappiness() { cout &lt;&lt; &quot;Your cat's happiness is &quot; &lt;&lt; happiness*100 &lt;&lt; &quot;%&quot; &lt;&lt; endl; } }; #endif /* CAT_H_ */ </code></pre> <p>it will be great if you could tell me how to improve code</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T00:51:26.340", "Id": "506186", "Score": "0", "body": "For a C++ beginner, this is an *excellent* attempt." } ]
[ { "body": "<ul>\n<li>Avoid <code>using namespace std;</code> - it can cause problems with name collisions. It's best to qualify names where necessary, e.g.: <code>std::cout</code></li>\n</ul>\n<hr />\n<ul>\n<li><code>std::endl</code> adds a newline, but it also flushes the output stream. Unless we actually need the flushing behavior, it's best to simply output a newline <code>&quot;\\n&quot;</code> where necessary (e.g. <code>&lt;&lt; &quot;2. to clean your cat, type c\\n&quot;</code>).</li>\n</ul>\n<hr />\n<ul>\n<li><code>char command;</code> does not need to be a global variable. It's only accessed in a single function, so it can be a local variable.</li>\n</ul>\n<hr />\n<ul>\n<li>The <code>exit()</code> function is not necessary. We can call <a href=\"https://en.cppreference.com/w/cpp/utility/program/exit\" rel=\"nofollow noreferrer\"><code>std::exit(0)</code></a> directly. Note that we should include <code>&lt;cstdlib&gt;</code> for this function, and use the exit codes <code>EXIT_SUCCESS</code> or <code>EXIT_FAILURE</code> instead of a number like <code>0</code>.</li>\n</ul>\n<hr />\n<ul>\n<li><p>Functions that are used only in a single file do not need to be declared in header files. If necessary, we can declare them above the point of use, or move the function definition higher up the file. e.g.:</p>\n<pre><code>void commandIdentify(); // forward declaration\n\nint main() { ... }\n\nvoid commandIdentify() { ... } // function definition\n</code></pre>\n<p>or</p>\n<pre><code>void commandIdentify() { ... } // function definition\n\nint main() { ... }\n</code></pre>\n</li>\n</ul>\n<hr />\n<ul>\n<li><p>In the <code>Cat</code> class, the <code>happy</code> and <code>isClean</code> members are not quite correct. They will only be set on initialization. If the cat's happiness or cleanness changes at a later time, they will not be updated. In addition, initialization of variables occurs <em>before</em> the body of the constructor, in the order that they are declared in the class.</p>\n<p>For the initial values of <code>happy</code> and <code>isClean</code> to be set correctly, we would have to use a member initializer list:</p>\n<pre><code>Cat::Cat():\n happiness(1),\n /* `happy` is initialized here */\n cleanness(1),\n /* `isClean` is initialized here */\n{\n // if we set happiness now, `happy` won't get updated!\n happiness = 0.2,\n}\n</code></pre>\n<p>In any case, since we want the values to always be updated, we should make <code>happy</code> and <code>isClean</code> member functions instead:</p>\n<pre><code>bool isClean() const { return cleanness &gt;= 0.6; }\n</code></pre>\n<p>That way, we don't need to update any extra state.</p>\n</li>\n</ul>\n<hr />\n<ul>\n<li><p>Member functions that don't modify the state of the class (i.e. any member veriables) should be declared <code>const</code>, e.g.:</p>\n<pre><code>void checkHappiness() const { ... }\n</code></pre>\n</li>\n</ul>\n<hr />\n<ul>\n<li><p><code>Cat cat;</code> This doesn't need to be a global variable. We can make the <code>cat</code> a local variable in <code>main()</code> and pass a reference to it to the functions that need to use it:</p>\n<pre><code>int main() {\n Cat cat;\n ...\n commandIdentify(cat);\n}\n\nvoid commandIdentify(Cat&amp; cat) {\n ...\n feedCat(cat);\n}\n\nvoid feedCat(Cat&amp; cat) {\n ...\n cat.feed();\n}\n</code></pre>\n<p>This may seem like more work, but it's quite important, as means that our <code>commandIdentify</code> function (and the functions for each command) will now work with <em>any</em> cat, not just the one cat that we declared in <code>main()</code>.</p>\n<p>So now we can feed <em>many</em> cats!</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T12:31:08.180", "Id": "256406", "ParentId": "256364", "Score": "1" } }, { "body": "<p>Welcome to C++! You're off at a good start. Your code is very good for a beginner and it was very easy for me to read.</p>\n<hr />\n<ul>\n<li><h2><code>using namespace std</code></h2>\n</li>\n</ul>\n<p>There's a <em>mistake</em> that I've seen most beginners make, (I'm guilty of it too) which is <code>using namespace std</code>.</p>\n<p>There has been a long discussion about this on the <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow</a> and I suggest you read it. In fact I've said this before multiple times in my reviews. The link I provided has excellent answers depicting the harmful effects of having this.</p>\n<p><a href=\"https://en.cppreference.com/w/cpp/language/namespace\" rel=\"nofollow noreferrer\">Namespaces</a> in C++ are a way preventing name collisions in C++. to The <code>std</code> namespaces has <strong>tons</strong> of identifiers, <strong>tons</strong>. By doing <code>using namespace std</code>, you erase the important line that seperates <strong>your</strong> stuff and the <strong>std</strong> stuff.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>namespace Apple {\n int a = 5;\n}\n\nnamespace Orange {\n int a = 6;\n}\n\nint main() {\n std::cout &lt;&lt; Orange::a &lt;&lt; std::endl; // 'a' in namespace Orange\n}\n</code></pre>\n<pre class=\"lang-cpp prettyprint-override\"><code>namespace Apple {\n int a = 5;\n}\n\nnamespace Orange {\n int a = 6;\n}\n\nint main() {\n using namespace Orange;\n using namespace Apple;\n std::cout &lt;&lt; a &lt;&lt; std::endl; // ?!?!?!?!?\n}\n</code></pre>\n<p>in addition to this, when i see <code>std::cout &lt;&lt; a</code> I want to know which <code>a</code> is being referenced here, any external library? A local variable? A global variable?</p>\n<ul>\n<li><strong>Moral of the story</strong>: Try to avoid doing this in your projects. Along the same lines, <strong>never</strong> have a <code>using namespace</code> in a header file. This header file gets included in other files and if you make it a habit you'll have no idea from where you're getting sudden name collisions.</li>\n</ul>\n<hr />\n<ul>\n<li><h2>Initializing members</h2>\n</li>\n</ul>\n<pre><code>Cat::Cat(){\n happiness = 1;\n cleanness = 1;\n}\n</code></pre>\n<p>Instead of having this constructor, you can directly do</p>\n<pre><code>class Cat {\nprivate:\n int happiness = 1;\n int cleanness = 1;\n Cat() = default;\n // ...\n</code></pre>\n<p>And btw, the word you're want is <em>cleanliness</em> :)</p>\n<p>Since you are a beginner, I recommend watching <a href=\"https://www.youtube.com/watch?v=FXhALMsHwEY\" rel=\"nofollow noreferrer\">this</a> video on C++ constructors to get some extra knowledge</p>\n<hr />\n<ul>\n<li><h2>Global variables</h2>\n</li>\n</ul>\n<p>You have some global variables in your program, and I have a problem with that. Put in other words, you have some variables <em>with no scope</em> in your program. That's exactly the problem.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>//Global variables\nchar command;\n</code></pre>\n<p>I don't want to repeat myself here, but -&gt; <em>you will realize why its bad as the size of your codebase grows</em>. The variable <code>command</code> is only needed by a few functions. There is no reason to have it leak into other scopes right? Given that <code>command</code> isn't a very distinctive name, if you by chance have to take in another input in another function, what do you do? <code>command_2</code>? These are some of the problems cause by globals. There are cases where you NEED them but this is surely not one of them.</p>\n<p>Instead of creating a global variable, give it a scope and use function parameters to pass it around. Trust me when I say its much better to have that!</p>\n<hr />\n<h2>Other suggestions</h2>\n<ul>\n<li>unnecessary <code>Cat::</code></li>\n</ul>\n<pre><code>void Cat::feed(){\n cout &lt;&lt; &quot;Yummy!!&quot; &lt;&lt; endl;\n Cat::happiness = Cat::happiness + 0.2;\n}\n\nvoid Cat::clean(){\n cout &lt;&lt; &quot;So soupy!!&quot; &lt;&lt; endl;\n Cat::cleanness = Cat::cleanness + 0.2;\n}\n</code></pre>\n<p>Drop the <code>Cat::</code> here, you're defining a member function you don't need it.</p>\n<ul>\n<li><code>#pragma once</code></li>\n</ul>\n<pre><code>// Header file\n#ifndef foo\n#define foo \n// your code ...\n#endif\n</code></pre>\n<p>You probably know what these are, (you've used them in your program). There is a nicer (although less portable) way of achieving the same which is to use <code>#pragma once</code></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#pragma once\n// your code ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T01:39:22.400", "Id": "506257", "Score": "0", "body": "`#pragma once` is only “nicer” when it works; when it fails, it’s an unholy nightmare to diagnose or fix… which is why it’s never been standardized. It’s bad advice to tell new programmers to use it. [Even the core guidelines recommend against it](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#sf8-use-include-guards-for-all-h-files)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T06:18:25.043", "Id": "506327", "Score": "0", "body": "@indi Oh, I've never heard anything about that. Why would it fail?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T19:17:46.410", "Id": "506392", "Score": "0", "body": "There are dozens of ways; far more than could be explained here. But two common classes of errors are: 1) the “same” file is accessed from different filesystems, which might happen if libraries are on network drives; and 2) a file is copied/modified by your build system so it’s no longer the “same” file, which might happen if a file is preprocessed somehow, or even just copied from the source dir to the build dir. These errors are functionally impossible to predict, may be silent, and are non-deterministic (may happen on Tuesday, but not Thursday). These are the *worst* kinds of errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T19:17:50.730", "Id": "506393", "Score": "0", "body": "By contrast, the only way include guards can “break” is if you use the same token in two different headers… which is such a trivial and obvious problem that someone that learned C++ 10 minutes ago can spot it (and fix it!), or it can even be detected by a simple tool. And, of course, it can be mostly avoided in the first place by following simple guidelines. This is the *best* kind of error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T19:18:20.790", "Id": "506394", "Score": "0", "body": "Granted, it’s *very* rare that `#pragma once` will fail… but when it does, you’re just totally boned; like, there’s just no fixing it, you basically have to give up and rethink your entire project structure from scratch. But it’s still better than *nothing*, so if someone’s using *nothing*, then suggesting `#pragma once` is… okay-ish (still better to tell them to use include guards, though). But if someone’s already using *the correct thing*—include guards—telling them to switch to `#pragma once` is irresponsible, terrible advice." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T12:40:26.577", "Id": "256407", "ParentId": "256364", "Score": "2" } } ]
{ "AcceptedAnswerId": "256407", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T06:26:19.107", "Id": "256364", "Score": "2", "Tags": [ "c++" ], "Title": "Simple pet caring game - console" }
256364
<p>I am writting an API backend application using .NET Core and Visual Studio.</p> <p>Here is the solution structure:</p> <p><code>[ProjectName]</code> - Solution</p> <ul> <li><code>[ProjectName].API</code> - API project containing Controllers, DTOs, AutoMapper etc.</li> <li><code>[ProjectName].Core</code> - Class Library project containing services and business logic</li> <li><code>[ProjectName].Data</code> - Class Library project containing DbContext and Migrations</li> <li><code>[ProjectName].Domain</code> - Class Library project containing database entities</li> <li><code>[ProjectName].Interfaces</code> - Class Library project containing interfaces</li> <li><code>[ProjectName].Repositories</code> - Class Library project containing repositories</li> <li><code>[ProjectName].Tests</code> - Console Application containing unit tests</li> </ul> <p>Here is the code structure:</p> <p>In <code>.Repositories</code> project there is <code>BaseRepository</code>:</p> <pre><code>public class BaseRepository&lt;T, TPrimaryKey&gt; : IBaseRepository&lt;T, TPrimaryKey&gt; where T : class where TPrimaryKey : struct { private readonly DatabaseContext _dbContext; public BaseRepository(DatabaseContext dbContext) { _dbContext = dbContext; } public async Task&lt;IEnumerable&lt;T&gt;&gt; GetAll() { return await _dbContext.Set&lt;T&gt;().ToListAsync(); } public IQueryable&lt;T&gt; GetQueryable() { return _dbContext.Set&lt;T&gt;(); } public async Task&lt;T&gt; Find(TPrimaryKey id) { return await _dbContext.Set&lt;T&gt;().FindAsync(id); } public async Task&lt;T&gt; Add(T entity, bool saveChanges = true) { await _dbContext.Set&lt;T&gt;().AddAsync(entity); if (saveChanges) await _dbContext.SaveChangesAsync(); return await Task.FromResult(entity); } public async Task Edit(T entity, bool saveChanges = true) { _dbContext.Entry(entity).State = EntityState.Modified; if (saveChanges) await _dbContext.SaveChangesAsync(); } public async Task Delete(T entity, bool saveChanges = true) { if (entity == null) throw new NullReferenceException(); _dbContext.Set&lt;T&gt;().Remove(entity); if (saveChanges) await _dbContext.SaveChangesAsync(); } public async Task&lt;IEnumerable&lt;T&gt;&gt; BulkInsert(IEnumerable&lt;T&gt; entities, bool saveChanges = true) { foreach (T entity in entities) { await _dbContext.Set&lt;T&gt;().AddAsync(entity); } if (saveChanges) await _dbContext.SaveChangesAsync(); return await Task.FromResult(entities); } public async Task BulkUpdate(IEnumerable&lt;T&gt; entities, bool saveChanges = true) { foreach (T entity in entities) { _dbContext.Entry(entity).State = EntityState.Modified; } if (saveChanges) await _dbContext.SaveChangesAsync(); } public async Task Save() { await _dbContext.SaveChangesAsync(); } } </code></pre> <p>In <code>.Interfaces</code> project there is:</p> <p><code>IBaseRepository</code>:</p> <pre><code>public interface IBaseRepository&lt;T, E&gt; where T : class where E : struct { Task&lt;IEnumerable&lt;T&gt;&gt; GetAll(); IQueryable&lt;T&gt; GetQueryable(); Task&lt;T&gt; Find(E id); Task&lt;T&gt; Add(T entity, bool saveChanges = true); Task Edit(T entity, bool saveChanges = true); Task Delete(T entity, bool saveChanges = true); Task&lt;IEnumerable&lt;T&gt;&gt; BulkInsert(IEnumerable&lt;T&gt; entities, bool saveC Task BulkUpdate(IEnumerable&lt;T&gt; entities, bool saveChanges = true); Task Save(); } </code></pre> <p><code>IServiceBase</code>:</p> <pre><code>public interface IServiceBase&lt;TEntity, TPrimaryKey&gt; { Task&lt;TEntity&gt; GetById(TPrimaryKey id); Task&lt;TEntity&gt; GetSingle(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition); Task&lt;IEnumerable&lt;TEntity&gt;&gt; GetAll(); IEnumerable&lt;TEntity&gt; GetAll(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition); IQueryable&lt;TEntity&gt; GetAllQueryable(); IQueryable&lt;TEntity&gt; Query(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition); Task&lt;TEntity&gt; Create(TEntity entity); Task Delete(TEntity entity); Task Update(TEntity entity); Task&lt;long&gt; Count(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition); Task&lt;long&gt; Count(); Task&lt;IEnumerable&lt;TEntity&gt;&gt; BulkInsert(IEnumerable&lt;TEntity&gt; entities); Task BulkUpdate(IEnumerable&lt;TEntity&gt; entities); } </code></pre> <p>and all interfaces of concrete entity services:</p> <p>for example <code>IAddressServices</code>:</p> <pre><code>public interface IAddressService : IServiceBase&lt;Address, Guid&gt; { Task&lt;Address&gt; VerifyAddress(Address address); } </code></pre> <p>In <code>.Core</code> project there is:</p> <p><code>ServiceBase</code>:</p> <pre><code>public abstract class ServiceBase&lt;TEntity, TRepository, TPrimaryKey&gt; : IServiceBase&lt;TEntity, TPrimaryKey&gt; where TEntity : class where TPrimaryKey : struct where TRepository : IBaseRepository&lt;TEntity, TPrimaryKey&gt; { public TRepository Repository; public ServiceBase(IBaseRepository&lt;TEntity, TPrimaryKey&gt; rep) { Repository = (TRepository)rep; } public virtual async Task&lt;TEntity&gt; GetById(TPrimaryKey id) { return await Repository.Find(id); } public async Task&lt;TEntity&gt; GetSingle(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition) { return await Repository.GetQueryable().Where(whereCondition).FirstOrDefaultAsync(); } public async Task&lt;IEnumerable&lt;TEntity&gt;&gt; GetAll() { return await Repository.GetAll(); } public IEnumerable&lt;TEntity&gt; GetAll(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition) { return Repository.GetQueryable().Where(whereCondition); } public IQueryable&lt;TEntity&gt; GetAllQueryable() { return Repository.GetQueryable(); } public IQueryable&lt;TEntity&gt; Query(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition) { return Repository.GetQueryable().Where(whereCondition); } public virtual async Task&lt;TEntity&gt; Create(TEntity entity) { return await Repository.Add(entity); } public virtual async Task Delete(TEntity entity) { await Repository.Delete(entity); } public virtual async Task Update(TEntity entity) { await Repository.Edit(entity); } public async Task&lt;long&gt; Count(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition) { return await Repository.GetQueryable().Where(whereCondition).CountAsync(); } public async Task&lt;long&gt; Count() { return await Repository.GetQueryable().CountAsync(); } public async Task&lt;IEnumerable&lt;TEntity&gt;&gt; BulkInsert(IEnumerable&lt;TEntity&gt; entities) { return await Repository.BulkInsert(entities); } public async Task BulkUpdate(IEnumerable&lt;TEntity&gt; entities) { await Repository.BulkUpdate(entities); } } </code></pre> <p>and concrete implementations of services:</p> <p>for example <code>AddressService</code>:</p> <pre><code>public class AddressService : ServiceBase&lt;Address, IBaseRepository&lt;Address, Guid&gt;, Guid&gt;, IAddressService { public AddressService(IBaseRepository&lt;Address, Guid&gt; rep) : base(rep) { } public async Task&lt;Address&gt; VerifyAddress(Address address) { //logic } } </code></pre> <p>In <code>.API</code> project there are controllers:</p> <p>for example <code>ProductController</code>:</p> <pre><code> public class ProductController : ControllerBase { private readonly IProductService _productService; private readonly IAddressService _addressService; private readonly ILogger _logger; private readonly IMapper _mapper; public ProductController (IProductService productService, IAddressService addressService, ILogger&lt;ProductController&gt; logger, IMapper mapper) { _packageService = packageService; _addressService = addressService; _logger = logger; _mapper = mapper; } [HttpGet] public async Task&lt;IActionResult&gt; GetAllProductsWithAddresses() { try { var products = await _productService.GetAllQueryable().Include(x =&gt; x.Address).ToListAsync(); return Ok(_mapper.Map&lt;List&lt;ProductResponse&gt;&gt;(products)); } catch (Exception e) { _logger.LogError($&quot;An unexpected error occured: ${e}&quot;); return StatusCode(StatusCodes.Status500InternalServerError); } } } </code></pre> <p>I have read a lot that Repository pattern is sometimes bad and it should be used only if unit tests are needed. In my case unit tests are needed, so I want to make sure I am using it in correct manner and there won't be performance bottlenecks in the future.</p> <ol> <li>Is using <code>GetQueryable</code> in <code>ProductController</code> correct by Repository pattern design? If not, is it only violation of Repository pattern or there are some other performance issues?</li> <li>If I wouldn't need unit tests, is it better just to remove Repository layer and use EF directly in services or controllers?</li> <li>Since I needed to update multiple records in the database, using <code>BulkUpdate</code> from <code>BaseRepository</code> is not perfect in terms of performance, since for updating 1000 rows, 1000 separate queries will be executed in the database. The ideal would be to execute 1 raw SQL query using <code>dbContext.Database.ExecuteSqlCommand</code>. How and where could I integrate execution of raw SQL queries in project setup like this to make sure clean architecture is satisfied?</li> <li>If answer to 3rd question is you can't integrate raw SQL queries in this architecture to make it clean, should I look at 3rd party libraries that enables those features such as Entity Framework plus (<a href="https://entityframework-plus.net/?z=ef-extended" rel="nofollow noreferrer">https://entityframework-plus.net/?z=ef-extended</a>). I am not so familiar with this library but as I found out they are executing 1 raw SQL query when updating multiple number of records. Example of integration would be <code>await GetAllQueryable().Where(p =&gt; p.Name.Contains(&quot;test&quot;)).UpdateAsync(p =&gt; new Product() { Quantity = 10 });</code>. Is it better to use 3rd party libraries such as EF Plus instead of raw SQL queries?</li> </ol> <p>Any help is appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T13:40:33.287", "Id": "506135", "Score": "1", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T13:59:28.043", "Id": "506137", "Score": "0", "body": "@TobySpeight Thanks for the advice! I edited the question a little bit, hopefully title is more meaningful now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T14:05:01.770", "Id": "506138", "Score": "2", "body": "Not really - it's still talking about the concerns with the code, rather than about what _purpose_ it serves. I would edit for you, but I can't work out from the description what the code is supposed to do. If you can write what **real-world problem** the program solves, then that would be an appropriate title. Did you follow the link I gave? Some more guidance is in [How to Ask](/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T14:08:50.887", "Id": "506139", "Score": "0", "body": "The program does not solve any real-world problem, lets say it like that. The code I provided is code-infrastructure that I am using in my project, by reading on internet some people say IQueryable is not meant to be used outside of the Repository pattern (BaseRepository class in my case). Not sure how the question should look like, but I have several questions down. Firstly I asked this question on standard StackOverflow, but they suggested to me to post it on codereview forum. @TobySpeight" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T14:28:37.510", "Id": "506141", "Score": "0", "body": "If it's infrastructure that enables some program to build on it to provide some real-world benefit, then that's fine - we have a lot of questions like that. As I don't do .Net, I'm not really qualified in this, but if it's a library or base class for something else, I would recommend using a title of the form \"Library to provide (services) for (type) applications\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T17:11:02.630", "Id": "506153", "Score": "0", "body": "IMHO I don't see the point of a Repository when all it does is provide a wrapper around DbContext which is itself already a repository. It just adds pointless overhead. Keep all your DB logic in one layer and expose data objects to other layers via a service class. Also consider something like https://github.com/jbogard/MediatR and/or CQRS -- https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs . Keep your controllers light." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T09:46:00.400", "Id": "506212", "Score": "2", "body": "@user238115: You're conflating the two communities' different focus on what questions they tackle. If you're asking about improvements to your code (as a general review), this is the right place. But this isn't the place to start _discussing_ the repository pattern and practices surrounding it. That question is more for SoftwareEngineering.SE. Different communities tackle different questions/issues." } ]
[ { "body": "<p><code>DbContext</code> is a <code>Repository</code> and Entity Framework uses <strong>Unit of Work</strong> pattern to wrap it, so if you need to wrap <code>DbContext</code> with a <code>Repository</code> you will need to narrow it down to more focused scope.</p>\n<p>You'll find some arguments about wrapping a repository with another repository (e.g. using repository with EF). Generally, it's not about right or wrong, but it's about avoiding redundancy. Nevertheless, sometimes wrapping big repositories with scoped ones can be beneficial to your work as it would minimize the requirements and add more manageability to your code. You will find some open-source projects have done the same scenario (e.g. <a href=\"https://github.com/dotnet/aspnetcore/tree/main/src/Identity\" rel=\"nofollow noreferrer\"><code>ASP.NET Core Identity</code></a>). So, it depends on your application requirements.</p>\n<blockquote>\n<p>Is using GetQueryable in ProductController correct by Repository\npattern design? If not, is it only violation of Repository pattern or\nthere are some other performance issues?</p>\n</blockquote>\n<p>Returning the <code>Set&lt;T&gt;</code> would make the repository looses its job!. As <code>Set&lt;T&gt;</code> it's a repository itself, so do you think it would make sense if your repository returns another repository?. In the other hand, returning an <code>IQueryable&lt;T&gt;</code> interface over <code>IEnumerable&lt;T&gt;</code> interface would vary based on your code scope (where and when you want the query to be executed - (database vs memory)), but definitely it would add more flexibility to the repository consumer.</p>\n<p><strong>For questions 3 &amp; 4 :</strong></p>\n<p>EF is not ideal for bulk operations up until now (maybe will be better in future versions, you'll never know!), and it's not possible to build your own. However, using 3rd party will save time and efforts, and it'll give you clear and manageable code.</p>\n<p>Just need to mention that <code>System.Data.SqlClient</code> has <code>SqlBulkCopy</code> class, which is used for bulk insert operations, old school, but still useful.</p>\n<p><strong>Returning to your code</strong></p>\n<p>The solution structure needs to be more specific, for instance, <code>[ProjectName].Interfaces</code> layer would contain all possible contracts that the application uses, however, it would be more convenient if divided into several abstraction layers. abstractions layers should be related to each layer, like <code>[ProjectName].API.Abstractions</code>, <code>[ProjectName].Data.Abstractions</code> and so on. This would avoid including unwanted code, and would add more scoped and manageability to your contracts, and also would ease work with DI.</p>\n<p>The current <code>[ProjectName].Repositories</code> not sure how you'll use it, but since you'll have an <code>API</code> I assume your application architecture would use the <code>API</code> to query <code>Data</code> and return the results to the consumer. If true, then I don't believe you need <code>Repositories</code> as other layers will call <code>API</code> layer and not the <code>Data</code> layer. So, you'll need to use <code>API</code> layer as a service, in which will eliminate the redundancy that you have in current work.</p>\n<p><strong>A few notes on current implementation :</strong></p>\n<p><code>IBaseRepository</code> and <code>IServiceBase</code> :</p>\n<ul>\n<li>Both serve the same purpose, and almost have the same implementation, so it should be combined into one.</li>\n<li><code>GetQueryable</code> should be in a separate interface.</li>\n<li><code>BulkUpdate</code> and <code>BulkInsert</code> should be in a separate interface.</li>\n<li><code>GetById</code> and <code>Find</code> are similar, use one of them.</li>\n<li><code>bool saveChanges = true</code> no need for that, as <code>Save()</code> is already there.</li>\n<li><code>T, E</code> the generic naming is not descriptive enough in <code>IBaseRepository&lt;T, E&gt;</code>, while <code>IServiceBase&lt;TEntity, TPrimaryKey&gt;</code> is.</li>\n<li><code>Count</code> is unnecessary as you can do it in <code>Linq</code>.</li>\n<li><code>Save()</code> should return <code>Task&lt;int&gt;</code> which is the number of changed rows.</li>\n</ul>\n<p>The simplified version would be something like this :</p>\n<pre><code>public interface IRepository : IDisposal\n{\n Task&lt;int&gt; Save();\n}\n\npublic interface IRepositoryQueryable&lt;TEntity, TKey&gt; : IRepository\n where TEntity : class \n where TKey : struct\n{\n IQueryable&lt;TEntity&gt; GetQueryable();\n}\n\npublic interface IRepositoryBulk&lt;TEntity, TKey&gt; : IRepository\nwhere TEntity : class \nwhere TKey : struct\n{\n Task&lt;int&gt; BulkInsert(IEnumerable&lt;TEntity&gt; entities); // returns number of inserted entries\n Task&lt;int&gt; BulkUpdate(IEnumerable&lt;TEntity&gt; entities); // returns number of updated entries\n}\n\npublic interface IRepository&lt;TEntity, TKey&gt; : IRepository\n where TEntity : class \n where TKey : struct\n{\n Task&lt;IEnumerable&lt;TEntity&gt;&gt; GetAll();\n IEnumerable&lt;TEntity&gt; GetAll(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition);\n Task&lt;TEntity&gt; GetSingle(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition);\n Task&lt;TEntity&gt; GetByKey(TKey id);\n Task Insert(TEntity entity);\n Task Update(TEntity entity);\n Task Delete(TEntity entity);\n}\n</code></pre>\n<ul>\n<li><code>IRepository</code> base interface.</li>\n<li><code>IRepositoryQueryable&lt;TEntity, TKey&gt;</code> for <code>IQueryable</code> operations</li>\n<li><code>IRepositoryBulk&lt;TEntity, TKey&gt;</code> for bulk operations</li>\n<li><code>IRepository&lt;TEntity, TKey&gt;</code> for basic operations.</li>\n</ul>\n<p>With that, you have more flexibility to extend and manage your contracts. A use case scenario to show how this would be beneficial, is having an entity that doesn't support <code>Bulk</code> operations, if you use the <code>IBaseRepository</code> then either you will have to implement the <code>BulkInsert</code> and <code>BulkUpdate</code> logic or simply throw <code>NotImplementedException</code>, which is unneeded.</p>\n<p><strong>Modifying Current Structure</strong></p>\n<p>If you treat the <code>API</code> as a service, then you will simplify your structure and work further. Let's take a quick look on how things would be if we change it.</p>\n<p>the new Structure :</p>\n<ul>\n<li><code>Project.Data</code> : DbContext and all related work.</li>\n<li><code>Project.API</code> : Controllers and AutoMapper work.</li>\n<li><code>Project.Abstractions</code>: holds application contracts that would be consumed by consumers (outside Data and API layers).</li>\n<li><code>Project.Tests</code> : unit tests.</li>\n</ul>\n<p>you can do an abstraction for <code>Data</code> and another one for <code>API</code>, but for simplicity I just did one for the full project for demonstration purpose.</p>\n<p>We can make our work much simpler by creating one generic repository class under <code>Data</code> and then use this repository in the base controller.</p>\n<p>here is the substituted <code>BaseRepository</code> that would have <code>CUSTOM</code> logic :</p>\n<pre><code>public sealed class Repository&lt;TEntity, TKey&gt; : IRepository&lt;TEntity, TKey&gt;, IRepositoryQueryable&lt;TEntity, TKey&gt;, IRepositoryBulk&lt;TEntity, TKey&gt;\n where TEntity : class \n where TKey : struct\n{\n private readonly DatabaseContext _context;\n\n private readonly DbSet&lt;TEntity&gt; _dbSet; \n\n protected RepositoryBase() \n {\n _context = new DatabaseContext(); \n _dbSet = _context.Set&lt;TEntity&gt;();\n }\n \n public async Task&lt;IEnumerable&lt;TEntity&gt;&gt; GetAll()\n {\n return await _dbSet.ToListAsync();\n }\n \n public async Task Insert(TEntity entity)\n {\n _dbSet.Add(entity);\n }\n \n // add the rest of your custom code\n \n}\n</code></pre>\n<p>Now under <code>API</code> we can create a base controller something like this :</p>\n<pre><code>[Route(&quot;api/[controller]&quot;)]\npublic abstract class ServiceControllerBase&lt;TEntity, TKey&gt; : ControllerBase\n where TEntity : class \n where TKey : struct\n{\n protected Repository&lt;TEntity, TKey&gt; Repository { get; }\n protected ILogger Logger { get; }\n protected IMapper Mapper { get; }\n\n protected ServiceControllerBase(ILogger logger, IMapper Mapper)\n {\n Repository = new Repository&lt;TEntity, TKey&gt;();\n Logger = logger;\n Mapper = mapper;\n }\n}\n</code></pre>\n<p>then your controllers would be :</p>\n<pre><code>public class ProductController : ServiceControllerBase&lt;Product, Guid&gt;\n{\n public ProductController (ILogger&lt;ProductController&gt; logger, IMapper mapper)\n : base(logger, mapper) { }\n\n [HttpGet]\n public async Task&lt;IActionResult&gt; GetAllProductsWithAddresses()\n {\n try\n {\n \n var products = await Repository.GetAllQueryable().Include(x =&gt; x.Address).ToListAsync(); \n return Ok(Mapper.Map&lt;List&lt;ProductResponse&gt;&gt;(products));\n }\n catch (Exception e)\n {\n Logger.LogError($&quot;An unexpected error occured: ${e}&quot;);\n return StatusCode(StatusCodes.Status500InternalServerError);\n }\n }\n}\n</code></pre>\n<p>Now, at this stage all you are doing is just querying the database from the controller, and return the results to the <code>IActionResult</code> based on the given logic.</p>\n<p>This allows your application to be easy to integrate. For instance, if you want to add a web project, then in the web project you only need to reference <code>Project.Abstractions</code> and use <code>HttpClient</code> to call the <code>API</code> layer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T11:35:59.883", "Id": "256468", "ParentId": "256372", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T13:11:00.667", "Id": "256372", "Score": "2", "Tags": [ "c#", "performance", ".net", "repository", "asp.net-core" ], "Title": "Is repository pattern violated while using IQueryable outside of it?" }
256372
<p>I have a 2D array of fixed size and I've implemented a FIFO function. So, the array will always be full before it reaches the FIFO function, then the FIFO will remove the oldest array, move all of the arrays up by one and then add the newest array to the other end. Basically a queue. Now, this code will actually be running on a microcontroller, an array will come from an ADC and then I store the ADC array in a 2D array. To design the FIFO algorithm in simple C first, I have written a program that generates random numbers and then stores them into a 2D buffer. The program then asks the user what new values should be stored, user puts in the latest array of values and then the program removes the oldest array, shuffles all the remaining arrays up by one and then the latest user numbers get added to the end. The program does this 10 times. This is designed to simulate what is happening in the microcontroller code. The 2D array is already full with values and then the ADC adds the latest set of values to the array, and the oldest set are forgotten.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; int fixed_number[5] = { 0 }; uint16_t big_array[10][5] = { 0 }; uint16_t big_array_copy[10][5] = { 0 }; uint16_t small_array_1[5] = { 0 }; uint16_t k[1] = { 0 }; uint8_t count = 0; int main() { for (int j = 0; j &lt; 10; j++) { for (int i = 0; i &lt; 5; i++) { big_array[j][i] = rand() % 255; } } for (int j = 0; j &lt; 10; j++) { for (int i = 0; i &lt; 5; i++) { big_array_copy[j][i] = big_array[j][i]; } } printf(&quot;These are the original numbers in the big array:\n&quot;); for (int j = 0; j &lt; 10; j++) { for (int i = 0; i &lt; 5; i++) { k[0] = big_array[j][i]; printf(&quot;%d,&quot;, k[0]); } printf(&quot;\n&quot;); } while (count &lt; 10) { printf(&quot;Please enter values for queue:\n&quot;); for (int i = 0; i &lt; 5; i++) { scanf_s(&quot;%d&quot;, &amp;fixed_number[i]); } printf(&quot;\n\n&quot;); printf(&quot;Array values have been swapped:\n &quot;); for (int k = 0; k &lt; 5; k++) { big_array_copy[10 - 1][k] = 0; } for (int j = 9; j &gt; 0; j--) { for (int i = 0; i &lt; 5; i++) { //small_array_1[i] = big_array[j + 1][i]; big_array_copy[j][i] = big_array[j - 1][i]; } } for (int i = 0; i &lt; 5; i++) { big_array_copy[0][i] = fixed_number[i]; } for (int j = 0; j &lt; 10; j++) { for (int i = 0; i &lt; 5; i++) { k[0] = big_array_copy[j][i]; printf(&quot;%d,&quot;, k[0]); } printf(&quot;\n&quot;); } for (int j = 0; j &lt; 10; j++) { for (int i = 0; i &lt; 5; i++) { big_array[j][i] = big_array_copy[j][i]; } } count++; } } </code></pre> <p>Now this code works perfectly fine, but there is a lot of loops and it also requires twice the memory space as the buffer, big_array[][] must be copied in to big_array_copy[][]. In the real application, the buffer is uint16_t somebuffer[100][45] which is 4.5kb. I've got 512kb of SRAM to use, but I'd rather use as little as I can.</p> <p>The above method can be implemented on my target platform (STM32F767 for those wondering) but is there a more simple method to implementing the above, that uses fairly portable c with no special functions, that could reduce the memory required and the processing time required? thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T15:51:36.583", "Id": "506144", "Score": "1", "body": "Welcome to Code Review, I added the `c` language tag to your question. I am a lot rusty but you are using `iostream` in a `c` program ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T17:09:22.423", "Id": "506152", "Score": "1", "body": "C doesn't have `<iostream>`, but it appears that include can be safely removed to make this a real C program." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T17:18:21.350", "Id": "506154", "Score": "0", "body": "As I wrote this code in Visual Studio, it added <iostream> by default and I didn't notice. I'll remove it from the code just for clarification." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T17:19:42.820", "Id": "506155", "Score": "0", "body": "When you say \"In my real code\" like that, it suggests that this isn't what you're actually using. Here at Code Review, we expect to see finished production code, not prototypes!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T17:23:53.270", "Id": "506156", "Score": "0", "body": "I'm testing an algorithm, and want to know if my C implementation could be made more efficient within the parameters I set out in the question, with a brief summary of why those restraints are there. It shouldn't matter what the end use of the code is if its outside the boundaries of the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T17:26:54.443", "Id": "506158", "Score": "2", "body": "Please do not change the code after an answer has been written, everyone needs to be able to see the code that the reviewed saw. Please read [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T17:29:20.013", "Id": "506159", "Score": "0", "body": "@ pacmaninbw but the answer is telling me that I need to change the code before my question is answered? So what do I do, leave the question up, change the code as requested, and then post another question with the code in a format as requested by the original answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T18:04:23.297", "Id": "506161", "Score": "0", "body": "@ChrisD91 Unfortunately the way the answer is worded you were bound to break our rules. Yes I would improve the code and post a new question as editing the code in your question is not longer allowed. I understand our rules here may seem like some needless red tape, however problems coming from answer invalidation are messy and leaving this question as is and posting a new question seems like the best way to avoid problems here. Note you didn't really follow Toby's advice in full before, so please follow the advice in full when posting a new question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T07:42:48.260", "Id": "506197", "Score": "0", "body": "I should have been clearer - after addressing the easy issues, please post a new question with the updated code. I'm sorry for causing confusion!" } ]
[ { "body": "<p>We're missing an include of <code>&lt;stdint.h&gt;</code>. On the other hand, we include <code>&lt;time.h&gt;</code> which we're not using.</p>\n<p>The code doesn't compile here because of the use of Annex K <code>scanf_s()</code> without checking for its availability. There's no reason not to use ordinary <code>scanf()</code> here (but do examine its return value - that's important!)</p>\n<p>There are a lot of magic constants sprinkled throughout the code, with no indication whether they relate to each other. That makes this an unmaintainable program, because you can't change any of those individually without understanding the <em>whole program</em>.</p>\n<p>Also, with all the functionality thrown together in <code>main()</code>, that makes it harder to understand the purpose of each part of the code. Please divide the code into well-named functions (probably with <code>static</code> linkage).</p>\n<p>I recommend fixing those before posting another review request to look at this in any depth.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T17:18:30.503", "Id": "256384", "ParentId": "256378", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T14:58:15.313", "Id": "256378", "Score": "0", "Tags": [ "c", "array", "queue" ], "Title": "FIFO queue for a 2D array in ANSI C" }
256378
<p>Six month ago I started studying C as my first programming language and a couple of weeks ago I decided to write snake as my first program. The program is written with ncurses and contains four modules: main, layout, controls and gameplay. I haven't added any features yet (score, pause, welcome screen etc.).</p> <p>Since it is my first program I would really appreciate any comments on how to improve my code or make it more efficient. You may also comment on the program design on a more general level. Many thanks!</p> <p><strong>main.c</strong></p> <pre><code>#define _DEFAULT_SOURCE #include &quot;layout.h&quot; #include &quot;controls.h&quot; #include &quot;gameplay.h&quot; #include &lt;unistd.h&gt; #include &lt;ctype.h&gt; struct snake *head = NULL; struct food cheese; chtype body; int snakey = 5; int snakex = 5; int ch; bool horizontal = true; bool run = true; void init_game(void); int delay(int csec, bool horizontal); bool check_game(void); bool eat_cheese(); void change_direction(void); void update_window(void); int main(void) { srand(time(0)); init_game(); generate_cheese(&amp;cheese, head); direction = right; while (true) { if (check_game()) break; if (eat_cheese()) continue; ch = delay(10, horizontal); if (ch != ERR) { delay(7, horizontal); } if (tolower(ch) == 'q') break; change_direction(); update_window(); } delay(100, horizontal); endwin(); return 0; } void init_game(void) { WIN win; system(&quot;resize -s 31 100&quot;); initscr(); raw(); keypad(stdscr, true); nodelay(stdscr, true); noecho(); curs_set(false); win_params(&amp;win); create_box(&amp;win); refresh(); } int delay(int csec, bool horizontal) { int ch; for (int i = 0; i &lt; csec; i++) { ch = getch(); if (horizontal == true) { if (ch == KEY_UP | ch == KEY_DOWN) { return ch; } } else if (horizontal == false) { if (ch == KEY_LEFT | ch == KEY_RIGHT) { return ch; } } if (ch == 'q') { return ch; } flushinp(); usleep(10000); } return ERR; } bool check_game(void) { if (border_limit(head) || autocannibalism(head, snakey, snakex)) { mvprintw(head-&gt;y, head-&gt;x, &quot;*&quot;); return true; } return false; } bool eat_cheese() { if (cheese.y == snakey &amp;&amp; cheese.x == snakex) { direction(&amp;snakey, &amp;snakex, &amp;body); push_to_snake(&amp;head, snakey, snakex, body); generate_cheese(&amp;cheese, head); print_window(head, cheese); return true; } return false; } void change_direction(void) { switch(ch) { case KEY_UP: direction = up; horizontal = false; break; case KEY_DOWN: direction = down; horizontal = false; break; case KEY_LEFT: direction = left; horizontal = true; break; case KEY_RIGHT: direction = right; horizontal = true; break; } } void update_window(void) { direction(&amp;snakey, &amp;snakex, &amp;body); pop_from_snake(&amp;head); push_to_snake(&amp;head, snakey, snakex, body); print_window(head, cheese); } </code></pre> <p><strong>layout.h</strong></p> <pre><code>#ifndef LAYOUT_H #define LAYOUT_H #include &lt;ncurses.h&gt; #define BORDER_STARTY 2 #define BORDER_STARTX 2 #define BORDER_HEIGHT 27 #define BORDER_WIDTH 96 typedef struct _win_border_struct { chtype ls, rs, ts, bs, tl, tr, bl, br; } WIN_BORDER; typedef struct _WIN_struct { int startx, starty; int height, width; WIN_BORDER border; } WIN; void win_params(WIN *p_win); void create_box(WIN *p_win); #endif </code></pre> <p><strong>layout.c</strong></p> <pre><code>#include &quot;layout.h&quot; void win_params(WIN *p_win) { p_win-&gt;height = BORDER_HEIGHT; p_win-&gt;width = BORDER_WIDTH; p_win-&gt;starty = BORDER_STARTY; p_win-&gt;startx = BORDER_STARTX; p_win-&gt;border.ls = ACS_VLINE; p_win-&gt;border.rs = ACS_VLINE; p_win-&gt;border.ts = ACS_HLINE; p_win-&gt;border.bs = ACS_HLINE; p_win-&gt;border.tl = ACS_ULCORNER; p_win-&gt;border.tr = ACS_URCORNER; p_win-&gt;border.bl = ACS_LLCORNER; p_win-&gt;border.br = ACS_LRCORNER; } void create_box(WIN *p_win) { int x, y, w, h; x = p_win-&gt;startx; y = p_win-&gt;starty; w = p_win-&gt;width; h = p_win-&gt;height; mvaddch(y, x, p_win-&gt;border.tl); mvaddch(y, x + w, p_win-&gt;border.tr); mvaddch(y + h, x, p_win-&gt;border.bl); mvaddch(y + h, x + w, p_win-&gt;border.br); mvhline(y, x + 1, p_win-&gt;border.ts, w - 1); mvhline(y + h, x + 1, p_win-&gt;border.bs, w - 1); mvvline(y + 1, x, p_win-&gt;border.ls, h - 1); mvvline(y + 1, x + w, p_win-&gt;border.rs, h - 1); refresh(); } </code></pre> <p><strong>controls.h</strong></p> <pre><code>#ifndef CONTROLS_H #define CONTROLS_H #include &quot;layout.h&quot; void (*direction)(int *snakey, int *snakex, chtype *body); void left(int *snakey, int *snakex, chtype *body); void right(int *snakey, int *snakex, chtype *body); void up(int *snakey, int *snakex, chtype *body); void down(int *snakey, int *snakex, chtype *body); #endif </code></pre> <p><strong>controls.c</strong></p> <pre><code>#include &quot;controls.h&quot; void left(int *snakey, int *snakex, chtype *body) { (*snakex)--; *body = ACS_CKBOARD; } void right(int *snakey, int *snakex, chtype *body) { (*snakex)++; *body = ACS_CKBOARD; } void up(int *snakey, int *snakex, chtype *body) { (*snakey)--; *body = ACS_CKBOARD; } void down(int *snakey, int *snakex, chtype *body) { (*snakey)++; *body = ACS_CKBOARD; } </code></pre> <p><strong>gameplay.h</strong></p> <pre><code>#ifndef GAMEPLAY_H #define GAMEPLAY_H #include &lt;stdbool.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &quot;layout.h&quot; struct food { int y; int x; }; struct snake { chtype body; int x; int y; struct snake *next; }; bool border_limit(struct snake *head); bool autocannibalism(struct snake *head, int snakey, int snakex); void generate_cheese(struct food *cheese, struct snake *head); bool check_overlap(struct food *cheese, struct snake *head); void push_to_snake(struct snake **head, int y, int x, chtype body); void pop_from_snake(struct snake **head); void clear_window(struct food cheese); void print_window(struct snake *head, struct food cheese); #endif </code></pre> <p><strong>gameplay.c</strong></p> <pre><code>#include &quot;gameplay.h&quot; #define CHEESE ACS_DIAMOND bool border_limit(struct snake *head) { if (head == NULL) { return FALSE; } else if (head-&gt;y == BORDER_STARTY | head-&gt;y == BORDER_HEIGHT + BORDER_STARTY | head-&gt;x == BORDER_STARTX | head-&gt;x == BORDER_WIDTH + BORDER_STARTX) { return TRUE; } return FALSE; } bool autocannibalism(struct snake *head, int snakey, int snakex) { if (head == NULL) { return FALSE; } else { head = head-&gt;next; } while (head) { if (snakey == head-&gt;y &amp;&amp; snakex == head-&gt;x) { return TRUE; } head = head-&gt;next; } return FALSE; } void generate_cheese(struct food *cheese, struct snake *head) { while (true) { cheese-&gt;y = (rand() % (BORDER_HEIGHT - 1)) + BORDER_STARTY + 1; cheese-&gt;x = (rand() % (BORDER_WIDTH - 1)) + BORDER_STARTX + 1; if (check_overlap(cheese, head)) { continue; } else { mvaddch(cheese-&gt;y, cheese-&gt;x, CHEESE); break; } } } bool check_overlap(struct food *cheese, struct snake *head) { while (head != NULL) { if (cheese-&gt;y == head-&gt;y &amp;&amp; cheese-&gt;x == head-&gt;x) { return true; } head = head-&gt;next; } return false; } void push_to_snake(struct snake **head, int y, int x, chtype body) { struct snake *new_snake; new_snake = malloc(sizeof(struct snake)); if (new_snake == NULL) { printf(&quot;Error: malloc failed in %s&quot;, __func__); exit(EXIT_FAILURE); } new_snake-&gt;body = body; new_snake-&gt;y = y; new_snake-&gt;x = x; new_snake-&gt;next = *head; *head = new_snake; } void pop_from_snake(struct snake **head) { struct snake *tail = *head; while (tail != NULL) { if (tail-&gt;next == NULL) { *head = tail-&gt;next; free(tail); break; } head = &amp;tail-&gt;next; tail = tail-&gt;next; } } void clear_window(struct food cheese) { for (int i = BORDER_STARTX + 1; i &lt; BORDER_HEIGHT + 2; i++) { for (int j = BORDER_STARTY + 1; j &lt; BORDER_WIDTH + 2; j++) { mvprintw(i, j, &quot; &quot;); } } mvaddch(cheese.y, cheese.x, CHEESE); } void print_window(struct snake *head, struct food cheese) { clear_window(cheese); while (head) { mvaddch(head-&gt;y, head-&gt;x, head-&gt;body); head = head-&gt;next; } refresh(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T18:19:39.907", "Id": "506163", "Score": "0", "body": "`border_limit` should use the `||` operator in the `if` statement, not `|`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T16:49:28.040", "Id": "256382", "Score": "1", "Tags": [ "c", "snake-game", "curses" ], "Title": "First c program: Snake with ncurses" }
256382
<p>This is a modification of my <a href="https://codereview.stackexchange.com/questions/256378/fifo-queue-for-a-2d-array-in-ansi-c?noredirect=1#comment506161_256378">previous version</a>.</p> <p>I would like advice on improving a FIFO algorithm for a 2D array that I've developed in ANSI C.</p> <p>I have written code that uses this algorithm for test purposes. Random numbers are put into an array until all elements are full. The program then asks the user what numbers need to go in to the 2D array in order to update it. The code then removes the oldest array, shifts all remaining arrays up by one, and then adds the new array (as input by the user).</p> <p>I am asking for a review of the FIFO code, <code>fifo_algorithm</code>; the surrounding code is only for testing purposes. I would appreciate any suggestions that only use standard C.</p> <p>code:</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void random_num_input(void); void print_random_num_input(void); void print_new_array(void); void fifo_algorithm(void); int user_num[5] = { 0 }; uint16_t big_array[10][5] = { 0 }; uint16_t big_array_copy[10][5] = { 0 }; uint16_t array_print[1] = { 0 }; uint8_t count = 0; int main() { random_num_input(); printf(&quot;These are the original numbers in the big array:\n&quot;); print_random_num_input(); while (count &lt; 10) { printf(&quot;Please enter values to swap in:\n&quot;); for (int i = 0; i &lt; 5; i++) { scanf(&quot;%d&quot;, &amp;user_num[i]); } printf(&quot;\n\n&quot;); fifo_algorithm(); count++; } } //stores random numbers between 0-255 into big_array and big_array_copy void random_num_input(void) { for (int j = 0; j &lt; 10; j++) { for (int i = 0; i &lt; 5; i++) { big_array[j][i] = rand() % 255; } } } //prints the random values within the big_array void print_random_num_input(void) { for (int j = 0; j &lt; 10; j++) { for (int i = 0; i &lt; 5; i++) { array_print[0] = big_array[j][i]; printf(&quot;%d,&quot;, array_print[0]); } printf(&quot;\n&quot;); } } //This algorithm removes the oldest array in big_array_copy (element 9), shifts every //element up by 1 and stores the user inputted array into element 0. Thus a fifo that updates //the 2d array with the user input values every time void fifo_algorithm(void) { for (int j = 0; j &lt; 10; j++) { for (int i = 0; i &lt; 5; i++) { big_array_copy[j][i] = big_array[j][i]; } } for (int k = 0; k &lt; 5; k++) { big_array_copy[10 - 1][k] = 0; } for (int j = 9; j &gt; 0; j--) { for (int i = 0; i &lt; 5; i++) { big_array_copy[j][i] = big_array[j - 1][i]; } } for (int i = 0; i &lt; 5; i++) { big_array_copy[0][i] = user_num[i]; } print_new_array(); for (int j = 0; j &lt; 10; j++) { for (int i = 0; i &lt; 5; i++) { big_array[j][i] = big_array_copy[j][i]; } } } //simply prints the new, updated values in big_array_copy void print_new_array(void) { printf(&quot;These array values have been swapped:\n &quot;); for (int j = 0; j &lt; 10; j++) { for (int i = 0; i &lt; 5; i++) { array_print[0] = big_array_copy[j][i]; printf(&quot;%d,&quot;, array_print[0]); } printf(&quot;\n&quot;); } } </code></pre> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T08:02:59.103", "Id": "506199", "Score": "0", "body": "I see you didn't incorporate the advice to indicate which of the constants are related (all those 5s, 9s and 10s). Is there a good reason why not?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T08:08:42.883", "Id": "506200", "Score": "0", "body": "Yes, because the constants are irrelevant as it could be any size array. I could have put macros down to name 5 and 10 but I didn't see how that could be advantageous, other than you can change the array size more easily as the loops are dependent on a fixed array size." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T12:37:18.793", "Id": "506217", "Score": "0", "body": "With magic constants scattered all over the function like that, it will only work with one specific size of array, and changing to any other size would involve some tedious and error-prone changes. But I'll mention that in my review (when I get time - it's a busy day for me here)." } ]
[ { "body": "<p><strong>Good formatting</strong></p>\n<p><strong>Good use of <code>(u)intN_t</code> types</strong></p>\n<p>When printing, use a matching format specifier: <code>printf(&quot;%&quot; PRI16u , array_print[0]);</code></p>\n<p><strong>Avoid naked magic numbers</strong></p>\n<p>Define constants for flexibility and clarity</p>\n<pre><code>// int user_num[5] = { 0] };\n//uint16_t big_array[10][5] = { 0 };\n\n#define BIG_ARRAY_MAXJ 10\n#define BIG_ARRAY_MAXI 5\nint user_num[BIG_ARRAY_MAXI] = { 0 };\nuint16_t big_array[BIG_ARRAY_MAXJ][BIG_ARRAY_MAXI] = { 0 };\n</code></pre>\n<p>Instead of <code>9</code>, use <code>BIG_ARRAY_MAXJ - 1</code>, etc.</p>\n<p>To address the &quot;I could have put macros down to name 5 and 10 but I didn't see how that could be advantageous,&quot; comment: using named constants convey to others, including yourself at a later time, the relationship amongst the many constants and their individual meaning.</p>\n<p><strong>Global objects</strong></p>\n<p>Typically, it is far better to code for use of local objects than global ones.</p>\n<p>Instead of</p>\n<pre><code>random_num_input(void)\n</code></pre>\n<p>Pass in a pointer to the array and its dimensions. If <a href=\"https://en.wikipedia.org/wiki/Variable-length_array#C99\" rel=\"nofollow noreferrer\">VLA</a> is supported:</p>\n<pre><code>random_num_input(int jn, int in, uint16_t a[j][i]) {\n for (int j = 0; j &lt; jn; j++) {\n for (int i = 0; i &lt; in; i++) {\n a[j][i] = rand() % 256;\n }\n}\n</code></pre>\n<p><strong>Array indexing</strong></p>\n<p>For <em>big</em> arrays, consider <code>size_t</code> instead of <code>int</code> to well handle large arrays. <code>size_t</code> is the <a href=\"https://en.wikipedia.org/wiki/Goldilocks_principle\" rel=\"nofollow noreferrer\">Goldilocks</a> size for array sizing and indexing: not too small, not too big.</p>\n<p>For <em>big</em> arrays, likely also need to move to allocated memory rather than fixed sizes.</p>\n<p><strong>Comment/code off by 1.</strong></p>\n<p><code>rand() % 255</code> forms values [0...254], not [0...255].</p>\n<pre><code>// stores random numbers between 0-255 into big_array ...\n big_array[j][i] = rand() % 255;\n</code></pre>\n<p>Consider</p>\n<pre><code>big_array[j][i] = rand() % 256;\n// or \nbig_array[j][i] = (uint8_t) rand();\n</code></pre>\n<p><strong>Copying arrays</strong></p>\n<p>With arrays of the same dimension and type, as here, could use <code>memcpy()</code>.</p>\n<pre><code>// for (int j = 0; j &lt; 10; j++) //\n// for (int i = 0; i &lt; 5; i++) {\n// big_array_copy[j][i] = big_array[j][i];\n// }\n//}\n\n// if known to be non-overlapping \nmemcpy(big_array_copy, big_array, sizeof big_array_copy); \n// else \nmemmove(big_array_copy, big_array, sizeof big_array_copy);\n</code></pre>\n<p><strong>Minor: Tidier print</strong></p>\n<p>Consider not printing a trailing <code>','</code>. Little reason for a global <code>array_print[]</code>. Use the correct portable specifier</p>\n<pre><code> char *sep = &quot;&quot;;\n for (int i = 0; i &lt; BIG_ARRAY_MAXI; i++) {\n printf(&quot;%s%&quot; PRI16u , sep, big_array_copy[j][i]);\n sep = &quot;,&quot;;\n }\n printf(&quot;\\n&quot;);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T22:51:08.083", "Id": "506247", "Score": "0", "body": "Thanks for the review. Although memcpy is easier for the programmer to write, is it as portable or more efficient than the basic for loop implementation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T22:54:16.987", "Id": "506248", "Score": "0", "body": "@ChrisD91 It is portable and is more _linearly_ efficient for large arrays. When looking at efficiency, best to focus on [big O](https://en.wikipedia.org/wiki/Big_O_notation) and code clarity than spend too much effort on linear issues." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T17:26:14.233", "Id": "256418", "ParentId": "256385", "Score": "1" } }, { "body": "<p>Passing everything in global variables might seem convenient for this small program, but is a poor practice more generally, since it makes it hard to reason about any function in isolation. In particular, <code>big_array_copy</code>, <code>array_print</code> and <code>count</code> seem to be used only for short-term storage, so should be local to their respective functions.</p>\n<p>The functions are tightly bound to those globals, and to the particular array sizes you have chosen. If you ever want to change any of the dimensions, you'll need to re-understand the entire program to make the many changes that are required. You could save all that effort by simply writing a couple of manifest constants for the dimensions, and using them consistently. That also helps readers, who no longer need to keep referring back to the definitions to check whether the bounds are correct (and remember, your code will be read many more times than written!).</p>\n<p>It's not clear why <code>user_num</code> holds <code>int</code> values, as they get silently converted to <code>uint16_t</code>:</p>\n<pre><code> big_array_copy[0][i] = user_num[i];\n</code></pre>\n<p>This problem could be avoided by declaring <code>user_num</code> to be an array of <code>uint16_t</code>.</p>\n<p>There's no need for <code>big_array_copy</code> - just move the items within <code>big_array</code> and then copy the new items into it:</p>\n<pre><code>void fifo_algorithm(uint16_t const *user_num)\n{\n memmove(big_array+1, big_array, sizeof big_array - sizeof big_array[0]);\n memcpy(big_array[0], user_num, sizeof big_array[0]);\n}\n</code></pre>\n<p>Not only is that much shorter than copying one element at a time to <code>big_array_copy</code> and back, it's also much less work for CPU and cache, too.</p>\n<p>The input handling is very weak - if we mistakenly provide a non-numeric input, the <code>scanf()</code> will repeatedly fail trying to parse it.</p>\n<p>It's good to see you've included a test program. You could improve on that by making the tests <em>self-checking</em> and providing their own input. As it is, the test requires a separate input file (or even worse, manual entry of data) and it requires visual inspection of the output, both of which make it unsuitable for automated regression testing.</p>\n<hr />\n<h1>Improved code</h1>\n<pre><code>#include &lt;inttypes.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nstatic void random_num_input(void);\nstatic int read_user_values(uint16_t *user_num);\nstatic void print_array(void);\nstatic void fifo_algorithm(uint16_t const *user_num);\n\n/* Global FIFO object */\n#define COLS 5\n#define ROWS 10\nuint16_t big_array[ROWS][COLS] = { 0 };\n\nint main(void)\n{\n random_num_input();\n puts(&quot;These are the original numbers in the big array:&quot;);\n print_array();\n for (int count = 0; count &lt; ROWS; ++count) {\n uint16_t user_num[COLS] = { 0 };\n int status = read_user_values(user_num);\n if (status) {\n return status;\n }\n printf(&quot;\\n\\n&quot;);\n fifo_algorithm(user_num);\n print_array();\n }\n}\n\n// Populate the FIFO with random numbers between 0-255\nvoid random_num_input(void)\n{\n for (int j = 0; j &lt; ROWS; ++j) {\n for (int i = 0; i &lt; COLS; ++i) {\n big_array[j][i] = (uint16_t)(rand() &amp; 0xff);\n }\n }\n}\n\n\nstatic int read_user_values(uint16_t *user_num)\n{\n puts(&quot;Please enter values to swap in:&quot;);\n for (int i = 0; i &lt; COLS; ++i) {\n int status = scanf(&quot;%&quot; SCNu16, &amp;user_num[i]);\n if (status == EOF) {\n fputs(&quot;Failed to read input\\n&quot;, stderr);\n return EXIT_FAILURE;\n } else if (status != 1) {\n /* discard and re-read this datum */\n fprintf(stderr, &quot;Failed to parse item %d; Re-enter last %d value(s)\\n&quot;,\n i, COLS-i);\n scanf(&quot;%*[^\\n]&quot;);\n --i; /* repeat this scanf */\n }\n }\n return 0; /* success */\n}\n\n\n// Prints the contents of the FIFO\nvoid print_array(void)\n{\n for (int j = 0; j &lt; ROWS; ++j) {\n for (int i = 0; i &lt; COLS; ++i) {\n printf(&quot;%&quot; PRIu16&quot;,&quot;, big_array[j][i]);\n }\n printf(&quot;\\n&quot;);\n }\n}\n\n// Shift a new row of data into the FIFO\nvoid fifo_algorithm(uint16_t const *user_num)\n{\n memmove(big_array+1, big_array, sizeof big_array - sizeof big_array[0]);\n memcpy(big_array[0], user_num, sizeof big_array[0]);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T14:52:43.277", "Id": "506282", "Score": "0", "body": "`scanf(\"%*[^\\n]%*c\");` is a common way to clear the reset of the line, yet is error prone _in general_ to handle various cases. Yet this usage is good as it comes _after_ a failed read attempt of an integer and is qualified with a status of not `EOF, 1`. UV for that. The `\"%*c\"` introduces asymmetry: successful integer read leaves \\n in stdin, failed integer read leads to reading the '\\n'. IAC not needed as a re-scan with `\"%d\"` consumes the leading white-space." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T15:57:34.887", "Id": "506286", "Score": "0", "body": "Yes, of course we don't need the `%*c` - I'll remove that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T08:53:58.550", "Id": "256429", "ParentId": "256385", "Score": "1" } } ]
{ "AcceptedAnswerId": "256418", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T18:17:23.010", "Id": "256385", "Score": "1", "Tags": [ "c", "array", "queue" ], "Title": "FIFO queue for a 2D array in ANSI C, version 2" }
256385
<h3>Some methods of this library require some improvements (see this description):</h3> <ol> <li><p>In the <code>constructor</code> I am trying to create the possibility that the user modifies the colors of the output. I think it can improve but I do not know if there is any standard or good practices in this regard, or if there is any way to optimize this class.</p> </li> <li><p>The method <code>getIndent</code> uses the analysis of the variable to determine the indentation of the output using the function <code>array_walk_recursive</code>. I don't have much knowledge about the handling of arrays, therefore I used this method because I found it simple. I don't know if it is the best to fulfil the purpose of the <code>getIndent</code> method.</p> </li> <li><p>The <code>AnalVariable</code> method uses the abstraction of the <code>pretty</code> function. It was the only example I found in which it allowed me to have an output similar to that of <code>var_dump</code> or <code>var_export</code>. Some other developers suggested to me to use reflection but I did not find an example related to the use / purpose that I want to give it.</p> <p>I also have an analysis cluster for spacing using ternary analysis. I would like someone with more experience to check, looking for possible errors or improvements. With the minimal tests that I have carried out I have not obtained any error.</p> </li> <li><p>The <code>EvalVariable</code> method is my favorite; This method is responsible for analyzing the data of the passed variable to determine the type of data and return it, taking into account that the returned code / value is usable. But I have not been able to recreate the objects or resources to make them usable, let's see an example :</p> <p>Example array we have a node as follows:</p> <pre><code>'resource' =&gt; curl_init() </code></pre> <p>but in the output tube to put:</p> <pre><code>'resource' =&gt; resource </code></pre> <p>This happens because the data type does not say that it comes from a <code>curl_init();</code> what I was hoping to do, which I have failed to do, is show the output:</p> <pre><code>'resource' =&gt; curl_init() </code></pre> </li> <li><p>Another thing that I also think can negatively impact the performance of the library is the analysis done by the <code>EvalVariable</code> method since it is a set of if and verifications. I think it can be improved but I don't know where to start or what things I should change.</p> </li> <li><p>I have also managed to improve the output a bit by adding or enriching it with a comment where I describe a more in-depth analysis.</p> <pre class="lang-php prettyprint-override"><code>// object (stdClass) # 2 (2). // object (FooBar) # 3 (0). // resource (6) of type (curl). </code></pre> </li> <li><p>The method <code>HighlightCode</code> is in charge of fixing the screen output. In this case, I use the <code>highlight_string</code> method in conjunction with other concatenations to take it to an HTML. But I don't know how I can recreate this for the CLI, which I would like to implement.</p> </li> <li><p>Another important point for me is to evaluate if in general the Script / library complies with the active PSR standards. I use the phpStorm IDE but it does not detect an error of this type.</p> </li> </ol> <p>My goal is to improve this script. I have listed the main points, and I await comments on them. Although it is not the main objective, I am also open to hear opinions based on documented and exemplified improvements.</p> <h2>Class/library Description:</h2> <h3>[BOH] Basic Output Handler for PHP</h3> <p><em>Acronym</em>: [BOH].<br /> <em>Name</em>: Basic Output Handler.<br /> <em>Dependencies</em>: Stand Alone / PHP v7.4.</p> <h3>What does [BOH] do?</h3> <p>[BOH] is a very simple PHP [output handler] implementation that show Human readable information instead of using the default PHP options:</p> <ul> <li><code>var_dump()</code> - Displays information about a variable.</li> <li><code>print_r()</code> - Print human-readable information about a variable.</li> <li><code>debug_zval_dump()</code> - Outputs a string representing an internal value of zend.</li> <li><code>var_export()</code> - Print or return a string representation of a parseable variable.</li> </ul> <p>This means that all the data passed is presented to the developer according to the chosen parameters. It also means that the displayed data can be directly reused as code. Comments are also generated for each value that briefly explains the type of data</p> <h3>Why use [BOH]?</h3> <p>Developers need the ability to decide how their code behaves when data needs to be checked. The native PHP Methods provide a range of information that is not reusable by the developer or may even require more work to get the correct output for data verification.</p> <p>This library handles data output proven to be extremely effective. [BOH] is a standalone implementation that can be used for any project and does not require a third-party library or software.</p> <h3>Help to improve [BOH]?</h3> <p>If you want to collaborate with the development of the library; You can express your ideas or report any situation related to this in: <a href="https://github.com/arcanisgk/BOH-Basic-Ouput-Handler/issues" rel="nofollow noreferrer">the issues section of the repository on github</a></p> <h2>My code</h2> <pre class="lang-php prettyprint-override"><code>&lt;?php namespace IcarosNet\BOHBasicOutputHandler; if (!version_compare(phpversion(), '7.4', '&gt;=')) { die('IcarosNet\BOHBasicOutputHandler requires PHP ver. 7.4 or higher'); } if (!defined('ENVIRONMENT_OUTPUT_HANDLER')) { define('ENVIRONMENT_OUTPUT_HANDLER', (IsCommandLineInterface() ? 'cli' : 'web')); } class OutputHandler { public string $background = ''; public string $themeused; public string $defenv = ''; public array $colorcli = [ &quot;comment&quot; =&gt; '', &quot;constant&quot; =&gt; '', &quot;function&quot; =&gt; '', &quot;keyword&quot; =&gt; '', &quot;magic&quot; =&gt; '', &quot;string&quot; =&gt; '', &quot;tag&quot; =&gt; '', &quot;variable&quot; =&gt; '', &quot;html&quot; =&gt; '', &quot;&quot; =&gt; &quot;%s&quot;, &quot;background&quot; =&gt; '', ]; public function __construct($theme = 'default') { $this-&gt;Theme($theme); $this-&gt;defenv = ENVIRONMENT_OUTPUT_HANDLER; } public function __destruct() { $this-&gt;ResetHighlight(); } //Theme Code and Highlight public function ResetHighlight() { ini_set(&quot;highlight.comment&quot;, &quot;#FF9900&quot;); ini_set(&quot;highlight.default&quot;, &quot;#0000BB&quot;); ini_set(&quot;highlight.html&quot;, &quot;#000000&quot;); ini_set(&quot;highlight.keyword&quot;, &quot;#007700; font-weight: bold&quot;); ini_set(&quot;highlight.string&quot;, &quot;#DD0000&quot;); } public function Theme(string $theme = 'default') { $this-&gt;themeused = $theme; switch ($theme) { case 'x-space': $color = ['043,128,041', '099,099,099', '128,128,128', '072,094,187', '221,079,079', '000,000,000']; $this-&gt;background = '000000'; break; case 'mauro-dark': $color = ['187,134,252', '250,250,250', '003,218,197', '255,204,255', '207,102,121', '018,018,018']; $this-&gt;background = '121212'; break; case 'natural-flow': $color = ['145,155,152', '30,156,107', '003,218,197', '006,156,004', '139,156,51', '004,041,003']; $this-&gt;background = '042903'; break; case 'monokai': $color = ['117,113,94', '255,255,255', '102,217,239', '249,038,114', '230,219,116', &quot;039,040,034&quot;]; $this-&gt;background = '272822'; break; default: $color = ['255,095,000', '000,000,255', '000,000,000', '000,175,000', '255,000,000', '255,255,255']; $this-&gt;background = 'ffffff'; break; } $this-&gt;UpdateInitSetHighlight($color); $this-&gt;UpdateInitSetHighlightCli($color); } private function UpdateInitSetHighlight($color) { ini_set(&quot;highlight.comment&quot;, 'rgb(' . $color[0] . '); background-color: #' . $this-&gt;background); ini_set(&quot;highlight.default&quot;, 'rgb(' . $color[1] . '); background-color: #' . $this-&gt;background); ini_set(&quot;highlight.html&quot;, 'rgb(' . $color[2] . '); background-color: #' . $this-&gt;background); ini_set(&quot;highlight.keyword&quot;, 'rgb(' . $color[3] . &quot;); font-weight: bold; background-color: #&quot; . $this-&gt;background); ini_set(&quot;highlight.string&quot;, 'rgb(' . $color[4] . ');background-color: #' . $this-&gt;background); } private function UpdateInitSetHighlightCli($color) { $this-&gt;colorcli['comment'] = &quot;\033[38;2;&quot; . $this-&gt;RGBforCLI($color[0]) . &quot;m%s\033[0m&quot;; $this-&gt;colorcli['constant'] = &quot;\033[38;2;&quot; . $this-&gt;RGBforCLI($color[4]) . &quot;m%s\033[0m&quot;; $this-&gt;colorcli['function'] = &quot;\033[38;2;&quot; . $this-&gt;RGBforCLI($color[1]) . &quot;m%s\033[0m&quot;; $this-&gt;colorcli['keyword'] = &quot;\033[38;2;&quot; . $this-&gt;RGBforCLI($color[3]) . &quot;m%s\033[0m&quot;; $this-&gt;colorcli['magic'] = &quot;\033[38;2;&quot; . $this-&gt;RGBforCLI($color[1]) . &quot;m%s\033[0m&quot;; $this-&gt;colorcli['string'] = &quot;\033[38;2;&quot; . $this-&gt;RGBforCLI($color[4]) . &quot;m%s\033[0m&quot;; $this-&gt;colorcli['tag'] = &quot;\033[38;2;&quot; . $this-&gt;RGBforCLI($color[1]) . &quot;m%s\033[0m&quot;; $this-&gt;colorcli['variable'] = &quot;\033[38;2;&quot; . $this-&gt;RGBforCLI($color[3]) . &quot;m%s\033[0m&quot;; $this-&gt;colorcli['html'] = &quot;\033[38;2;&quot; . $this-&gt;RGBforCLI($color[2]) . &quot;m%s\033[0m&quot;; $this-&gt;colorcli['background'] = &quot;\033[48;2;&quot; . $this-&gt;RGBforCLI($color[5]) . &quot;m&quot;; } private function RGBforCLI($color) { return str_replace(',', ';', $color); } private function HighlightCode(string $string): string { return highlight_string(&quot;&lt;?php \n#output of Variable:&quot; . str_repeat(' ', 10) . '*****| Theme Used: ' . $this-&gt;themeused . &quot; |*****\n&quot; . $string . &quot;\n?&gt;&quot;, true); } private function HighlightCodeCli(string $string): string { $bg = $this-&gt;colorcli['background']; $string = '&lt;?php' . PHP_EOL . $string . PHP_EOL . '?&gt;'; $string = $this-&gt;CoverforBackground($string); $COLORS = $this-&gt;colorcli; $TOKENS = [ T_AS =&gt; &quot;as&quot;, T_CLOSE_TAG =&gt; &quot;tag&quot;, T_COMMENT =&gt; &quot;comment&quot;, T_CONCAT_EQUAL =&gt; &quot;&quot;, T_CONSTANT_ENCAPSED_STRING =&gt; &quot;string&quot;, T_CONTINUE =&gt; &quot;keyword&quot;, T_DOUBLE_ARROW =&gt; &quot;variable&quot;, T_ECHO =&gt; &quot;keyword&quot;, T_ELSE =&gt; &quot;keyword&quot;, T_FILE =&gt; &quot;magic&quot;, T_FOREACH =&gt; &quot;keyword&quot;, T_FUNCTION =&gt; &quot;keyword&quot;, T_IF =&gt; &quot;keyword&quot;, T_IS_EQUAL =&gt; &quot;&quot;, T_ISSET =&gt; &quot;keyword&quot;, T_LIST =&gt; &quot;keyword&quot;, T_OPEN_TAG =&gt; &quot;tag&quot;, T_RETURN =&gt; &quot;keyword&quot;, T_STATIC =&gt; &quot;keyword&quot;, T_VARIABLE =&gt; &quot;variable&quot;, T_WHITESPACE =&gt; &quot;&quot;, T_LNUMBER =&gt; &quot;function&quot;, T_DNUMBER =&gt; &quot;function&quot;, T_OBJECT_CAST =&gt; &quot;variable&quot;, T_STRING =&gt; &quot;function&quot;, T_INLINE_HTML =&gt; &quot;&quot;, ]; $output = &quot;&quot;; foreach (token_get_all($string) as $token) { if (is_string($token)) { $output .= $bg . $token . &quot;\033[0m&quot;; continue; } list($t, $str) = $token; if ($t == T_STRING) { if (function_exists($str)) { $output .= $bg . sprintf($COLORS[&quot;function&quot;], $str) . &quot;\033[0m&quot;; } else { if (defined($str)) { $output .= $bg . sprintf($COLORS[&quot;function&quot;], $str) . &quot;\033[0m&quot;; } else { $output .= $bg . sprintf($COLORS[&quot;function&quot;], $str) . &quot;\033[0m&quot;; } } } else { if (isset($TOKENS[$t])) { $output .= $bg . sprintf($COLORS[$TOKENS[$t]], $str) . &quot;\033[0m&quot;; } else { $output .= $bg . sprintf(&quot;&lt;%s '%s'&gt;&quot;, token_name($t), $str) . &quot;\033[0m&quot;; } } } return $output; } private function CoverforBackground(string $string): string { $info = shell_exec('MODE 2&gt; null') ?? shell_exec('tput cols'); $widthreal = 80; if (strlen($info) &gt; 5) { preg_match('/CON.*:(\n[^|]+?){3}(?&lt;cols&gt;\d+)/', $info, $match); $widthreal = $match['cols'] ?? 80; } $width = (int) $widthreal - 10; $stringarr = preg_split('/\r\n|\r|\n/', rtrim($string)); $numline = count($stringarr); $maxlen = max(array_map(function ($el) { return mb_strlen($el); }, $stringarr)); $longest = ($maxlen &gt; $width ? $maxlen : $width); if ($maxlen &gt; $widthreal) { echo 'Oops, your terminal window is not wide enough to display the information correctly.' . PHP_EOL . 'If you can increase the amount of characters per line (' . ($maxlen + 10) . ') it would work correctly.'; exit; } $string = ''; $count = 1; foreach ($stringarr as $key =&gt; $line) { $lenline = mb_strlen($line); $string .= $line . str_repeat(' ', $longest - $lenline) . ($count &lt; $numline ? PHP_EOL : ''); $count++; } return $string; } private function ApplyCss(string $string): string { $bg = '#' . $this-&gt;background; $class = mt_rand(); return '&lt;style&gt;.outputhandler-' . $class . '{background-color: ' . $bg . '; padding: 8px;border-radius: 8px;}&lt;/style&gt; &lt;div class=&quot;outputhandler-' . $class . '&quot;&gt;' . $string . '&lt;/div&gt;'; } //core Analysis or OuputHandler private function CheckEnv($env): string { $iscli = IsCommandLineInterface(); $env = ($env == null ? $this-&gt;defenv : $env); if ($iscli &amp;&amp; $env == 'wb') { echo 'error: you are trying to run output() method from CLI and it is not supported, use OutputCli() or AdvanceOutput() with CLI argument method instead.'; exit; } elseif (!$iscli &amp;&amp; $env == 'cli') { echo 'error: you are trying to run OutputCli() method from web browser and it is not supported, use Output() or AdvanceOutput() with HTML argument method instead.'; exit; } return $env; } public function Output($var, $env = null, $retrive = false) { $env = $this-&gt;CheckEnv($env); if ($env == 'web') { $string = $this-&gt;OutputWb($var, $retrive); } elseif ($env == 'cli') { $string = $this-&gt;OutputCli($var, $retrive); } else { $string = $this-&gt;OutputWb($var, $retrive); } if ($retrive) { return $string; } } public function OutputWb($var, $retrive = false) { $indents = $this-&gt;GetIndent($var); $string = $this-&gt;GetString($var, $indents); $string = $this-&gt;HighlightCode($string); $string = $this-&gt;ApplyCss($string); $this-&gt;ResetHighlight(); return ($retrive ? $string : $this-&gt;OutView($string)); } public function OutputCli($var, $retrive = false) { $indents = $this-&gt;GetIndent($var); $string = $this-&gt;GetString($var, $indents); $string = $this-&gt;HighlightCodeCli($string); $this-&gt;ResetHighlight(); return ($retrive ? $string : $this-&gt;OutView($string)); } private function GetIndent($var): array { $data = $var; $indents = ['key' =&gt; 0, 'val' =&gt; 0]; if (is_array($data) || is_object($data)) { array_walk_recursive($data, function (&amp;$value) { $value = is_object($value) ? (array) $value : $value; }); $deep = ($this-&gt;CalcDeepArray($data) + 1) * 4; array_walk_recursive($data, function ($value, $key) use (&amp;$indents) { $indents['key'] = ($indents['key'] &gt;= mb_strlen($key)) ? $indents['key'] : mb_strlen($key); if (!is_array($value) &amp;&amp; !is_object($value) &amp;&amp; !is_resource($value)) { $indents['val'] = ($indents['val'] &gt;= mb_strlen($value)) ? $indents['val'] : mb_strlen($value); } }, $indents); $indents['key'] += $deep; $indents['val'] += $deep / 2; } else { $indents = ['key' =&gt; mb_strlen('variable'), 'val' =&gt; mb_strlen($data)]; } return $indents; } private function CalcDeepArray(array $array): int { $max_depth = 0; foreach ($array as $key =&gt; $value) { if (is_array($value)) { $depth = $this-&gt;CalcDeepArray($value) + 1; if ($depth &gt; $max_depth) { $max_depth = $depth; } } } return $max_depth; } private function GetString($var, array $indents): string { return $this-&gt;AnalysisVariable('variable', $var, $indents); } private function AnalysisVariable(string $varname, $var, array $indents): string { $pretty = function ($indents, $varlentitle, $v = '', $c = &quot; &quot;, $in = 0, $k = null) use (&amp;$pretty) { $r = ''; if (in_array(gettype($v), array('object', 'array'))) { $lenname = mb_strlen(&quot;'$k'&quot;); $lenkeys = $indents['key'] - $in - $lenname; if ($lenkeys &lt; 0) { $lenkeys = 0; } $eval = $this-&gt;EvaluateVariable($v); $v = (array) $v; $lenkey = $indents['val'] - mb_strlen($eval['val']) + 1; if (empty($v)) { $r .= ($in != 0 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : &quot;'$k'&quot; . str_repeat($c, $lenkeys) . &quot;=&gt; &quot; . $eval['val'] . &quot;[],&quot; . str_repeat(&quot; &quot;, $lenkey - 6) . &quot;// &quot; . $eval['desc']) . (empty($v) ? '' : PHP_EOL); } else { $r .= ($in != 0 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : &quot;'$k'&quot; . str_repeat($c, $lenkeys) . &quot;=&gt; &quot; . $eval['val'] . &quot;[&quot; . str_repeat(&quot; &quot;, $lenkey - 4) . &quot;// &quot; . $eval['desc']) . (empty($v) ? '' : PHP_EOL); foreach ($v as $sk =&gt; $vl) { $r .= $pretty($indents, $varlentitle, $vl, $c, $in + 4, $sk) . PHP_EOL; } $r .= (empty($v) ? '],' : ($in != 0 ? str_repeat($c, $in / 2) : '') . (is_null($v) ? '' : str_repeat($c, $in / 2) . &quot;],&quot;)); } } else { $lenkey = $indents['key'] - mb_strlen(&quot;'$k'&quot;) - $in; if ($lenkey &lt; 0) { $lenkey = 0; } $eval = $this-&gt;EvaluateVariable($v); $lenval = $indents['val'] - (mb_strlen(&quot;'&quot; . $eval['val'] . &quot;'&quot;)); if ($lenval &lt; 0) { $lenval = 0; } $r .= ($in != -1 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : &quot;'$k'&quot; . str_repeat($c, $lenkey) . '=&gt; ') . $eval['val'] . str_repeat(&quot; &quot;, $lenval) . '// ' . $eval['desc']; } return $r; }; $varlentitle = mb_strlen('$' . $varname); if (in_array(gettype($var), array('object', 'array'))) { return '$' . $varname . str_repeat(&quot; &quot;, ($indents['key'] - $varlentitle)) . '= [' . str_repeat(&quot; &quot;, $indents['val'] - 2) . '// main array node' . rtrim($pretty($indents, $varlentitle, $var), ',') . ';'; } else { $eval = $this-&gt;EvaluateVariable($var); return '$' . $varname . str_repeat(&quot; &quot;, $indents['key']) . '=' . $eval['val'] . ';' . str_repeat(&quot; &quot;, $indents['val'] - 1) . '// ' . $eval['desc']; } } public function EvaluateVariable($var): array { if (null === $var || 'null' === $var || 'NULL' === $var) { if (is_string($var)) { return ['val' =&gt; &quot;'null'&quot;, 'desc' =&gt; 'null value string.']; } else { return ['val' =&gt; 'null', 'desc' =&gt; 'null value.']; } } if (is_array($var)) { return ['val' =&gt; &quot;&quot;, 'desc' =&gt; 'array node.']; } if (in_array($var, [&quot;true&quot;, &quot;false&quot;, true, false], true)) { if (is_string($var)) { return ['val' =&gt; &quot;'&quot; . $var . &quot;'&quot;, 'desc' =&gt; 'string value boolean ' . $var . '.']; } else { return ['val' =&gt; ($var ? 'true' : 'false'), 'desc' =&gt; 'boolean value ' . ($var ? 'true' : 'false') . '.']; } } ob_start(); var_dump($var); $string = ob_get_clean(); if (is_object($var)) { $string = explode('{', $string); return ['val' =&gt; '(object) ', 'desc' =&gt; rtrim($string[0]) . '.']; } unset($string); if ((int) $var == $var &amp;&amp; is_numeric($var)) { if (is_string($var)) { return ['val' =&gt; &quot;'&quot; . $var . &quot;'&quot;, 'desc' =&gt; '(' . mb_strlen($var) . ') integer value string.']; } else { return ['val' =&gt; $var, 'desc' =&gt; '(' . mb_strlen($var) . ') integer value.']; } } if ((float) $var == $var &amp;&amp; is_numeric($var)) { if (is_string($var)) { return ['val' =&gt; &quot;'&quot; . $var . &quot;'&quot;, 'desc' =&gt; '(' . mb_strlen($var) . ') float value string.']; } else { return ['val' =&gt; $var, 'desc' =&gt; '(' . mb_strlen($var) . ') float value.']; } } ob_start(); var_dump($var); $string = ob_get_clean(); if (mb_strpos($string, 'resource') !== false) { return ['val' =&gt; 'resource', 'desc' =&gt; rtrim($string) . '.']; } elseif (mb_strpos($string, 'of type ') !== false) { return ['val' =&gt; 'resource', 'desc' =&gt; rtrim($string) . '.']; } unset($string); if (mb_strpos($var, ' ') !== false &amp;&amp; mb_strpos($var, ':') !== false &amp;&amp; mb_strpos($var, '-') !== false) { $datetime = explode(&quot; &quot;, $var); $validate = 0; foreach ($datetime as $value) { if ($this-&gt;ValidateDate($value)) { $validate++; } } if ($validate &gt;= 2) { return ['val' =&gt; &quot;'&quot; . $var . &quot;'&quot;, 'desc' =&gt; '(' . mb_strlen($var) . ') string value datetime.']; } } if ($this-&gt;ValidateDate($var) &amp;&amp; mb_strpos($var, ':') !== false) { return ['val' =&gt; &quot;'&quot; . $var . &quot;'&quot;, 'desc' =&gt; '(' . mb_strlen($var) . ') string value time.']; } if ($this-&gt;ValidateDate($var) &amp;&amp; mb_strlen($var) &gt;= 8 &amp;&amp; mb_strpos($var, '-') !== false) { return ['val' =&gt; &quot;'&quot; . $var . &quot;'&quot;, 'desc' =&gt; '(' . mb_strlen($var) . ') string value date.']; } if ($this-&gt;ValidateDate($var) &amp;&amp; mb_strlen($var) &gt;= 8 &amp;&amp; mb_strpos($var, '-') !== false) { return ['val' =&gt; &quot;'&quot; . $var . &quot;'&quot;, 'desc' =&gt; '(' . mb_strlen($var) . ') string value date.']; } if (is_string($var)) { $arr = $this-&gt;StrSplitUnicode($var); $currencylist = [ '¤', '$', '¢', '£', '¥', '₣', '₤', '₧', '€', '₹', '₩', '₴', '₯', '₮', '₰', '₲', '₱', '₳', '₵', '₭', '₪', '₫', '₠', '₡', '₢', '₥', '₦', '₨', '₶', '₷', '₸', '₺', '₻', '₼', '₽', '₾', '₿' ]; $currencycheck = []; foreach ($arr as $char) { if (in_array($char, $currencylist, true)) { $currencycheck[] = $char; } } if (!empty($currencycheck)) { return [ 'val' =&gt; &quot;'&quot; . $var . &quot;'&quot;, 'desc' =&gt; 'string/amount value related to currency (' . implode(',', $currencycheck) . ').' ]; } } if (is_string($var)) { return ['val' =&gt; &quot;'&quot; . $var . &quot;'&quot;, 'desc' =&gt; 'string value of ' . mb_strlen($var) . ' character.']; } return ['val' =&gt; 'unknow', 'desc' =&gt; 'unknow']; } private function ValidateDate(string $date): bool { return (strtotime($date) !== false); } private function StrSplitUnicode(string $str, $length = 1): array { $tmp = preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY); if ($length &gt; 1) { $chunks = array_chunk($tmp, $length); foreach ($chunks as $i =&gt; $chunk) { $chunks[$i] = join('', (array) $chunk); } $tmp = $chunks; } return $tmp; } private function OutView(string $string) { echo $string; } } function IsCommandLineInterface(): bool { return (php_sapi_name() === 'cli'); } </code></pre> <h2>Example Usage</h2> <pre class="lang-php prettyprint-override"><code>&lt;?php use \IcarosNet\BOHBasicOutputHandler as Output; require __DIR__ . '\..\vendor\autoload.php'; /** * FooBar is an example class. */ class FooBar { function foo_function() { return &quot;Hello World!&quot;; } } $var_class = new FooBar; $example_single = 'Hello World'; $example_array = [//1 'null' =&gt; null, 'null_text' =&gt; 'null', 'integer' =&gt; 10, 'integer_text' =&gt; '10', 'float' =&gt; 20.35, 'float_text' =&gt; '20.35', 'string' =&gt; 'Hello World', 'date_1' =&gt; '2021-01-17', 'date_2' =&gt; '2021-Jan-17', 'hour_1' =&gt; '6:31:00 AM', 'hour_2' =&gt; '17:31:00', 'datetime_1' =&gt; '2021-01-17 17:31:00', 'datetime_2' =&gt; '2021-Jan-17 6:31:00 AM', 'datetime_3' =&gt; '2021-01-17 6:31:00 AM', 'datetime_4' =&gt; '2021-Jan-17 17:31:00', 'currency_1' =&gt; '1.45$', 'currency_2' =&gt; 'db£ 1.45 ₹', 'array' =&gt; [//2 'boolean_true' =&gt; true, 'boolean_false' =&gt; false, 'boolean_true_text' =&gt; 'true', 'boolean_false_text' =&gt; 'false', 'object' =&gt; (object) [//3 'key_index_most' =&gt; 'Hello Wolrd', 'joder' =&gt; [//4 'prueba' =&gt; 'prueba', ] ], 'nested' =&gt; [ // deep = 3 no cuenta ya existe 'other_obj' =&gt; (object) [ // deep = 4 no cuenta ya existe 'apple', 'banana', 'coconut', ], ], ], 'objects_list' =&gt; [ 'object_empty' =&gt; (object) [], 'class' =&gt; $var_class, 'resource' =&gt; curl_init(), ], ]; $output = new Output\OutputHandler(); $output-&gt;Theme('monokai'); $output-&gt;Output($example_array); // Other Examples: </code></pre> <h2>Example Output:</h2> <p>Please keep in mind that this output was captured in the browser, although it has a code format, this is one of the functionalities of the class. the format is not possible to replicate in SE sites, so I add the images.</p> <ul> <li><p><strong>default theme</strong> <a href="https://i.stack.imgur.com/d0fLi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d0fLi.jpg" alt="enter image description here" /></a></p> </li> <li><p><strong>monokai theme</strong> <a href="https://i.stack.imgur.com/QyGEM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QyGEM.jpg" alt="monokai theme" /></a></p> </li> <li><p><strong>natural-flow</strong> <a href="https://i.stack.imgur.com/Z2ltD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z2ltD.jpg" alt="enter image description here" /></a></p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T19:16:43.957", "Id": "506390", "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 should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://codereview.meta.stackexchange.com/a/1765)." } ]
[ { "body": "<h3>Standards</h3>\n<blockquote>\n<pre><code> private function AnalysisVariable(string $varname, $var, array $indents): string\n</code></pre>\n</blockquote>\n<p>So there are a couple problems here. In the text of your question, you refer to this as <code>AnalVariable</code>. That's a particularly bad name as anal is an English word that is somewhat off-color. Fortunately changed here.</p>\n<p><a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md\" rel=\"nofollow noreferrer\">PSR-1</a> says that method names should be camelCased. StudlyCaps are used for class names.</p>\n<p>In general, method names should be verbs. Analysis is a noun. The verb form is analyze.</p>\n<p>So this should be</p>\n<pre><code> private function analyzeVariable(string $varname, $var, array $indents): string\n</code></pre>\n<p>You might find that people would find this method more useful if it were accessible when the class was extended. I.e. if it were <code>protected</code> instead of <code>private</code>.</p>\n<h3>Efficiency</h3>\n<blockquote>\n<pre><code> ob_start();\n var_dump($var);\n $string = ob_get_clean();\n if (is_object($var)) {\n $string = explode('{', $string);\n return ['val' =&gt; '(object) ', 'desc' =&gt; rtrim($string[0]) . '.'];\n }\n unset($string);\n</code></pre>\n</blockquote>\n<p>This seems weird to me. If <code>$var</code> is not an object, you do an ob_start and ob_get_clean only to immediately throw away the result. Why not reorder to</p>\n<pre><code> if (is_object($var)) {\n ob_start();\n var_dump($var);\n return ['val' =&gt; '(object) ', 'desc' =&gt; rtrim(explode('{', ob_get_clean(), 2)[0]) . '.'];\n }\n</code></pre>\n<p>Now, there is no need to unset <code>$string</code>, as it is never created.</p>\n<p>If <code>$var</code> is not an object, we don't do the output buffering.</p>\n<p>I think that string is a bad name for an array. However, it's hard to see what it should be named in this case. Particularly as you are only using the first element from the array.</p>\n<p>I also only split on the first brace, rather than on every one that may be present in the string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T14:57:44.723", "Id": "506368", "Score": "0", "body": "reset only support variable passed by reference not expresions or function XD" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T15:00:11.790", "Id": "506369", "Score": "0", "body": "https://i.imgur.com/nG4IW6l.png" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T20:15:00.677", "Id": "506404", "Score": "1", "body": "This revised version will work, although it would probably be more readable to make an intermediate variable if you can come up with a reasonable name." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T09:34:27.423", "Id": "256461", "ParentId": "256388", "Score": "2" } }, { "body": "<h2>Initial feedback</h2>\n<p>This code looks okay, though has quite a bit of room for improvement - see this suggestions below. I like how the short array syntax is used in many places, as well as type hinting of parameters and return types for methods.</p>\n<p>Some methods are a bit lengthy and a bit of an eyesore - e.g. the method <code>EvaluateVariable</code>- its more than 100 lines of code! Consider breaking that up into smaller methods to reduce redundancy and allow for better testing. Speaking of which - do you have any <strong>unit tests</strong> or plan to make some? If I consider using a library I look to see if it has unit tests and whether they are passing.</p>\n<p>The method <code>AnalysisVariable()</code> is also very long. The function stored in <code>$pretty</code> does not need to be an anonymous function - it can be a method instead.</p>\n<p>If I was to use a library like this then I would prefer not to have to instantiate an object- even once. A singleton pattern could be used if instances are necessary but as a Laravel user who is familiar with the <a href=\"https://laravel.com/docs/8.x/logging#writing-log-messages\" rel=\"nofollow noreferrer\">illuminate logger methods</a> I like how most output methods are static so I don’t have to have an instance of a helper object in order to use them.</p>\n<h2>Bugs</h2>\n<h3>warning on call to <code>str_repeat()</code></h3>\n<p>I tried passing a simple array to the <code>Output</code> method:</p>\n<pre><code>$example_array = ['a' =&gt; 1, 'b'=&gt;2];
\n$output-&gt;Output($example_array);
\n</code></pre>\n<p>That yielded a warning before the output:</p>\n<blockquote>\n<p>Warning: str_repeat(): Second argument has to be greater than or equal to 0 in outputtest.php on line 360</p>\n</blockquote>\n<p>It appears you may have fixed this with the code in the repository, given that you updated the example code there to include this sample array.</p>\n<h3>CLI column width pattern match</h3>\n<p>I tried installing the library via Composer on my mac. No matter how wide I make my terminal it always shows the <code>Oops</code> message. Apparently <code>MODE 2&gt; null</code> yields nothing while <code>tput cols</code> yields a single integer - e.g. <code>176</code> so the regular expression starting with <code>CON.*:</code> won't match anything.</p>\n<h2>Suggestions</h2>\n<h3>Don’t repeat yourself</h3>\n<p>In the method <code>UpdateInitSetHighlightCli()</code> it appears that the only thing that changes in each line except the last is the key to set and the key to index - those could be put into an associative array to map keys and then use a <code>foreach</code> loop to set values accordingly.</p>\n<blockquote>\n<pre><code> $this-&gt;colorcli['comment'] = &quot;\\033[38;2;&quot; . $this-&gt;RGBforCLI($color[0]) . &quot;m%s\\033[0m&quot;;\n $this-&gt;colorcli['constant'] = &quot;\\033[38;2;&quot; . $this-&gt;RGBforCLI($color[4]) . &quot;m%s\\033[0m&quot;;\n// and so on\n</code></pre>\n</blockquote>\n<p>Could be simplified:</p>\n<pre><code>const CLI_KEY_COLOR = [\n 'comment' =&gt; 0,\n 'constant' =&gt; 4, \n // and do on \n];\n</code></pre>\n<p>then loop through those:</p>\n<pre><code>foreach (self::CLI_KEY_COLOR as $key =&gt; $colorIndex) {\n $this-&gt;colorcli[$key] = &quot;\\033[38;2;&quot; . $this-&gt;RGBforCLI($color[$colorIndex]) . &quot;m%s\\033[0m&quot;;\n}\n//the exception:\n$this-&gt;colorcli['background'] = &quot;\\033[48;2;&quot; . $this-&gt;RGBforCLI($color[5]) . &quot;m&quot;;\n</code></pre>\n<h3>Constants</h3>\n<p>Any data with a name in all caps - e.g. <code>$TOKENS</code> is a convention of a constant. For proper constant declaration, use <a href=\"https://www.php.net/manual/en/language.oop5.constants.php\" rel=\"nofollow noreferrer\">the <code>const</code> keyword</a> - which would make it not a variable.</p>\n<p>It might be wise to consider pulling the values used in the <code>Theme</code> method, as well as other data that doesn't get modified- like <code>$currencylist</code> - out into constants - e.g. for the colors and background colors. That way if any of those values needed to be updated, you wouldn't have to go down into the method, but rather at the constant definition. Also, it would allow for a different way to set those values - e.g. instead of using a <code>switch</code> statement, check if the value of <code>$theme</code> exists as a key in an array of values in a constant - if so, use the value at that index.</p>\n<p>You might also consider defining constants for strings like <code>wb</code> and <code>cli</code> to avoid mistakes caused by typos.</p>\n<p>I don’t see much point in defining <code>ENVIRONMENT_OUTPUT_HANDLER</code> since it only appears to be used in the constructor. The constructor could simply call the function to set the value accordingly.</p>\n<h3>PHP version check</h3>\n<blockquote>\n<pre><code>if (!version_compare(phpversion(), '7.4', '&gt;=')) {\n</code></pre>\n</blockquote>\n<p>Since the <a href=\"/questions/tagged/performance\" class=\"post-tag\" title=\"show questions tagged &#39;performance&#39;\" rel=\"tag\">performance</a> was added to the post, I can’t help but notice this line uses the functions to compare versions</p>\n<p>Instead of calling those two functions, use the <a href=\"https://www.php.net/manual/en/reserved.constants.php#reserved.constants.core\" rel=\"nofollow noreferrer\"><code>PHP_VERSION_*</code> constants</a> to reduce the number of function calls, though you might have to ensure those are defined first - if not then you’d know the version was likely prior to 5.2.7.</p>\n<h3>Method name convention</h3>\n<p>I know mdfst13 already mentioned this but I planned to mention it anyway.\nWhile it is not required, it is good to follow the <a href=\"https://www.php-fig.org/psr\" rel=\"nofollow noreferrer\">PSRs</a> for readability and maintainbility. <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1</a> recommends the following convention for method names:</p>\n<blockquote>\n<p>Method names MUST be declared in <code>camelCase</code>.</p>\n</blockquote>\n<h3>character replacement</h3>\n<p>In some cases <a href=\"https://www.reddit.com/r/PHP/comments/3qk44w/performance_of_strtr_vs_str_replace/\" rel=\"nofollow noreferrer\">using <code>strtr()</code> could be faster than <code>str_replace()</code></a> but you should test on the input your code normally uses to see what may be best- the differences may be negligible.</p>\n<h3>docblocks</h3>\n<p>I happened to see that <a href=\"https://codereview.stackexchange.com/posts/256388/revisions#rev-body-ca0bf884-4e15-4549-b284-b0dc660776b9\">you updated your code</a>, which needed to be rolled back since an answer had already been submitted and the code shouldn't be changed after that happens. In that revision you added dockblocks - I was intending to mention those. Good work adding those. You can post a follow-up question for the code that contains those.</p>\n<h3>Null coalescing operator</h3>\n<p>Since the code requires PHP version 7.4 or newer, the <a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op\" rel=\"nofollow noreferrer\">null coalescing operator</a> can be used. For example, instead of this line in the method <code>CheckEnv()</code>:</p>\n<blockquote>\n<pre><code>$env = ($env == null ? $this-&gt;defenv : $env);
$env = \n</code></pre>\n</blockquote>\n<p>Simplify it to this:</p>\n<pre><code>$env ?? $this-&gt;defenv;\n</code></pre>\n<h3><code>else</code> after <code>return</code></h3>\n<p>In that method <code>EvaluateVariable()</code> I see this (indentation decreased for the sake of readability):</p>\n<blockquote>\n<pre><code>if (null === $var || 'null' === $var || 'NULL' === $var) {\n if (is_string($var)) {\n return ['val' =&gt; &quot;'null'&quot;, 'desc' =&gt; 'null value string.'];\n } else {\n return ['val' =&gt; 'null', 'desc' =&gt; 'null value.'];\n }\n}\n</code></pre>\n</blockquote>\n<p>There is no need to have an <code>else</code> block when the previous block(s) contain a <code>return</code> statement.</p>\n<h3>Anonymous function in call to <code>array_map()</code></h3>\n<p>In the method <code>CoverforBackground()</code> (which is apparently renamed to <code>adjusterSpaceLine()</code>) there is this code:</p>\n<blockquote>\n<pre><code> $maxlen = max(array_map(function ($el) {\n return mb_strlen($el);\n }, $stringarr));\n</code></pre>\n</blockquote>\n<p>The extra anonymous function can be removed from the call to <code>array_map()</code> by passing the function name in a string literal:</p>\n<pre><code>$maxlen = max(array_map('mb_strlen', $stringarr));\n</code></pre>\n<p>If you still wanted an anonymous function there, then an <a href=\"https://www.php.net/manual/en/functions.arrow.php\" rel=\"nofollow noreferrer\">arrow function</a> could be used, given that PHP 7.4 is required for the code:</p>\n<pre><code>$maxlen = max(array_map(fn($el) =&gt; mb_strlen($el), $stringarr));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T21:13:24.750", "Id": "506405", "Score": "0", "body": "thank for your review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T21:52:50.317", "Id": "506406", "Score": "0", "body": "hello the bug you find is based on the code of this question or you have installed the lasted version with composer like the documentation say?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T21:54:39.307", "Id": "506407", "Score": "0", "body": "I don't know how to do unit tests yet, it's in my long-term plans." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T22:51:26.757", "Id": "506411", "Score": "0", "body": "i have 2 option a null estatemente value and a null statement like string value... becouse it i need else block, but i can minimifid it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T21:41:34.757", "Id": "506619", "Score": "0", "body": "\"_hello the bug you find is based on the code of this question or you have installed the lasted version with composer like the documentation say?_\" - yes its using the code above since that is what we are supposed to review here. I see you have updated the code in GH to handle the scenario so I have updated that part of my review, along with other sections." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T22:20:27.200", "Id": "506622", "Score": "1", "body": "Thank you I will continue to make new improvements throughout tonight. Regards." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T21:10:12.247", "Id": "256486", "ParentId": "256388", "Score": "1" } }, { "body": "<blockquote>\n<p>FYI - I'm a bit rusty with PHP and not a PHP expert in anyways.</p>\n</blockquote>\n<h1>TL;DR</h1>\n<ul>\n<li>Be strict on coding style and standard.</li>\n<li>Clean the class responsibility, implement (at least) Single Responsibility Principle.</li>\n<li>Make smaller functions.</li>\n<li>Write Unit test.</li>\n</ul>\n<hr />\n<h1>Retrospect</h1>\n<h3>Use Strict!</h3>\n<p>This generated a lot of errors that was not there before.</p>\n<pre><code>&lt;?php declare(strict_types=1);\n</code></pre>\n<h3>Access Specifiers</h3>\n<p>Private, Protected and Public are used, which is great to see but I think there has NOT been put a lot of thought for doing it.</p>\n<h3>Class</h3>\n<p>In general, class OutputHandler is too large, more than 400 lines.The standard rule would be maximum lines of a Class is around 100.</p>\n<p>It has too many functionalities which could be separated out in another class of just utility functions which can be called directly.</p>\n<p>Like IsCommandLineInterface() we can move other common usage functions to a separate file so that our class could be cleaner. Or if are moving with a pure Object Oriented approach then probably make another class.</p>\n<p>I think the best way would be to make separate classes for CLI and Web version. We can have a OutputHandler Abstract base class with some similary functionalities which can be extended by class CliOutputHandler and WebOutputHandler child classes to implement needed features dependently.</p>\n<p>Furthermore,I can see the validation process could be move out to a separate class just with the validation functionality.</p>\n<p>And some more classes are possible for other small utility purposes which could be used just as a function but as I have mentioned let go complete OO.</p>\n<h3>Constructor</h3>\n<p>We might want to do pass example array kind of input variable here and do the validation in the constructor. It would be a good practice.</p>\n<pre><code>public function __construct($theme = 'default')\n{\n $this-&gt;getTheme($theme);\n // This is variable is not used so remove. \n // $this-&gt;defenv = ENVIRONMENT_OUTPUT_HANDLER;\n}\n</code></pre>\n<h3>Function getTheme()</h3>\n<pre><code>public function getTheme(string $theme = 'default'): void\n{\n if (isset(self::THEMESLIST[$theme])) {\n $color = self::THEMESLIST[$theme];\n $this-&gt;themeused = $theme;\n \n } else {\n $color = self::THEMESLIST['default'];\n $this-&gt;themeused = 'default';\n }\n\n IsCommandLineInterface() ? \n $this-&gt;setHighlightThemeCli($color)\n : $this-&gt;setHighlightTheme($color);\n \n} \n</code></pre>\n<h3>Function output()</h3>\n<p>I can see the goodness of strongly type being implemented in few functions. What I would love to see is that, that standard being maintained in this function signature as well.</p>\n<p>Minor modification is done in the implementation.</p>\n<pre><code>public function output($var, $env = null, $retrieve = false)\n{\n \n $indents = $this-&gt;getIndent($var);\n $string = $this-&gt;analyzeVariable($var, $indents);\n\n if (IsCommandLineInterface() ) {\n $string = $this-&gt;highlightCodeCli($string);\n\n } else {\n $string = $this-&gt;highlightCode($string);\n }\n\n $string = $this-&gt;applyCss($string);\n $this-&gt;resetHighlight();\n\n return ($retrieve ? $string : $this-&gt;outView($string));\n}\n</code></pre>\n<h3>Function getIndent()</h3>\n<p>One of function I am not happy seeing as I am not able to understand what's the purpose of the function and the way it has been implemented.</p>\n<p>We are returning indents array with [key =&gt; value] but we are doing trying to find the length of the array and objects, this is not done using mb_strlen.</p>\n<pre><code>private function getIndent($data): array\n{\n $indents = ['key' =&gt; 0, 'val' =&gt; 0];\n\n if ( is_array($data) || is_object($data) ) {\n \n $data = is_object($data) ? (array) $data : $data;\n \n // This literally does not make any sense.\n // Why are we looping and assigning value to \n // the same variable $value? And the $value is \n // used in the local scope.\n // array_walk_recursive($data, function (&amp;$value) {\n // $value = is_object($value) ? (array) $value : $value;\n // });\n \n // THIS WILL GIVE ERROR!\n // var_dump($value);\n\n $deep = ($this-&gt;calcDeepArray($data) + 1) * 4;\n \n array_walk_recursive($data, function ($value, $key) use (&amp;$indents) {\n\n if (mb_strpos(strval($key), chr(0)) !== false) {\n $key = str_replace(chr(0), &quot;'::'&quot;, $key);\n $key = substr($key, 4);\n }\n \n // It does not make sense to use mb_strlen for\n // array and objects.\n if (!is_array($value) \n &amp;&amp; !is_object($value) \n &amp;&amp; !is_resource($value) \n &amp;&amp; !is_null($value)) {\n $indents['val'] = ($indents['val'] &gt;= mb_strlen(strval($value))) \n ? $indents['val'] : mb_strlen(strval($value));\n\n $indents['key'] = ( $indents['key'] &gt;= mb_strlen(strval($key)) ) \n ? $indents['key'] : mb_strlen(strval($key));\n }\n \n\n }, $indents);\n\n $indents['key'] += $deep;\n $indents['val'] += $deep / 2;\n\n } else {\n $indents = ['key' =&gt; mb_strlen('variable'), 'val' =&gt; mb_strlen($data)];\n }\n\n return $indents;\n}\n</code></pre>\n<h3>function analyzeVariable</h3>\n<p>This is a bit messy. Let try to remove the recursion and check it other simple way. I believe the purpose of the function is to validate the variables in the input. A good way to design a API is to stick to some form of input standards. I think that usage of JSON format would be good as it helps to validate the schema easily. Here is an example of JSON Schema validator:</p>\n<p><a href=\"https://github.com/opis/json-schema\" rel=\"nofollow noreferrer\">https://github.com/opis/json-schema</a></p>\n<p>But it is not mandatory to do it.</p>\n<p>protected function analyzeVariable($data, array $indents): string\n{\n$varname = 'variable';</p>\n<pre><code>// We are using anonymous function to do some \n// analysis but I believe there is a better \n// way to do it, even without the use of recursion!\n// I am not sure what are the validation criteria\n// as the function is too hard to understand what's\n// going on.\n$pretty = function ($indents, $varlentitle, $v = '', $c = &quot; &quot;, $in = 0, $k = null) use (&amp;$pretty) {\n $r = '';\n \n // Previously, checking of object and array was done\n // like this:\n // if ( is_array($data) || is_object($data) ) {\n // Why are we chaning the way we check?\n if (in_array(gettype($v), ['object', 'array'])) {\n \n if (!is_null($k)) {\n if (mb_strpos($k, chr(0)) !== false) {\n $k = str_replace(chr(0), &quot;'::'&quot;, $k);\n $k = substr($k, 4);\n }\n }\n $lenname = mb_strlen(&quot;'$k'&quot;);\n $lenkeys = $indents['key'] - $in - $lenname;\n\n if ($lenkeys &lt; 0) {\n $lenkeys = 0;\n }\n\n $eval = $this-&gt;evaluateVariable($v);\n\n $v = (array) $v;\n $lenkey = $indents['val'] - mb_strlen($eval['val']) + 1;\n \n if (empty($v)) {\n $r .= ($in != 0 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : &quot;'$k'&quot;\n . str_repeat($c, $lenkeys) . &quot;=&gt; &quot; . $eval['val'] . &quot;[],&quot;\n . str_repeat(&quot; &quot;, $lenkey - 6) . &quot;// &quot;\n . $eval['desc']) . (empty($v) ? '' : PHP_EOL);\n } else {\n $r .= ($in != 0 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : &quot;'$k'&quot;\n . str_repeat($c, $lenkeys) . &quot;=&gt; &quot; . $eval['val'] . &quot;[&quot;\n . str_repeat(&quot; &quot;, $lenkey - 4) . &quot;// &quot;\n . $eval['desc']) . (empty($v) ? '' : PHP_EOL);\n \n foreach ($v as $sk =&gt; $vl) {\n $r .= $pretty($indents, $varlentitle, $vl, $c, $in + 4, $sk) . PHP_EOL;\n }\n $r .= (empty($v) ? '],' : ($in != 0 ? str_repeat($c, $in / 2) : '') .\n (is_null($v) ? '' : str_repeat($c, $in / 2) . &quot;],&quot;));\n }\n\n } else {\n\n if (mb_strpos($k, chr(0)) !== false) {\n $k = str_replace(chr(0), &quot;&quot;, $k);\n }\n\n $lenkey = $indents['key'] - mb_strlen(&quot;'$k'&quot;) - $in;\n if ($lenkey &lt; 0) {\n $lenkey = 0;\n }\n $eval = $this-&gt;evaluateVariable($v);\n $lenval = $indents['val'] - (mb_strlen(&quot;'&quot; . $eval['val'] . &quot;'&quot;));\n\n if ($lenval &lt; 0) {\n $lenval = 0;\n }\n $r .= ($in != -1 ? str_repeat($c, $in) : '') . (is_null($k) ? '' : &quot;'$k'&quot;\n . str_repeat($c, $lenkey) . '=&gt; ') . $eval['val']\n . str_repeat(&quot; &quot;, $lenval) . '// ' . $eval['desc'];\n }\n\n return str_replace(&quot;\\0&quot;, &quot;&quot;, $r);\n};\n\n// DO WE EVEN RECACH HERE?\n// There is a return in the recursive function \n// and I'm not sure if we even reach down low.\n\n$varlentitle = mb_strlen('$' . $varname);\n\nif (in_array(gettype($data), ['object', 'array'])) {\n $string = '$' . $varname . str_repeat(&quot; &quot;, (($indents['key'] - $varlentitle) &gt;= 0 ? $indents['key'] - $varlentitle : 1)) . '= ['\n . str_repeat(&quot; &quot;, $indents['val'] - 2) . '// main array node.'\n . rtrim($pretty($indents, $varlentitle, $data), ',') . ';';\n} else {\n $eval = $this-&gt;evaluateVariable($data);\n $string = '$' . $varname . str_repeat(&quot; &quot;, $indents['key']) . '=' . $eval['val'] . ';'\n . str_repeat(&quot; &quot;, $indents['val'] - 1) . '// ' . $eval['desc'];\n}\n\nreturn $string;\n</code></pre>\n<p>}</p>\n<h3>Function evaluateVariable()</h3>\n<p>Well improvements can be here as well</p>\n<pre><code>if (is_object($var)) {\n // Is there any specific reason for it?\n // I am not able to figure out!\n ob_start();\n $string = explode('{', ob_get_clean());\n return ['val' =&gt; '(object) ', 'desc' =&gt; rtrim(reset($string)) . '.'];\n}\n\n// Im not sure why we need to do this?\n// What are we storing in buffer and \n// reusing? And we are returning so what\n// will be the purpose of doing this?\nob_start();\n$string = ob_get_clean();\nif (mb_strpos($string, 'resource') !== false) {\n return ['val' =&gt; 'resource', 'desc' =&gt; rtrim($string) . '.'];\n} elseif (mb_strpos($string, 'of type ') !== false) {\n return ['val' =&gt; 'resource', 'desc' =&gt; rtrim($string) . '.'];\n}\nunset($string);\n \n</code></pre>\n<hr />\n<h1>Conclusion</h1>\n<p>Well those were some things I could see but that is just my perception. There is a lot of room for improvement and I can see there are good signs that your are trying to do that, which is a promising sign :).</p>\n<p>The first thing I would recommend I go through Clean Code, SOLID Principles, and Write Unit Test. PSR has already been mentioned so it would be good to follow them as well.</p>\n<p>As I read from one of your replies that is in your future plan, I would say amend that plan immediately as writing test will help you become a good software engineer and a better programmer! And writing test is not that hard, at all!</p>\n<p>Here is a brief article on Unit Test : <a href=\"https://codeanit.medium.com/developers-guide-write-good-test-5e3e3cdec78e\" rel=\"nofollow noreferrer\">https://codeanit.medium.com/developers-guide-write-good-test-5e3e3cdec78e</a></p>\n<p>To further improve the quality of your code you can use Static Analysis Tools, an example: <a href=\"https://github.com/squizlabs/PHP_CodeSniffer\" rel=\"nofollow noreferrer\">https://github.com/squizlabs/PHP_CodeSniffer</a></p>\n<p>And one last thing I would like to add more is practice data structure and algorithm usage in PHP. Use tools like HackerRank, Codility, etc.. to practice problem solving and code challenges which will definitely make you better. As from the hard review of the code, I definitely can also see a well structural implemented system.</p>\n<p>I wish you all the very best!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T18:25:12.003", "Id": "506593", "Score": "0", "body": "Hello friend, thanks for your feedback; This question was already verified and resolved at the time. but currently there is another open reward candidate publication based on the latest update, which includes documentation on each objective of each function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T18:25:20.497", "Id": "506594", "Score": "0", "body": "New POST: https://codereview.stackexchange.com/questions/256491/class-showing-a-format-similar-to-var-dump-v1-0-5" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T18:25:34.410", "Id": "506595", "Score": "0", "body": "Github repository with all the documentation to test: https://github.com/arcanisgk/BOH-Basic-Output-Handler" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T18:26:25.497", "Id": "506596", "Score": "0", "body": "in the same way I have taken note of everything indicated for version v1.0.6, thank you very much" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T18:29:25.627", "Id": "506597", "Score": "0", "body": ":) Well I have copy pasted the answer to your current post. I hope it helps!\nAnd I literally cannot see Unit Test in the repository." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T18:31:29.187", "Id": "506598", "Score": "0", "body": "It has not that I have not done it but there are other updates that I implement. of the suggestions mentioned above in other answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T18:33:10.523", "Id": "506599", "Score": "0", "body": "That's Ok @FranciscoNúñez :) I was just looking for test anyways. I hope the review is of some value to you and helps to improve your current implementation. Take care." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-02T22:25:23.017", "Id": "506721", "Score": "0", "body": "at the momento i not have a Mac OS to test de CLI count..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-03T04:12:17.170", "Id": "506741", "Score": "1", "body": "Linux/Windows/Mac, It does not matter which platform you are in @FranciscoNúñez! If you seriously interested to improve yourself as a developer you will find a way to write test anyways. And it's easy to run from CLI - php file.php. Also I recommend you to use a debugger.\nI know it sounds a lot at first but anyone who is seriously looking to make a good career, she/he will have to learn to do the hard stuffs.\nAnyways, again I wish all the very best!" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T17:57:58.120", "Id": "256581", "ParentId": "256388", "Score": "0" } } ]
{ "AcceptedAnswerId": "256461", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T19:12:07.837", "Id": "256388", "Score": "5", "Tags": [ "performance", "php", "object-oriented", "security", "logging" ], "Title": "Class showing a format similar to var_dump RC5 Version" }
256388
<p>I'm working on an app to compare SDKS (their churn and acquisiton rates). I have created an API with two separate endpoints.</p> <p>The first, compares one sdk to ther other and spits out that data for each sdk.</p> <p>The second, simply gets general information about a single sdk.</p> <p>I'm merging these objects into one, so that all information regarding a single SDK can be found.</p> <p>Problems I previously had, and might still come up (hopefully fixed by now): When setting the object at the end with <code>setAllSdksInfo(objCopy)</code> there was a problem in which it would not set it ok.</p> <p>I'm also getting an ESLint warning which states <code>&quot;Function declared in a loop contains unsafe references to variable(s) 'objCopy', 'objCopy', 'objCopy', 'objCopy', 'objCopy', 'objCopy', 'objCopy'&quot;</code> but that doesn't seem to be causing any problems.</p> <pre><code>import React, { useEffect } from &quot;react&quot;; import MatrixSquare from &quot;./MatrixSquare&quot;; function Matrix({ selectedSdks, allSdksInfo, setAllSdksInfo, showMatrix, setShowMatrix }) { useEffect(() =&gt; { (async () =&gt; { const selectedSdksKeys = Object.keys(selectedSdks); if (!selectedSdksKeys.length) return; setShowMatrix(false); let comparedCount = 0; const notComparedKeys = []; selectedSdksKeys.forEach((key, i) =&gt; { for (let j = i + 1; j &lt; selectedSdksKeys.length; j++) { if ( allSdksInfo?.[key]?.[&quot;churned_to&quot;]?.hasOwnProperty( selectedSdksKeys[j])) { comparedCount += 1; if (comparedCount === 3) { setShowMatrix(true); } } else { notComparedKeys.push([key, selectedSdksKeys[j]]); } } }); let objCopy = Object.assign({}, allSdksInfo); for (let i = 0; i &lt; notComparedKeys.length; i++) { await fetch( `/api/sdk/churn?sdk1_id=${notComparedKeys[i][0]}&amp;sdk2_id=${notComparedKeys[i][1]}`) .then((res) =&gt; res.json()) .then((res) =&gt; { const copyPreviousObj = Object.assign({}, objCopy); objCopy = { ...objCopy, ...res }; const resKeys = Object.keys(res); resKeys.forEach((key) =&gt; { const new_churned_to = objCopy[key][&quot;churned_to&quot;]; const new_acquired_from = objCopy[key][&quot;acquired_from&quot;]; if (copyPreviousObj[key]) { objCopy[key][&quot;churned_to&quot;] = { ...new_churned_to, ...copyPreviousObj[key][&quot;churned_to&quot;], }; objCopy[key][&quot;acquired_from&quot;] = { ...new_acquired_from, ...copyPreviousObj[key][&quot;acquired_from&quot;], }; } }); }); } selectedSdksKeys.forEach(async (id, i) =&gt; { if (allSdksInfo[id]?.[&quot;num_installed_apps&quot;]) return; const res = await fetch(`/api/sdk/general_info?sdk_id=${id}`); const data = await res.json(); objCopy[id][&quot;num_installed_apps&quot;] = data[&quot;num_installed_apps&quot;]; objCopy[id][&quot;acquired_total&quot;] = data[&quot;acquired_total&quot;]; objCopy[id][&quot;churned_total&quot;] = data[&quot;churned_total&quot;]; }); setAllSdksInfo(objCopy); setShowMatrix(true); })(); }, [selectedSdks]); </code></pre>
[]
[ { "body": "<p>I beleive the issue with</p>\n<blockquote>\n<p>When setting the object at the end with setAllSdksInfo(objCopy) there\nwas a problem in which it would not set it ok.</p>\n</blockquote>\n<p>Is because <code>Object.assign</code> is not doing what you're expecting it to do, <a href=\"https://medium.com/technofunnel/deep-and-shallow-copy-in-javascript-110f395330c5#:%7E:text=2.-,Object.,copy%20prototype%20properties%20and%20methods.&amp;text=This%20method%20does%20not%20create,of%20creating%20a%20separate%20object.\" rel=\"nofollow noreferrer\">it <strong>does not</strong> create a deep copy of the source object</a></p>\n<p><em><strong>TLDR;</strong></em></p>\n<p>When you modify a nested property of the copied object, it will affect the original one, one way of creating a deep copy of the object is <code>JSON.parse(JSON.stringify(obj))</code> :</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const obj_original = {\n a: {\n b: {\n c: 'hello'\n }\n }\n}\n\nconst obj_copy = Object.assign({}, obj_original);\n\nconst deep_copy = JSON.parse(JSON.stringify(obj_original));\n\nobj_original.a.b.c = 'test';\n\nconsole.log(obj_original); // { a: { b: { c: 'test' } } } \nconsole.log(obj_copy); // { a: { b: { c: 'test' } } }\nconsole.log(deep_copy); // { a: { b: { c: 'hello' } } }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><a href=\"https://medium.com/jl-codes/dry-vs-wet-code-589c564aa5aa\" rel=\"nofollow noreferrer\">Keep it DRY :</a></p>\n<p>instead of <code>objCopy[id][&quot;churned_total&quot;] = data[&quot;churned_total&quot;];</code> you could use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assignment</a> to avoid repeating :</p>\n<pre><code>selectedSdksKeys.forEach(async (id, i) =&gt; {\n if (allSdksInfo[id]?.num_installed_apps) return;\n\n const res = await fetch(`/api/sdk/general_info?sdk_id=${id}`);\n\n const { num_installed_apps, acquired_total, churned_total } = await res.json();;\n\n objCopy[id] = {\n ...objCopy[id],\n num_installed_apps, \n acquired_total, \n churned_total\n }\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-20T22:53:26.520", "Id": "257458", "ParentId": "256389", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T19:14:49.660", "Id": "256389", "Score": "0", "Tags": [ "api", "react.js", "jsx" ], "Title": "Merge into an object from two different API calls" }
256389
<p>I would like to know if my registration system is secure. I'm not sure if it is secure, as I'm new in development, and I'm afraid that the system is flawed</p> <p>Also, I'm not experienced in object oriented programming, I would like to know if my script looks a bit like OOP or is simply a set of procedural programming with object oriented</p> <p><strong>database.php</strong></p> <pre><code>&lt;?php /** * Class responsible for connecting to the database * It will be inherited by the SignUp class */ class DatabaseConnection { public function __construct(string $host, string $dbname, string $username, string $password) { try{ $this-&gt;database = new PDO(&quot;mysql:host=$host;dbname=$dbname;charset=utf8mb4&quot;, $username, $password); }catch(PDOException $e){ throw new Exception($e-&gt;getMessage()); } } } </code></pre> <p><strong>registration.php</strong></p> <pre><code>&lt;?php /** * This is a registration script * @author Anne Batch * @copyright 2021 */ declare(strict_types = 1); class SignUp extends DatabaseConnection { /** * Database Connection * @var PDO */ private $database; /** * @var string */ private $name; /** * @var string */ private $email; /** * @var string */ private $passwordHash; /** * @var string */ private $signUpPage; /** * @param string $name Assign the username */ public function setName(string $name) { $this-&gt;name = $name; } /** * @param string $email Assign the email */ public function setEmail(string $email) { $this-&gt;email = $email; } /** * @param string $password &amp; $confirm Assign password and password confirmation */ public function setPassword(string $password, string $confirm) { if ($password === $confirm) { $options = [ 'cost' =&gt; 12, ]; $this-&gt;passwordHash = password_hash($password, PASSWORD_BCRYPT, $options); } else { $this-&gt;returnWithError('&lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;Passwords does not match!&lt;/div&gt;'); } } /** * @param $signUpPage Redirect Page */ public function signUpPage(string $signUpPage) { $this-&gt;signUpPage = $signUpPage; } /** * @param $errorMessage Notification Message */ private function returnWithError(string $errorMessage) { $_SESSION['error'] = $errorMessage; header('Location: ' . $this-&gt;signUpPage); exit(); } /** * Checks whether a name exists */ public function existingName(): void { $statement = $this-&gt;database-&gt;prepare(&quot;SELECT 1 FROM users WHERE username = :username&quot;); $statement-&gt;execute([ &quot;:username&quot; =&gt; $this-&gt;name ]); $exists = $statement-&gt;fetchColumn(); if(!$exists) { $this-&gt;returnWithError('&lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;Name already exists!&lt;/div&gt;'); } } /** * Checks whether an email exists */ public function existingEmail(): void { $statement = $this-&gt;database-&gt;prepare(&quot;SELECT email FROM users WHERE email = :email&quot;); $statement-&gt;execute([ &quot;:email&quot; =&gt; $this-&gt;email ]); $result = $statement-&gt;rowCount(); if($result != 0) { $this-&gt;returnWithError('&lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;Email already exists!&lt;/div&gt;'); } } /** * Checks if the fields have been filled */ public function isDefinedFields(): void { if(!$this-&gt;name || !$this-&gt;email) { $this-&gt;returnWithError('&lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;Please, fill out all the fields!&lt;/div&gt;'); } } /** * Checks if the username is less than 3 or greater than 50 */ public function ValidateNameLength(): void { if(mb_strlen($this-&gt;name) &lt; 3) { $this-&gt;returnWithError('&lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;Can only use 3 or more characters as name!&lt;/div&gt;'); } if(mb_strlen($this-&gt;name) &gt; 50) { $this-&gt;returnWithError('&lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;Can only use a maximum of 50 characters as name!&lt;/div&gt;'); } } /** * Checks if the email is semantically correct */ public function ValidateEmail(): void { if(!filter_input(INPUT_POST, $this-&gt;email, FILTER_VALIDATE_EMAIL)) { $this-&gt;returnWithError('&lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;Incorrect email!&lt;/div&gt;'); } } /** * Checks if the username matches the regular expression * The purpose of regular expression is to prevent JavaScript attacks * The user will not be able to use certain characters, such as &lt;&gt; \/ */ public function addUser(): void { if(preg_match(&quot;/^[\w&amp;.\-]*$/&quot;, $this-&gt;name)) { $statement = $this-&gt;database-&gt;prepare(&quot;INSERT INTO users VALUES(?, ?, ?, ?, ?, ?, ?)&quot;); $statement-&gt;execute([ $this-&gt;name, $this-&gt;email, $this-&gt;passwordHash, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_CLIENT_IP'], $_SERVER['HTTP_X_FORWARDED_FOR'], $_SERVER['HTTP_USER_AGENT'] ]); if($statement) { $this-&gt;returnWithError('&lt;div class=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;Registered successfully!&lt;br&gt;Login now&lt;/div&gt;'); } } else { $this-&gt;returnWithError('&lt;div class=&quot;alert alert-danger&quot; role=&quot;alert&quot;&gt;Can only use letters and numbers as name!&lt;/div&gt;'); } } } </code></pre> <p><strong>main.php</strong></p> <pre><code>&lt;?php session_start(); require_once('database.php'); require_once('registration.php'); $users = new SignUp('localhost', 'database', 'root', 'password'); $users-&gt;setName($_POST['username']); $users-&gt;setEmail($_POST['email']); $users-&gt;signUpPage('signup'); $users-&gt;setPassword($_POST['password'], $_POST['password2']); $users-&gt;existingName(); $users-&gt;existingEmail(); $users-&gt;isDefinedFields(); $users-&gt;ValidateNameLength(); $users-&gt;ValidateEmail(); $users-&gt;addUser(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T21:40:57.603", "Id": "506178", "Score": "2", "body": "You question has gained a close vote for \"missing review context\", which doesn't make much sense since you've posted what looks like some pretty complete code. Please can you add a short description on what the code does, otherwise your question looks fine to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T22:28:14.937", "Id": "506180", "Score": "3", "body": "The code looks really solid to me. Up to now, the worst mistake I found is the simple typo \"Passwords _does_ not match\", which should be \"Passwords _do_ not match\". If there is nothing else, this can only mean that I'm too tired right now. I'll try again tomorrow. For someone \"new in development\" and \"not experienced\", the code definitely contains too few mistakes. ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T00:24:41.393", "Id": "506182", "Score": "0", "body": "@RolandIllig If you can check again, I'll be happier than I already am. Thanks for your feedback!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T10:34:46.583", "Id": "506270", "Score": "0", "body": "You've gone through the trouble of creating `setter` methods so I'm interested: what's the logic behind **not** incorporating the validation in those methods?" } ]
[ { "body": "<p>First of all, your code looks rock-solid, obvious in what it does and very clean. This is not something that I would expect from someone &quot;new in development&quot;. Whoever you learned all this from, you should keep them.</p>\n<p>You got all of the major topics of a login system right:</p>\n<ul>\n<li>Your code uses parameterized statements for all database access, to protect against SQL injections.</li>\n<li>Your code saves passwords only in their hashed form, to protect against data breaches.</li>\n<li>You use a decent password hashing algorithm. Good that PHP provides a sane default here and makes it easy to use. Throughout its long history, PHP had not always made it easy to write correct and secure code. For password hashing it succeeded to provide a good API, and you use it perfectly as well.</li>\n<li>You use the full available character set from Unicode by connecting to the MySQL database using the <code>utf8mb4</code> encoding. This allows emojis in user names to be saved correctly.</li>\n<li>All HTML that is printed carefully avoids to reflect any user-provided data. This prevents cross-site scripting.</li>\n</ul>\n<p>Next, I'm looking at the details of the code, from top to bottom, see if there are any unnecessary stylistic variations.</p>\n<h3>database.php</h3>\n<p>For me, the comment on the <code>DatabaseConnection</code> is redundant. The name of the class already expresses clearly that the DatabaseConnection connects to the database. Therefore I would not need that comment. Since you are still new in development, it's perfectly fine to keep that comment until you (and whoever else works on your project) don't need it anymore because it's obvious.</p>\n<p>Same for the <code>will be inherited</code> part in the comment. My IDE lets me quickly see the type hierarchy of classes, which makes this comment redundant as well. Plus, <code>will be</code> refers to the future and is probably outdated by now.</p>\n<p>The constructor of <code>DatabaseConnection</code> initializes the field <code>$this-&gt;database</code>, but when looking at the class <code>DatabaseConnection</code> alone, that field is not used anywhere. This feels strange at first. I'm somehow missing the <code>private $database</code> declaration, like you wrote it in the class <code>SignUp</code>.</p>\n<p>Still in the constructor of <code>DatabaseConnection</code>, you wrote <code>try{</code> without a space in between. It is more common to write <code>try {</code> with a space in between, just like there is a space after <code>if</code> and <code>catch</code>. If you are using an IDE, it has a command to &quot;format the source code&quot;, so you don't have to do that yourself. There are many different styles of formatting the code, it doesn't matter which one you choose. Just choose one that you like and apply it <em>consistently</em> to all of the code.</p>\n<p>Still in the constructor of <code>DatabaseConnection</code>, when I first saw the code, I didn't see a reason for the <code>try catch</code> block at all. If you remove that block and only keep the single line <code>$this-&gt;database = ...</code> instead, the original stack trace will be preserved, including all information about the actual cause of the exception. By wrapping the <code>PDOException</code> in a plain <code>Exception</code> and only copying the message, you give away this context information. So far for my first impression.</p>\n<p>The original stack trace contains a lot of information that is useful for tracking down errors. However, it also contains the database credentials, and these must not end up in the log files of the server. Therefore stripping the exception from all unnecessary information is essential in this case. To alert future readers of the code, I would add a comment explaining this in a single line, or just referring to a Stack Overflow answer with all the details.</p>\n<h3>registration.php</h3>\n<p>The comment <code>This is a registration script</code> is redundant. Keeping the author information is good if you plan on passing the project to someone else later, so that they have someone to contact. Whether or not the <code>copyright 2021</code> is necessary or helpful is something I cannot decide for you.</p>\n<p>Declaring <code>strict_types=1</code> is good style, you should add it to <code>database.php</code> as well.</p>\n<p>The class <code>SignUp</code> has no comment above it. This leaves a reader a bit unclear about what a <code>SignUp</code> really is. It might be &quot;all data that is collected on the sign-up page&quot;, or it might be &quot;the data that is actually required to perform a sign-up operation&quot;. The difference between these two is that the former would include the password confirmation field, but the latter would not.</p>\n<p>You declare <code>SignUp extends DatabaseConnection</code>, which sounds strange. It's not that &quot;every sign-up is a specialized database connection&quot;, but that's what the keyword <code>extends</code> usually means. Instead, it's more likely that the class <code>SignUpPage</code> would <em>use</em> a database connection. Therefore I would drop the <code>extends DatabaseConnection</code> from the class <code>SignUp</code>.</p>\n<p>It's a nice trick that by declaring <code>private $database</code> in the class <code>SignUp</code>, you make that previously undeclared field of the class <code>DatabaseConnection</code> visible. Having tricks like these in the code may be confusing for readers, or they may even expect them. Instead of this trick, I would rather declare a field <code>private $database</code> of type <code>DatabaseConnection</code> and initialize this field in the constructor.</p>\n<p>I like the field name <code>$passwordHash</code> since it makes it obvious that the password is never stored in its plain text form. I hope that you use that field in exactly this way, I haven't looked at the actual code yet. But even if at some place there were some code that read <code>$passwordHash = $_POST['password']</code>, this would immediately alert any careful reader that something is wrong here, which is a good second-line defense.</p>\n<p>I'm not sure what the purpose of the field <code>$signUpPage</code> is. It could be a complete URL like <code>https://localhost:3000/signup</code>, it could be the HTML that makes up the sign-up page, or it could be the simple word <code>signup</code>, as in your code. A more precise name would be <code>$relativeSignUpPageUrl</code>, but that name is rather long, so it's understandable you chose a shorter name. In that case it might help the reader to add a small comment describing an example value for the variable. From this example value it is usually simple enough to infer all allowed values.</p>\n<p>The function <code>setName</code> has the comment <code>Assign the username</code>. First, when I let my IDE render that comment, it looks like this:</p>\n<p><a href=\"https://i.stack.imgur.com/02r2M.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/02r2M.png\" alt=\"Screenshot of rendered comment\" /></a></p>\n<p>The word <code>Assign</code> is listed in the section of the parameter <code>$name</code> while it really describes the function, not the parameter. The comment should rather be:</p>\n<pre class=\"lang-php prettyprint-override\"><code> /**\n * Assign the username\n * @param string $name\n */\n</code></pre>\n<p>If you were to rename the function to <code>setUsername</code>, each word of the comment would be redundant, allowing you to leave out the comment completely.</p>\n<p>In the function <code>setPassword</code>, the comment contains the words <code>&amp; $confirm</code>. The <code>&amp;</code> should be written as <code>&amp;amp;</code> since the comments contain HTML, just like <a href=\"https://www.oracle.com/de/technical-resources/articles/java/javadoc-tool.html\" rel=\"nofollow noreferrer\">Javadoc</a> (different programming language, same idea). When you search for <code>@param</code> in that document, you will find in match 16/36 that each parameter has a <code>@param</code> of its own. It's the same for PHP.</p>\n<p>In the comment for <code>signUpPage</code>, I don't see a need to write <code>Page</code> with a capital P. Same for <code>returnWithError</code>.</p>\n<p>The comment for <code>existingName</code> says &quot;Checks whether a name exists&quot;. The return type is <code>void</code>, which is unexpected to me. I would have expected <code>bool</code> here since that's the correct type for &quot;whether&quot;. Instead, the function exits if the name does not exist. Therefore I would rename that function to <code>checkNameExists</code>. Function names starting with <code>check</code> usually behave this way, throwing either an exception on failure or exiting plainly.</p>\n<p>In the function <code>ValidateNameLength</code> you started the name with a capital <code>V</code>, that is unusual. The other function names start with a lowercase letter.</p>\n<p>In <code>ValidateNameLength</code> you check the length of the name using <code>mb_strlen</code>. This is very careful, many other programmers would have used the wrong <code>strlen</code> instead.</p>\n<p>In <code>addUser</code>, you use a <code>\\w</code> in the regular expression. The <a href=\"https://www.php.net/manual/en/regexp.reference.escape.php\" rel=\"nofollow noreferrer\">documentation for the \\w</a> was a bit hard to find since it is not directly referenced in the documentation of <code>preg_match</code>, but anyways. The <code>\\w</code> includes all &quot;word&quot; characters, even outside <code>[A-Za-z]</code>. This may include Cyrillic, Hangul and several other alphabets. If you want to avoid usernames that look equal but are not (the Latin <code>a</code> and the Cyrillic <code>а</code>), you should rather restrict the allowed characters to <code>[A-Za-z]</code> first. You can always extend the character set later, restricting it is more work since it might affect existing usernames.</p>\n<p>Still in <code>addUser</code>, the SQL statement currently depends on the order of the column names in the database. If the order of the columns should change in the future, your code will put the data in the wrong columns. To prevent this, you can list the column names explicitly, as in <code>INSERT INTO users(name, email, password_hash, remote_addr, client_ip, forwarded_for, user_agent)</code>. This change, of course, will make your code dependent on the <em>names</em> of the columns instead of their position. Choose either way, I'm not sure which change is more likely to happen.</p>\n<h3>main.php</h3>\n<p>The call to <code>new SignUp</code> with the database connection parameters looks strange. This is because a <code>Page</code> object should not need to know these connection parameters as individual values, it should rather only have a single parameter of type <code>DatabaseConnection</code>. Assume that the database connection needs more more parameter, for whatever reason. Then you would have to adjust the call to <code>new SignUp</code>, and that feels wrong because a page should be independent from this low-level change.</p>\n<h3>Summary</h3>\n<p>Even after these many detailed remarks, the code still looks very solid to me. The remarks can be fixed easily, and the overall structure of the code is very nice and easy to understand. Very well done.</p>\n<p>And to answer your initial main question: Yes, your code is secure. All user-generated data is only used in safe ways, without allowing any injection attacks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T15:28:14.227", "Id": "506284", "Score": "3", "body": "If they remove the try block and only keep the single line $this->database = ... instead, the original stack trace will be preserved, including all information about the actual cause of the exception *including database credentials*, which feels at least awkward and some argue being a security breach to have database credentials revealed if not to the client but even in the sever logs anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T18:04:26.427", "Id": "506293", "Score": "0", "body": "@Roland Illig Thank you so much for your answer. Clear and objective answer, thanks for the tips" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T00:53:48.793", "Id": "506323", "Score": "0", "body": "@YourCommonSense Thank you for that explanation, I incorporated it into my answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T14:22:39.547", "Id": "256440", "ParentId": "256391", "Score": "4" } }, { "body": "<p>This code is rather good if you look at each separate line, but rather bad from the organizational standpoint.</p>\n<p>Each separate code snippet is indeed nearly flawless but it's the way they are glued together is wrong. <code>SignUp</code> is, so to say, a &quot;Diety Object&quot; as it's not as omniscient as a <a href=\"https://en.wikipedia.org/wiki/God_object\" rel=\"nofollow noreferrer\">God Object</a>, but definitely it does <strong>way too much</strong>:</p>\n<ul>\n<li>connects to a database</li>\n<li>validates input</li>\n<li>directly interacts with a database</li>\n<li>directly interacts with HTTP client</li>\n<li>it formats the output</li>\n</ul>\n<p>All these tasks <strong>must</strong> be delegated to separate classes or even components.</p>\n<p>You need to learn about separation of concerns and some basic MVC. Some pointers to get it right:</p>\n<ul>\n<li>a signup process is not a database connection. You never extend the former from the latter, just like you never extend a Human class from a Potato class in order to make a Human to eat a Potato. Besides, what if your page will require some other database interaction and use another class extended from database connection? It will create two database connections. And another class and so on. Which will eventually lead to the infamous &quot;Too many connections&quot; error. A connection has to be made only <strong>once</strong> and then passed to all classes as a constructor <strong>parameter</strong></li>\n<li>although the signup class can validate the data itself, most of the validation methods must be moved into a separate class for the code reuse. Also, it makes a little sense to call separate methods for validation. It will take less writing and lead to less errors if all validations would be performed in the <code>set</code> methods. <em>Just like <code>setPassword()</code> for some reason does not following the other methods' example.</em></li>\n<li>either way, the validation code should <strong>never format the HTML output</strong>. It is not only makes a <em>designer</em> to dig into your PHP code to change one class to another but also a severe case of a code repetition. Imagine you'd like to add some fancy icon to your flash messages. Going to go though all the PHP code changing it in hundreds lines, seriously?</li>\n<li>neither should it otherwise interact with a client. the validation code should <strong>only return a user interactions error</strong> while it should be conveyed to a user by some other mechanism</li>\n<li>the actual insert query can be made into a separate class but can be kept in this one. Either way, <strong>it must be fed with all the data required</strong>, not trying to get some data magically from a superglobal array. Remember that at some point you'd want to register users from a command line utility where no variable like <code>['HTTP_CLIENT_IP']</code> will ever be present</li>\n<li>I am sure you already can feel uneasiness when calling <code>signUpPage</code> method which is absolutely alien to all the other code. There must be <strong>another class responsible for the HTTP interaction</strong> to which this method would belong</li>\n<li>all the output must be formatted in a completely different component called &quot;View&quot;. It should have predefined templates for this kind of flash messages and the job of the HTTP component is just to define the message type and text</li>\n</ul>\n<p>I would strongly suggest to look at some established PHP frameworks, namely Symfony or Laravel, in order to see how the prosess is done and how the matters are usually get separated from each other.</p>\n<p>The refactored version could be like this</p>\n<pre><code>&lt;?php\n\nsession_start();\n\nrequire_once 'autoload.php';\n\n$http = new HTTPTransport();\n$validator = new Validator();\n$database = new DatabaseConnection('localhost', 'database', 'root', 'password');\n$user = new SignUp($database, $validator);\n\ntry {\n $user-&gt;setName($_POST['username']);\n $user-&gt;setEmail($_POST['email']);\n $user-&gt;setPassword($_POST['password'], $_POST['password2']);\n $user-&gt;setUserAgent($_SERVER['HTTP_USER_AGENT']);\n // same for the IP address and related HTTP headers\n} catch (SignUpValidationError $e) {\n $http-&gt;setFlashMessage('error', $e-&gt;getMessage());\n $http-&gt;redirect('signup');\n}\n$user-&gt;addUser();\n$http-&gt;setFlashMessage('success', 'Registered successfully!');\n$http-&gt;redirect('login');\n</code></pre>\n<p>which implies that your set methods validate the data like this</p>\n<pre><code>public function setEmail(string $email)\n{\n if (!$this-&gt;validator-&gt;validateEmail($email)) {\n throw new SignUpValidationError('Incorrect email');\n }\n if ($this-&gt;findUserByEmail($email)) {\n throw new SignUpValidationError('Email already exists');\n }\n $this-&gt;email = $email;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T18:04:48.040", "Id": "506294", "Score": "0", "body": "Thank you so much, it looks perfect. The only thing I didn't understand was block catch, my IDE(VS Code) reports: `Undefined type 'SignUpValidationError'.intelephense`. What, after all, is `SignUpValidationError`, judging by the **setEmail** method, seems to be a method? I created a method with that name in the `Validator` class and the error continues" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T18:19:56.813", "Id": "506295", "Score": "2", "body": "SignUpValidationError is a *class*. That's how exceptions work. You can define your own exceptions https://www.php.net/manual/en/language.exceptions.extending.php with the purpose of making catch to catch only a certain kind of exception" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-02T15:38:37.967", "Id": "506676", "Score": "0", "body": "I'm stuck with the methods that validate the data. What is within those methods that you reference? You throw an exception, but I can't understand it, I don't know if I should do something like `if (condition) { // check if email exists and do nothing because we'll use exception}`. Please help me, I can't understand" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-02T15:43:58.190", "Id": "506679", "Score": "0", "body": "@AnneBatch validateEmail is simply one line `return filter_var($email, FILTER_VALIDATE_EMAIL);` but I don't really understand your question. Can you post your code [here](https://phpize.online/) so I can test it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-02T15:55:45.673", "Id": "506684", "Score": "0", "body": "You can see the code [here](https://phpize.online/?phpses=cbbac21ac3998bdb07786e8563cd275b&sqlses=null&php_version=php8&sql_version=mysql57)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-02T16:00:19.377", "Id": "506685", "Score": "0", "body": "I think I'll make you confused..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-02T16:01:25.810", "Id": "506686", "Score": "1", "body": "Like I said, validateEmail should just `return` the result. findUserByEmail shouldn't be a part pf the Validator class but a Signup class. SignUpValidationError should be a class, not a method" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-03T12:40:41.657", "Id": "506778", "Score": "0", "body": "@AnneBatch Did I make it any clearer for you? To be honest, this is quite a complex topic, it took me years to start understanding the principle which is used to separate the code between classes. So it's not a problem if you won't make it all at once" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-03T23:16:01.180", "Id": "506839", "Score": "0", "body": "Yes, I understood you perfectly. I'm just having some problems when dealing with the database, but that's okay, I won't give up. The most important thing is that I learned, thank you for your help, I'm happy to have helped me and because you are still here, I recognize that you are an excellent professional, talking to you is an honor. Thanks! I wish you success." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-04T05:53:39.140", "Id": "506866", "Score": "0", "body": "@AnneBatch yes, a database is always a problem. What I would *really* propose is to discard the Signup class and create a *User* class, with methods involving a database interaction, which would roughly represent a \"Model\" from the famous MVC acronym. It would have methods signup(), login(), findUserByEmail() etc. and both signup(), login() would use findUserByEmail() internally" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T15:11:19.153", "Id": "256442", "ParentId": "256391", "Score": "6" } }, { "body": "<p>First of all, you really deserve to be commended for following best practices in PHP programming. You really want to learn how to develop websites properly and your effort shows.</p>\n<p>The code which you have shown us already looks amazing and you are on the right track. However, there are still a lot of things that you could improve. Let's review some of them.</p>\n<h1>Database class</h1>\n<p>PDO is a built-in class for all your database needs. You don't really need another class to wrap PDO around. However, if you want to make your development easier you could use one of the popular classes that abstract PDO further, e.g. <a href=\"https://github.com/paragonie/easydb\" rel=\"noreferrer\">EasyDB</a>. <strong>You definitely do not need an empty <code>DatabaseConnection</code> class</strong>.</p>\n<p>I would also recommend to use fully-qualified names whenever possible. It helps to avoid accidental name clashes.</p>\n<h2>Inheriting from the database class</h2>\n<p>This is a big no. Your <code>SignUp</code> class is not a special instance of <code>DatabaseConnection</code>. It needs a database connection, but it is not a type of database connection class. Inheritance should narrow the type of object.</p>\n<h2>Error reporting</h2>\n<p>Since PHP 8.0 PDO has error reporting always enabled, but as a best practice I would recommend to enable error reporting explicitly and <strong>disable emulated prepares</strong>.</p>\n<p>When we fix these problems, this is what is left:</p>\n<pre><code>try {\n $pdo = new \\PDO(&quot;mysql:host=$host;dbname=$dbname;charset=utf8mb4&quot;, $username, $password, [\n \\PDO::ATTR_ERRMODE =&gt; \\PDO::ERRMODE_EXCEPTION,\n \\PDO::ATTR_EMULATE_PREPARES =&gt; false\n ]);\n} catch (\\PDOException $e) {\n throw new \\PDOException($e-&gt;getMessage(), (int) $e-&gt;getCode());\n}\n</code></pre>\n<h1>Comments</h1>\n<p>This is always a controversial topic. Code comments are meant to help you or any other developer who reads the code after you understand the difficult parts of the code. But if your code has difficult non-self-explanatory code then you should refactor it. This should result in keeping comments in code to the absolute minimum. Use self-descriptive variable/class/function names. Don't make your functions/classes too complex. Keep it all simple.</p>\n<p>This also applies to PHPDoc blocks. The code should be written in such a way that you shouldn't need them either.</p>\n<p>Comments are bad because they often go stale. You will change the code, but you forget to update the comments. Comments often tend to make an idiot of the developer, and that isn't always the fault of the person who wrote the comment.</p>\n<p>Consider this example:</p>\n<pre><code>/**\n * Database Connection\n * @var PDO\n */\nprivate $database;\n</code></pre>\n<p>The comment tells me that this property holds a database connection and is of type PDO. This is not a lie, but we could convey exactly the same information using pure code.</p>\n<pre><code>private \\PDO $databaseConnection;\n</code></pre>\n<p>Some of your comments are useful, but some of them are not:</p>\n<blockquote>\n<p>Checks if the fields have been filled</p>\n</blockquote>\n<p>What fields? The method doesn't take any arguments and it doesn't return any values. The comment fails to explain the behaviour of that method.</p>\n<p>This is almost a good comment:</p>\n<pre><code>/**\n * Checks if the username matches the regular expression\n * The purpose of regular expression is to prevent JavaScript attacks\n * The user will not be able to use certain characters, such as &lt;&gt; \\/\n */\n</code></pre>\n<p>It aims to explain a regular expression, which are always difficult to read. However, what attacks does it prevent? How does it prevent them? I assume you meant XSS, but this is not good protection against XSS. It can't be a JavaScript injection either. What is the purpose of the regex then?</p>\n<h1>The Signup class</h1>\n<p>This class does too much. It is not really object-oriented. While it is difficult to have true OOP in MVC programming, this class is especially bad at it. You call each method procedurally one after another. What we can do is split up the functionality into separate classes and then refactor this class.</p>\n<h2>Password class</h2>\n<p>Password hashing functionality should really be a separate class. In your example, you could create a simple class like this one:</p>\n<pre><code>class Password\n{\n const ALGO = PASSWORD_BCRYPT;\n\n const OPTIONS = [\n 'cost' =&gt; 12,\n ];\n\n public static function hash(string $password): string\n {\n if ($password === '') {\n throw new \\RuntimeException('Password cannot be empty.');\n }\n\n return password_hash($password, self::ALGO, self::OPTIONS);\n }\n}\n</code></pre>\n<p>The advantage of having a separate class is that you can extend it with more functionality later on. For example, checking the password strength. (Warning: do not add arbitrary restrictions, do not force people to use certain character classes. Good password should be of at least a certain length with no maximum and should not appear in any leaked password lists). I have written in the past a very similar class:</p>\n<pre><code>&lt;?php\n\nnamespace Security;\n\nuse Curl\\Curl;\nuse Curl\\CurlException;\n\nclass Password\n{\n const ALGO = \\PASSWORD_DEFAULT;\n const OPTIONS = ['cost' =&gt; 12];\n const MIN_LENGTH = 8;\n\n public function hash(string $password): string\n {\n if ($password === '') {\n throw new \\RuntimeException('Password cannot be empty.');\n }\n\n return \\password_hash($password, self::ALGO, self::OPTIONS);\n }\n\n public function needsRehash(string $hash): bool\n {\n return \\password_needs_rehash($hash, self::ALGO, self::OPTIONS);\n }\n\n public function checkIfStrongPassword(string $password): bool\n {\n try {\n $count = $this-&gt;getHashCountFromAPI($password);\n } catch (CurlException $e) {\n error_log('Could not verify password quality.');\n return \\mb_strlen(\\count_chars($password, 3)) &gt;= self::MIN_LENGTH;\n }\n return \\mb_strlen($password) &gt;= self::MIN_LENGTH &amp;&amp; $count &lt; 1;\n }\n\n private function getHashCountFromAPI(string $password): int\n {\n $hash = \\strtoupper(\\sha1($password));\n $first5 = \\substr($hash, 0, 5);\n $rest = \\substr($hash, 5);\n $rq = new Curl('https://api.pwnedpasswords.com/range/'.$first5);\n foreach (\\explode(&quot;\\r\\n&quot;, $rq-&gt;exec()) as $line) {\n [$secondPartOfHash, $count] = \\explode(':', $line);\n if ($rest === $secondPartOfHash) {\n return $count;\n }\n }\n return 0;\n }\n}\n</code></pre>\n<h2>UserAccount class</h2>\n<p>I believe that if we use classes we should strive to follow the OOP concept. In OOP, classes should represent entities that have certain properties and certain actions. Here, we are trying to create a new user account so we should have such class that represents an account. This class can have setters as actions that would validate each input. For example:</p>\n<pre><code>&lt;?php\n\ndeclare(strict_types=1);\n\nclass UserAccount\n{\n private string $name;\n private string $email;\n private string $passwordHash;\n\n public function __construct(public Validator $validator)\n {\n }\n\n public function setName(string $name): void\n {\n $this-&gt;name = $name;\n }\n\n public function getName(): string\n {\n return $this-&gt;name;\n }\n\n public function setEmail(string $email): void\n {\n if (!$this-&gt;validator-&gt;isEmail($email)) {\n throw new \\RuntimeException('Incorrect email!');\n }\n $this-&gt;email = $email;\n }\n\n public function getEmail(): string\n {\n return $this-&gt;email;\n }\n\n public function setPassword(string $password, string $confirm): void\n {\n if ($password === $confirm) {\n $this-&gt;passwordHash = Password::hash($password);\n } else {\n throw new \\RuntimeException('Passwords does not match!');\n }\n }\n\n public function getPasswordHash(): string\n {\n return $this-&gt;passwordHash;\n }\n}\n</code></pre>\n<p>For more information on how to properly validate input and report errors see <a href=\"https://codereview.stackexchange.com/a/256442/185636\">Your Common Sense's answer</a></p>\n<h2>The new Signup class</h2>\n<p>Ok, so now that we have split the responsibility of this class into smaller classes what is left to do in this class? As the name suggests, it should have a method that takes a user as an argument and saves it into the database.</p>\n<pre><code>&lt;?php\n\ndeclare(strict_types=1);\n\nclass SignUp\n{\n\n public function __construct(private PDO $databaseConnection)\n {\n }\n\n public function addUser(UserAccount $user): void\n {\n $statement = $this-&gt;databaseConnection-&gt;prepare(&quot;INSERT INTO users (name, email, password, ip, client_ip, forwarded_ip, user_agent) VALUES(?, ?, ?, ?, ?, ?, ?)&quot;);\n $statement-&gt;execute([\n $user-&gt;getName(),\n $user-&gt;getEmail(),\n $user-&gt;getPasswordHash(),\n $_SERVER['REMOTE_ADDR'],\n $_SERVER['HTTP_CLIENT_IP'],\n $_SERVER['HTTP_X_FORWARDED_FOR'],\n $_SERVER['HTTP_USER_AGENT']\n ]);\n }\n}\n</code></pre>\n<p>Cool, but what about checking if the username or email already exists in the database? Answer: don't! <strong><a href=\"https://stackoverflow.com/questions/17736421/how-to-prevent-duplicate-usernames-when-people-register/66285030#66285030\">You should set the field in the database table to be unique if you want to prevent duplicate entries</a>.</strong> I didn't include methods to check for their existence because when you try to insert a duplicate then PDO will throw an exception. You can look for that in your error handler and inform the user that this username is taken.</p>\n<h1>Main file</h1>\n<pre><code>&lt;?php\n\ndeclare(strict_types=1);\n\nspl_autoload_register();\n\ntry {\n $pdo = new \\PDO(&quot;mysql:host=$host;dbname=$dbname;charset=utf8mb4&quot;, $username, $password, [\n \\PDO::ATTR_ERRMODE =&gt; \\PDO::ERRMODE_EXCEPTION,\n \\PDO::ATTR_EMULATE_PREPARES =&gt; false\n ]);\n} catch (\\PDOException $e) {\n throw new \\PDOException($e-&gt;getMessage(), (int) $e-&gt;getCode());\n}\n\n$validator = new Validator(); // unspecified class\n\n$newUser = new UserAccount($validator);\n$newUser-&gt;setName(filter_input(INPUT_POST, 'name'));\n$newUser-&gt;setEmail(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL));\n$newUser-&gt;setPassword(filter_input(INPUT_POST, 'password'), filter_input(INPUT_POST, 'password2'));\n\n(new Signup($pdo))-&gt;addUser($newUser);\n</code></pre>\n<h1>Other points</h1>\n<ul>\n<li>Always specify all your columns in the <code>INSERT</code> statement.</li>\n<li>I don't understand why do you maintain IP addresses as part of your user record. Consider rethinking this approach.</li>\n<li>Return early or use exceptions for erroneous situations. Do not use custom handling like you did as this is very messy and against best practices.</li>\n<li>Do not check for return value of <code>PDOStatement::execute()</code>. If the query fails then PDO will throw an exception.</li>\n<li>Use PSR-4 and autoloader. I recommend using Composer's autoloader but if you want something simpler you can write your own one in a few lines of code or use the built-in one.</li>\n<li>Session handling requires a little bit more logic than <code>session_start()</code>, but that's a completely different topic.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T21:06:41.720", "Id": "256448", "ParentId": "256391", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T20:37:38.487", "Id": "256391", "Score": "8", "Tags": [ "php", "security" ], "Title": "Is my website's PHP registration system secure?" }
256391
<p>I have an implementation of an edit text to show line numbers and also highlight the current line. I think it needs more optimization because when I scroll through the edit text with about 500 lines of code, it lags, yet when I comment out the code, the scrolling is smooth.</p> <p>I need help optimizing this <code>onDraw</code> method in which I do everything above. The line numbers appear on the right with a custom separator e.g</p> <pre><code> 1| ... 10| .. 100| .. </code></pre> <pre class="lang-java prettyprint-override"><code>public class NumberedEditText extends AppCompatEditText { private Rect nRect; private Rect nRect_; private int nOffset; private Paint nPaint; private Paint nPaint_; private boolean nShow; private int nAlignment; private char nSeparator; private boolean nLineHlt; public NumberedEditText (Context context, AttributeSet attrs) { super (context, attrs); nRect = new Rect (); nRect_ = new Rect (); nPaint = new Paint (); nPaint_ = new Paint (); nAlignment = NUMBER_ALIGNMENT_LEFT_SEP_LEFT; nSeparator = '|'; nLineHlt = true; nShow = true; nOffset = 2; nPaint_.setColor (Color.parseColor (&quot;#222222&quot;)); nPaint.setColor (Color.LTGRAY); nPaint.setStyle (Paint.Style.FILL); nPaint.setTypeface (Typeface.MONOSPACE); } @Override public void onDraw (Canvas canvas) { // I use short variable names because i think // they are executed much faster. if (nShow) { nPaint.setTextSize (getTextSize () - nOffset); int bl = getBaseline (); int lc = getLineCount (); int lh = getLineHeight (); // i use an array here for efficient // random access to store the // positions where the line numbers // will be according to the number // of lines String lcs = Integer.toString (lc); int nl = lcs.length (); char[] ch = new char[nl + 1]; int cl = ch.length; String s; // i fill the array with spaces // ready to be replaced with numbers for (int i = 0; i &lt; nl; i++) ch [i] = 32; // set the last character to the separator ch [nl] = nSeparator; // now i loop thru all the numbers // replacing the characters in the array // (with spaces) with numbers // to form something like // ' 1|' // ' 10|' // ' 100|' for (int i = 1, j = cl - 2; i &lt;= lc; i++, bl += lh) { if (i == 10 || i == 100 || 1 == 1000 || i == 10000 || i == 100000) j--; s = Integer.toString (i); if (j &gt; -1) s.getChars (0, s.length (), ch, j); canvas.drawText (ch, 0, cl, nRect.left, bl, nPaint); } // now i set the padding and an // additional margin setPadding ((int) nPaint.measureText (lcs + &quot;__&quot;), getPaddingTop (), getPaddingRight (), getPaddingBottom ()); } // this is to highlight the current line Layout l = getLayout (); if (nLineHlt &amp;&amp; l != null) { int ln = l.getLineForOffset (getSelectionStart ()); getLineBounds (ln, nRect_); canvas.drawRect (nRect_, nPaint_); } super.onDraw (canvas); } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<blockquote>\n<p>// I use short variable names because i think<br />\n// they are executed\nmuch faster.</p>\n</blockquote>\n<p>You are wrong. Execution speed does not depend on the length of identifiers anyhow.</p>\n<blockquote>\n<pre><code>// i use an array here for efficient\n// random access to store the\n// positions where the line numbers\n// will be according to the number\n// of lines\n</code></pre>\n</blockquote>\n<p>As usual the use of (primitive) arrays leads to procedural solution involving al lot of looping. Unnecessary looping is the most common performance issue.</p>\n<blockquote>\n<pre><code> // now i loop thru all the numbers\n // replacing the characters in the array\n // (with spaces) with numbers\n</code></pre>\n</blockquote>\n<p>Instead of looping you should <em>calculate</em> what you need.</p>\n<p>Because of your poor naming I'm not analyzing in detail what your code really does, but it looks like in mainly calculates the indentation needed.\nGiven the number of the current line and the overall line count I would do it this way:</p>\n<pre><code> // this could also be a member variable \n // so that it does not need to be \n // calculated each time the draw method runs\n int indentedNumberWith =\n String.valueOf(lineCount).length();\n\n String indentedLineNumber =\n String.format(\n &quot;% &quot;+indentedNumberWith+&quot;s&quot;,\n // note this ^ space\n String.valueOf(lineNumber));\n</code></pre>\n<p>This should replace the loop with the <code>if</code> cascade...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-07T21:47:58.593", "Id": "256859", "ParentId": "256393", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T02:11:23.627", "Id": "256393", "Score": "2", "Tags": [ "java", "android", "text-editor" ], "Title": "how to efficiently draw line numbers in edittext ondraw without causing lag in scrolling" }
256393
<p>CODE:</p> <pre><code>applicationData = [td.text for td in webBrowser.find_elements_by_xpath('//td[@class=&quot;wpsTableNrmRow&quot; and text()!=&quot; &quot;]')] applicationHeader = [re.sub('[^A-Za-z0-9]+', '', td.text) for td in webBrowser.find_elements_by_xpath('//td[@class=&quot;wpsTableShdRow&quot; and text()!=&quot; &quot;]')] record = {'TitleOfInvention': (webBrowser.find_element_by_xpath('//*[@id=&quot;bibviewTitle&quot;]/tbody/tr/td[2]')).text} for i in range(len(applicationHeader)): record[applicationHeader[i]] = applicationData[i] return record </code></pre> <p>I am returning scraped data in the dictionary type. But I DON'T WANT to use 3 LOOPS for scraping and storing it in a record(dictionary).</p> <p>I can't find any other solution other than is.</p> <p>Any suggestion will be helpful to learn.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T21:54:37.737", "Id": "506244", "Score": "0", "body": "Why don't you want to use 3 loops" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T05:58:32.133", "Id": "256396", "Score": "0", "Tags": [ "python-3.x", "web-scraping", "selenium", "webdriver" ], "Title": "Web scraping using selenium in python" }
256396
<p>I've made a Discord bot, and (to my knowledge) the code is pretty good. However, I've mostly taught myself Python and discord.py (the discord library for Python), so I was wondering if there's any improvements to be made.</p> <p>The only thing I can discern right now is that I could probably do with a few more comments, but other than that I'm not really sure.</p> <p><a href="https://github.com/Sinel-Servers-Limited/JoyBot" rel="noreferrer">https://github.com/Sinel-Servers-Limited/JoyBot</a></p> <p>The 'on topic' rules state that I can post external links, but the most important part of the code has to be on the site. I would consider this my most important part:</p> <pre><code># JoyBot/cogs/bump.py @commands.Cog.listener() async def on_message(self, message): try: if Ban(message.guild.id).is_banned(): return except AttributeError: return if Counting(message.guild.id).channel_get_id() == message.channel.id: return firstbump = False if message.author.id == config['DISBOARDID']: for embed in message.embeds: if &quot;:thumbsup:&quot; in embed.description: bumpID = await get_id().member(embed.description) bump = Bmp(message.guild.id, bumpID) oldtop = bump.get_top(raw=True) if oldtop is None: firstbump = True oldtop = 0 bump.add_total() newtop = bump.get_top(raw=True) send_msg = f&quot;&lt;@{bumpID}&gt;, your bump total has been increased by one!\nType `.bumptotal` to view your current bump total!&quot; if not firstbump: if oldtop != newtop: send_msg += &quot;\nYou also managed to get the top spot! Nice!&quot; send_msg += f&quot;\n\n&lt;@{oldtop}&gt;, you've lost your top spot!&quot; else: send_msg += &quot;\n\nYou were also the first to bump the server. Congrats!&quot; await message.channel.send(send_msg) </code></pre> <p>This code tracks the amount of times that a person who 'bumps' the server on Disboard. I consider this important because it's the main feature of my bot, and the one I've spent the most time on.</p>
[]
[ { "body": "<h2>Decorators</h2>\n<h3>The problem to solve</h3>\n<p>The top of your code should be moved into another function as you have duplicated the code elsewhere.\nTo DRY your code we can build a decorator.\nTo explain decorators I'll start from two made up function and work up.</p>\n<p>In our world negative numbers are not allowed, if we get a negative number we <code>return</code>.\nWe have two functions one to double numbers and another to add 1 to a number.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def double(number):\n if number &lt; 0:\n return\n return 2 * number\n\ndef add_one(number):\n if number &lt; 0:\n return\n return 1 + number\n</code></pre>\n<p>Now having the same code in two functions is a code smell.\nIf the spec changes, you need to modify your code at least twice.\nIf you forget even one location you've introduced a bug into your code!\nFor example not handling <code>None</code> may be an oversight, where we actually need to.</p>\n<p>We can introduce a function to check if the number is valid.\nBut this isn't exactly helpful here, because all we've done is hide <code>number &lt; 0</code> behind a function.\nAnd we still have the same <code>if ...: return</code> boilerplate.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_positive(number):\n return 0 &lt;= number\n\ndef double(number):\n if not is_positive(number):\n return\n return 2 * number\n</code></pre>\n<h3>Functions as first class citizens</h3>\n<p>Instead we can pass a function to <code>is_positive</code> to be called if the number is positive.\nThere is the downside that if we don't call our functions in a convoluted way we don't actually validate the input.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_positive(fn, number):\n if number &lt; 0:\n return\n return fn(number)\n\ndef double(number):\n return 2 * number\n\ndef add_one(number):\n return 1 + number\n\nprint(is_positive(double, 2))\nprint(is_positive(double, -1))\nprint(double(-1))\nprint(is_positive(add_one, 2))\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>4\nNone\n-2 # Oops, should be None\n3\n</code></pre>\n<h3>Closures to the rescue</h3>\n<p>To always call <code>is_positive</code> before calling; <code>double</code> and <code>add_one</code>, we can use a closure.\nThe closure will take in a function (<code>double</code> or <code>add_one</code>) and return a new function (what <code>is_positive</code> currently is).</p>\n<p>If we re-assign <code>double</code> to the newly made function the issue is solved.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_positive(fn):\n def inner(number):\n if number &lt; 0:\n return\n return fn(number)\n return inner\n\ndef double(number):\n return 2 * number\n \nprint(is_positive(double)(2))\nprint(is_positive(double)(-1))\nprint(double(-1)) # Still has the issue\n\ndouble = is_positive(double) # Fix the issue\n\nprint(double(2))\nprint(double(-1))\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>4\nNone\n-2 # Look the issue\n4\nNone # Now the issue is fixed\n</code></pre>\n<h3>Decorator syntactic sugar</h3>\n<p>I find <code>double = is_positive(double)</code> to be quite ugly.\nHowever Python has <code>@</code> syntax to decorate functions.\n<code>@</code> is the same as using <code>double = is_positive(double)</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_positive(fn):\n def inner(number):\n if number &lt; 0:\n return\n return fn(number)\n return inner\n\n@is_positive\ndef double(number):\n return 2 * number\n\nprint(double(2))\nprint(double(-1))\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>4\nNone\n</code></pre>\n<h3>Common wrapper patterns</h3>\n<p>Before selecting how to apply decorators to your code, we need to look at ways we can provide arguments to the decorator.</p>\n<ol>\n<li><p>No wrapper</p>\n<p><strong>Pro</strong>: No extra parentheses and really simple implementation.<br />\n<strong>Con</strong>: No option for positional or keyword arguments.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import functools\n\ndef is_positive(fn):\n @functools.wraps(fn)\n def inner(*args, **kwargs):\n # ...\n return inner\n\n@is_positive\ndef double(number):\n return 2 * number\n\n@is_positive\ndef add_one(number):\n return 1 * number\n</code></pre>\n</li>\n<li><p>Closure wrapper</p>\n<p><strong>Pro</strong>: Allow positional and keyword arguments.<br />\n<strong>Con</strong>: Have to always use parentheses even when not providing arguments.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import functools\n\ndef is_positive(include_zero=True):\n def wrapper(fn):\n @functools.wraps(fn)\n def inner(*args, **kwargs):\n # ...\n return inner\n return wrapper\n\n@is_positive(False)\ndef double(number):\n return 2 * number\n\n@is_positive()\ndef add_one(number):\n return 1 * number\n</code></pre>\n</li>\n<li><p>Partial wrapper</p>\n<p><strong>Pro</strong>: Don't have to provide parentheses when not providing arguments.<br />\n<strong>Con</strong>: Only allows keyword arguments.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import functools\n\ndef is_positive(fn=None, *, include_zero=True):\n if fn is None:\n return functools.partial(include_zero=include_zero)\n\n @functools.wraps(fn)\n def inner(*args, **kwargs):\n # ...\n return inner\n\n@is_positive(include_zero=False)\ndef double(number):\n return 2 * number\n\n@is_positive\ndef add_one(number):\n return 1 * number\n</code></pre>\n</li>\n</ol>\n<p>Which you should pick can be a bit complicated.\nThe basics are;</p>\n<ul>\n<li>If you don't need to provide arguments; use 1.</li>\n<li>If you are upgrading from 1, and you need to maintain backwards compatibility; use 3.</li>\n<li>Otherwise pick whichever you prefer between 2 and 3.</li>\n</ul>\n<p>For the most part picking between 2 and 3 is like picking between Coke and Pepsi.\nPick the one that tickles your fancy more.\nI prefer 3.\nI normally don't need positional arguments.\nI think forcing arguments to be keywords is a benefit.\nAnd I don't like having to provide unneeded parentheses.\nHowever 2 is simpler and I think the more common approach.\nFor example we can guess <code>commands.Cog.listener</code> is using 2.</p>\n<h2>Your code</h2>\n<h3>How should you decorate</h3>\n<p><sub><strong>Note</strong>: Code from here is untested</sub></p>\n<p>To decorate your function we can go one of four ways.</p>\n<ol>\n<li><p>Your method should be a static method.\nYou never use <code>self</code> in the code, so we can decorate with <code>@staticmethod</code> first.</p>\n<p><strong>Problem</strong>: You won't be able to decorate a non-static method.</p>\n</li>\n<li><p>The user should specify the argument's index where message is.</p>\n<p><strong>Problem</strong>: The user of the function may forget to specify the correct index. The code now can be kind of noisy, if we haven't selected a good default.</p>\n</li>\n<li><p>You could make a method-aware decorator, possibly making a <a href=\"https://docs.python.org/3/reference/datamodel.html#implementing-descriptors\" rel=\"noreferrer\">descriptor</a>, and assume message is the first argument.</p>\n<p><strong>Problem</strong>: We'd need to convert to a class decorator and would force message to be the first argument. Probably would be annoying to get correctly working with static and class methods.</p>\n</li>\n<li><p>You can inspect the <a href=\"https://docs.python.org/3/library/inspect.html#inspect.signature\" rel=\"noreferrer\">function's signature</a> to get the index of the argument named &quot;message&quot;.</p>\n<p>Similar to how dependency injection injects the correct stuff.\nHowever we wouldn't be injecting dependencies and we'd be going off names not types.</p>\n<p><strong>Problem</strong>: You must name the argument &quot;message&quot;.</p>\n</li>\n</ol>\n<p>The best option is really your choice.\nI quite like 4, but DI isn't really a thing in Python.\nNever mind untyped half-baked DIesque patterns.\nRegardless I'll show you how to implement 2.\n2 is probably the best general way to solve the issue.\nNot too clever and works in most situations.</p>\n<p>Since we are going by index we can, to simplify the code, only take args.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def validate_message(index=0):\n def wrapper(fn):\n @functools.wraps(fn)\n async def inner(*args):\n message = args[index]\n try:\n if Ban(message.guild.id).is_banned():\n return\n except AttributeError:\n return\n\n if Counting(message.guild.id).channel_get_id() == message.channel.id:\n return\n return await fn(*args)\n return inner\n return wrapper\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>@commands.Cog.listener()\n@validate_message(index=1)\nasync def on_message(self, message):\n firstbump = False\n # ...\n</code></pre>\n<h3>Allowing keyword arguments and default values</h3>\n<p>You may need to allow keyword arguments or default values.\nTo do so we should inspect the wrapped function and bind the arguments.\nYour code will then be one step away from implementing 4.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import inspect\n\n\ndef validate_message(index=0):\n def wrapper(fn):\n @functools.wraps(fn)\n async def inner(*args, **kwargs):\n _args = signature.bind(*args, **kwargs)\n message = _args.arguments.get(parameter.name, parameter.default)\n if message is inspect.Parameter.empty:\n raise ValueError(&quot;a message must be provided&quot;)\n # ...\n return await fn(*_args.args, **_args.kwargs)\n\n signature = inspect.signature(fn)\n parameter = list(signature.parameters.values())[index]\n return inner\n return wrapper\n</code></pre>\n<h2>Review</h2>\n<ul>\n<li><p>Your code follows the arrow anti-pattern.\nYou can use guard statements to stop your code from moving more and more rightwards.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if message.author.id != config[&quot;DISBOARDID&quot;]:\n return\n# ...\n</code></pre>\n</li>\n<li><p>Your style isn't consistent, some places you use <code>'</code> other places you use <code>&quot;</code>.\nSame with the case of variables <code>firstbump</code>, <code>bumpID</code> and <code>send_msg</code>.</p>\n<p>Have you taken and modified parts of your code from code on the internet?\nHave you followed the licence(s) if you've taken and modified other people's IP?</p>\n</li>\n<li><p>Strings are not guaranteed to have fast concatenation.\nWith your code I can't really see the need though.\nHowever you can build a list and <code>&quot;&quot;.join</code> to guarantee fast concatenation of strings in all spec compliant environments.</p>\n<p>To my eye the code is now less pretty here.</p>\n</li>\n<li><p>If you have more than one embed in one message, where one is the first bump; your code will say all embeds are the first bump.</p>\n</li>\n<li><p>The rest of the code looks like boilerplate code around <code>get_id</code> and <code>Bmp</code>.\nMy answer is long enough, so I'll leave me review here.</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>@commands.Cog.listener()\n@validate_message(index=1)\nasync def on_message(self, message):\n if message.author.id != config['DISBOARDID']:\n return\n for embed in message.embeds:\n if &quot;:thumbsup:&quot; not in embed.description:\n continue\n\n bump_id = await get_id().member(embed.description)\n bump = Bmp(message.guild.id, bump_id)\n old_top = bump.get_top(raw=True)\n _old_top = old_top or 0\n bump.add_total()\n new_top = bump.get_top(raw=True)\n\n msg = [f&quot;&lt;@{bump_id}&gt;, your bump total has been increased by one!\\nType `.bumptotal` to view your current bump total!&quot;]\n if old_top is None:\n msg.append(&quot;\\n\\nYou were also the first to bump the server. Congrats!&quot;)\n elif _old_top != _new_top:\n msg.append(\n &quot;\\nYou also managed to get the top spot! Nice!&quot;\n f&quot;\\n\\n&lt;@{_old_top}&gt;, you've lost your top spot!&quot;\n )\n\n await message.channel.send(&quot;&quot;.join(msg))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T00:11:21.490", "Id": "256424", "ParentId": "256401", "Score": "6" } } ]
{ "AcceptedAnswerId": "256424", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T08:23:34.577", "Id": "256401", "Score": "6", "Tags": [ "python", "python-3.x", "discord" ], "Title": "Entire Discord bot" }
256401
<p>First, this is my first post on this stack exchange site. So please be patient with me. If there is something wrong or you miss something, please let me know. I will add it asap.</p> <p>I am currently working with the SOLID principles and trying to achieve a practical implementation. I have seen Tim Corey's practical videos on YouTube, which explain the principles well. Now I have a project where I would like to implement this and I am struggling a bit with the implementation of the dependency inversion principle in the context of SQL queries to a SQL server. Here, several instances of different classes are often needed, e.g. <code>SqlConnection</code>, <code>SqlDataAdapter</code> or <code>DataSet</code>. Perhaps in advance. I know that <strong>Dependency Injection</strong> could make things easier. But first I wanted to understand the principle of <strong>dependency inversion</strong>.</p> <p>I've created now a (mini) project, where my approach becomes clear (the project with the complete code is also available on Github <a href="https://github.com/dnsnx/Dependency_Inversion_SQL" rel="nofollow noreferrer">https://github.com/dnsnx/Dependency_Inversion_SQL</a>).</p> <p>I first created an interface <code>IDatabase</code>:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dependency_Inversion_SQL.Interfaces { public interface IDatabase { void AddParameters((string name, object value)[] parameters); System.Data.DataSet GetData(string commandText, System.Data.CommandType commandType = System.Data.CommandType.Text, string sourceTable = null); } } </code></pre> <p>For simplicity, I just want to read data at the moment - no updates yet. So I defined a method for setting parameters (<code>AddParameters</code>) and one method for reading the data (<code>GetData</code>). First difficulty here: Keep the interface non-specific, i.e. not directly designed for SQL Server. In the future, the DB system could be changed! Then I created a class <code>SQLDatabase</code> which implements this interface:</p> <pre><code>using Dependency_Inversion_SQL.Interfaces; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace Dependency_Inversion_SQL.Classes { public class SQLDatabase : IDatabase { #region Variables private readonly string _SqlServer = &quot;Integrated Security=true;Initial Catalog=Test;Server=localhost\\localhost;&quot;; private SqlConnection _SqlConnection; private SqlCommand _SqlCommand; private SqlDataAdapter _SqlDataAdapter; private DataSet _DataSet; #endregion #region Properties public string SqlServer { get { return _SqlServer; } } #endregion #region Constructors public SQLDatabase(SqlConnection sqlConnection, SqlDataAdapter sqlDataAdapter, DataSet dataSet) { _SqlConnection = sqlConnection; _SqlConnection.ConnectionString = _SqlServer; _SqlCommand = _SqlConnection.CreateCommand(); _SqlDataAdapter = sqlDataAdapter; _DataSet = dataSet; } #endregion #region Methods public void AddParameters((string name, object value)[] parameters) { for (var i = 0; i &lt; parameters.Length; i++) { _SqlCommand.Parameters.AddWithValue(parameters[i].name, parameters[i].value); } } public System.Data.DataSet GetData(string commandText, System.Data.CommandType commandType = System.Data.CommandType.Text, string sourceTable = null) { if (sourceTable == null) { sourceTable = &quot;someName&quot;; } _DataSet.Clear(); _SqlCommand.CommandText = commandText; _SqlCommand.CommandType = commandType; _SqlDataAdapter.SelectCommand = _SqlCommand; _SqlDataAdapter.SelectCommand.Connection.Open(); _SqlDataAdapter.Fill(_DataSet, sourceTable); _SqlDataAdapter.SelectCommand.Connection.Close(); _SqlCommand.Parameters.Clear(); _SqlCommand.CommandText = string.Empty; return _DataSet; } #endregion } } </code></pre> <p>Now, to implement dependency inversion, we need a <code>factory</code> class that defines which instances are created:</p> <p><code>Factory</code>:</p> <pre><code>using Dependency_Inversion_SQL.Classes; using Dependency_Inversion_SQL.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dependency_Inversion_SQL { public static class Factory { public static ICar CreateCar() { return new Car(CreateDatabase()); } public static IDatabase CreateDatabase() { return new SQLDatabase(CreateDatabaseConnection(), CreateDatabaseAdapater(), CreateDatabaseDataSet()); } public static System.Data.SqlClient.SqlConnection CreateDatabaseConnection() { return new System.Data.SqlClient.SqlConnection(); } public static System.Data.SqlClient.SqlDataAdapter CreateDatabaseAdapater() { return new System.Data.SqlClient.SqlDataAdapter(); } public static System.Data.DataSet CreateDatabaseDataSet() { return new System.Data.DataSet(); } } } </code></pre> <p>Then I needed a class, which queries SQL data. I created a simple class <code>Car</code>, which &quot;reads&quot; a car name.</p> <pre><code>using Dependency_Inversion_SQL.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dependency_Inversion_SQL.Classes { class Car : ICar { IDatabase _Database; public Car(IDatabase database) { _Database = database; } public string GetCarName() { var result = _Database.GetData(&quot;SELECT 'Audi R8' as CarName&quot;); return result.Tables[0].Rows[0].ItemArray[0].ToString(); } } } </code></pre> <p>Now my console application:</p> <pre><code>using Dependency_Inversion_SQL.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dependency_Inversion_SQL { class Program { static void Main(string[] args) { ICar car = Factory.CreateCar(); Console.WriteLine($&quot;My dream car is an { car.GetCarName() }&quot;); Console.ReadLine(); } } } </code></pre> <p>As I wrote above, I was wondering, if there would be a more easy way to implement the <code>SQLDatabase</code> class. It needs all the stuff in the constructor (<code>SqlConnection</code>, <code>SqlDataAdapter</code>, <code>DataSet</code>) and so on. What I also don't know, if it is correct, how I implemented the generation of these classes in the <code>Factory</code> class.</p> <pre><code>public static System.Data.SqlClient.SqlConnection CreateDatabaseConnection() { return new System.Data.SqlClient.SqlConnection(); } public static System.Data.SqlClient.SqlDataAdapter CreateDatabaseAdapater() { return new System.Data.SqlClient.SqlDataAdapter(); } public static System.Data.DataSet CreateDatabaseDataSet() { return new System.Data.DataSet(); } </code></pre> <p>What I understood is, that the return type, should be a interface as best. This is in my eyes not possible with the SQL classes.</p> <p>If this question is too large or I misunderstood the stack exchange site, please let me know. I will delete the question then. Many thanks in advance for any comment on this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T13:05:23.080", "Id": "506218", "Score": "1", "body": "Welcome to the Code Review Community. This site is specifically about improving ones coding ability. While we may recommend some best practices while reviewing the code, the point is to review the code. It is not clear that you are looking for a code review. We may review design as part of a code review, but for true design reviews you might want to try [Software Engineering](https://softwareengineering.stackexchange.com/help) instead. Please see our help center for what we discuss here, start with [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)." } ]
[ { "body": "<p>Some quick remarks:</p>\n<ul>\n<li><p><code>IDatabase</code> is IMHO a bad name, and you can see that with a method name like <code>CreateDatabase</code>. The same problem also applies to other things, e.g. <code>SqlServer</code> which is in reality a connection string (which you should never hardcoded, it should be part of a configuration file). And so on.</p>\n</li>\n<li><p>I haven't checked your github, but I suspect you are not properly disposing of your DB connections.</p>\n</li>\n<li><p><code>GetCarName()</code> is wrong on so many levels. The proper way is to retrieve a <code>Car</code> object from the DB, and then look at its <code>Name</code> property, e.g. <code>var carName = car.Name;</code>.</p>\n</li>\n</ul>\n<hr />\n<p>But all of that is pointless criticism of details. My advice: throw away all of this code. You're writing your own DB framework, and it will never ever be as good as Entity Framework or Dapper. You're wasting your time; what you should be doing is learning how to properly use Entity Framework or Dapper.</p>\n<p>WRT SOLID etc., please understand that these are guidelines, not unbreakable laws.</p>\n<p>WRT dependency injection etc.: follow the numerous guides on how to combine dependency injection and Entity Framework that are available. These things have been solved long ago, and no company will ever require you to write your own implementation, they'll simply want you to follow their way of working (which will likely be the general way as documented in numerous guides).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T14:27:20.673", "Id": "506224", "Score": "1", "body": "Thank you for your feedback. I know, that the connection should be stored in a configuration file and also I know, that `GetCarName` method is a bad method. It was just to demonstrate the issue I have. I would never implement this method in a production code. As I wrote, I created this project to demonstrate my issue. But many thanks for your hint for Entity Framework. I already implemented it in different project, but I was wondering, if I can use the `SqlConnection` classes with DI, too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T13:08:12.983", "Id": "256409", "ParentId": "256404", "Score": "0" } }, { "body": "<p>I think you have a reasonable grasp to understand the technical ins and out of design patterns, but you are struggling to use them sensibly. So this answer focuses on intent rather than specific syntax.</p>\n<p>I just want to take some time here to point out something that you may wrongly infer about my feedback. Just because I call your implementations bad, doesn't mean I'm calling you a bad developer. You have <em>clearly</em> put a lot of thought and effort into this, and I'm most definitely not accusing you of not doing your due diligence or questioning your ability to write code.</p>\n<p>You know how to lay bricks, but you're not working off of the right blueprint. I often use the example of <a href=\"https://youtu.be/Mc59_SXmZzw?t=58\" rel=\"noreferrer\">Forrest Gump playing American football</a>. He's amazing at putting one foot in front of the other, but he doesn't realize where he should and shouldn't be going or when to stop.</p>\n<p>You've done the same thing. Your code is good if you look at it line by line, but it misses the bigger picture of what it tries to achieve.</p>\n<hr />\n<p><strong>The factory pattern</strong></p>\n<p>A factory is a place that creates things. You've nailed that part.</p>\n<p>However, why would we use a factory instead of just a constructor? Because we can just as well call <code>new Foo()</code> without needing to create a <code>FooFactory.CreateFoo</code>.</p>\n<p>There are three main purposes to the factory pattern:</p>\n<ol>\n<li>If the construction of the object is more complex than the consumer needs to care about, the factory acts as a consumer-friendly simplification.</li>\n<li>If the consumer doesn't get to decide which concrete class should be used, and instead the factory decides that for them. This is what I call a &quot;smart&quot; factory, it makes the choice for the consumer.</li>\n<li>Specific to DI, when a class needs to be able to repeatedly create new instances of an injected dependency, rather than having one instance injected in its constructor.</li>\n</ol>\n<p>Your code, which is a factory wrapper around not even your own code (they're <code>System.Data</code> classes), doesn't actually add anything meaningful. It does nothing, other than call an empty constructor. This doesn't match the purposes of a factory, and therefore the factory is not necessary.</p>\n<p>Some quick examples of how factories can be useful:</p>\n<p><strong>Purpose 1</strong></p>\n<pre><code>public class CarFactory\n{\n public ICar CreateCar()\n {\n return new Car()\n {\n Engine = new PetrolEngine(),\n Wheels = new[] { new Wheel(), new Wheel(), new Wheel(), new Wheel() }\n }\n }\n}\n</code></pre>\n<p>In this example, you don't want your consumer to know how to put a car together, so you have the factory do it for them.</p>\n<p><strong>Purpose 2</strong></p>\n<pre><code>public class CarFactory\n{\n public ICar CreateAppropriateCar(CarGoal goal)\n {\n switch(goal)\n {\n case CarGoal.Racing:\n case CarGoal.ShowingOff:\n return new SportsCar();\n case CarGoal.Transport:\n case CarGoal.LivingIn:\n return new Van();\n case CarGoal.Offroading:\n return new Jeep();\n case CarGoal.Tourism:\n return new TourBus();\n default:\n return new Sedan();\n }\n }\n}\n</code></pre>\n<p>You don't want the consumer to have to decide which car is most appropriate, the consumer only knows what they intend to do with the car (<code>CarGoal</code>). The factory makes the correct decision based on the reported goal.</p>\n<p><strong>Purpose 3</strong> isn't easily demonstrable.</p>\n<hr />\n<blockquote>\n<p>What I understood is, that the return type, should be a interface as best.</p>\n</blockquote>\n<p>For purpose 2, it is <em>essential</em> that your return type is not the concrete type, or it would otherwise defeat the purpose.</p>\n<p>For purposes 1 and 3, it's not necessary but still a general nice-to-have in terms of clean coding. Not so much for the validity of the factory pattern in and of itself, but rather because it implies that you're using your interfaces correctly in your codebase.</p>\n<blockquote>\n<p>This is in my eyes not possible with the SQL classes.</p>\n</blockquote>\n<p>Since they don't implement an interface, it isn't.</p>\n<p>There are cases where you'd wrap a library class in one of your own, and you can implement an interface on that custom class, but don't start doing this blindly as it leads to a bunch over unused over-engineered boilerplate code.</p>\n<hr />\n<p><strong>When all you have is a hammer, everything looks like a nail.</strong></p>\n<pre><code>public static ICar CreateCar()\n{\n return new Car(CreateDatabase());\n}\n</code></pre>\n<p>You've gone overboard on using the factory pattern to the point trying to wrap everything in a factory. This relates back to my initial paragraph in this answer: you know <em>how</em> to implement a factory, but you don't know <em>when or why</em> to implement a factory.</p>\n<p>The larger issue here is that the instantiation of a car should not trigger the instantiation of a database connection (or the object which will eventually make the connection).\nCreating an in-memory object shouldn't be inherently tied to connecting to a database. It defeats the purpose of doing things in-memory. Conceptually these are very separate steps.</p>\n<hr />\n<p><strong>Is-a versus has-a</strong></p>\n<p>The goal is to use <code>SqlDatabase</code> in your codebase, but without tightly coupling yourself to that specific data provider. This much is clear.</p>\n<p>But it seems like the only attempts you've made at doing this has been through using interfaces.</p>\n<p>I can't and won't explain it in its entirety here, but you need to introduce yourself to the concept of <a href=\"https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance\">composition over inheritance</a>. While inheritance isn't quite the same as interface implementation, in context of comparing composition and inheritance, you can lump interfaces in with inheritance.</p>\n<p>Interfaces implementation and class inheritance are a &quot;is-a&quot; relationship. <code>Car</code> <strong>is</strong> an <code>ICar</code>. <code>SQLDatabase</code> <strong>is</strong> an <code>IDatabase</code>.</p>\n<p>But compositions uses a &quot;has a&quot; relationship. Take the example of me, a person. I have a car. How would you reflect that in code? Like this?</p>\n<pre><code>public class Person : Car { }\n</code></pre>\n<p>No. It's not done by using inheritance or interfaces, because &quot;A <code>Person</code> is a <code>Car</code>&quot; is not correct.</p>\n<pre><code>public class Person\n{\n public Car Car { get; set; }\n}\n</code></pre>\n<p>This is the correct approach, because &quot;A <code>Person</code> <strong>has</strong> a <code>Car</code>&quot;</p>\n<p>Note: since cars have interfaces, it's indeed correct to use the interface instead of the concrete type here, so a better version would be:</p>\n<pre><code>public class Person\n{\n public ICar Car { get; set; }\n}\n</code></pre>\n<p>But in cases where there is no interface, using the concrete type would still be a correct usage of composition over inheritance.</p>\n<p>I suggest you look into the <a href=\"https://www.c-sharpcorner.com/UploadFile/b1df45/getting-started-with-repository-pattern-using-C-Sharp/\" rel=\"noreferrer\">repository pattern</a> to understand how to use composition to work with your <code>SqlDatabase</code>, while at the same time hiding it from view from the consumer.</p>\n<p>While I generally don't use repositories myself anymore, it's a really good start for a beginner to grasp basic layer separation and encapsulation. With more experience, you'll learn about other possible (and more advanced) approached.</p>\n<hr />\n<p><strong>Dependency inversion</strong></p>\n<blockquote>\n<p>But first I wanted to understand the principle of dependency inversion.</p>\n</blockquote>\n<p>I can't go into this in full detail, but I'll use an analogy to help you understand the intent. Suppose we run a sandwich shop:</p>\n<pre><code>public class SandwichShop\n{\n public Sandwich MakeSandwich()\n {\n var bread = new WhiteBread();\n bread.Cut();\n\n var toppings = new List&lt;Topping&gt;() { new Bacon(), new Lettuce, new Tomato() };\n\n bread.Add(toppings);\n bread.Wrap();\n\n return bread; \n }\n}\n</code></pre>\n<p>The customer depends on the sandwich shop, and the sandwich shop depends on the white bread. That mean that the customer indirectly depends on the white bread. Similarly, the customer can only have the toppings that the sandwich shop has hardcoded.</p>\n<p><strong>If we give the customer control over which bread to use, that would be inverting the normal order of dependency</strong>.</p>\n<p>This is the same class, but now made with dependency inversion in mind:</p>\n<pre><code>public class SandwichShop\n{\n public Sandwich MakeSandwich(Bread bread, List&lt;Topping&gt; toppings)\n {\n bread.Cut();\n bread.Add(toppings);\n bread.Wrap();\n\n return bread; \n }\n}\n</code></pre>\n<p>Now, the customer (i.e. the actor who calls <code>MakeSandwich</code> gets to decide the bread and the toppings). The downside is that the customer is now responsible for <strong>providing</strong> those dependencies as well.</p>\n<p>This example uses a method and method parameters. In software development, the more common implementation of dependency inversion is related to the constructor argument, but it's the same principle: the caller (i.e. the actor who calls the constructor) provides the dependencies of the object it's creating.</p>\n<p>Just to disambiguate:</p>\n<ul>\n<li>Dependency <em>injection</em> generally refers to using a framework or container to automatically provide the correct dependency to any object, based on what it asks for in the constructor.</li>\n<li>Inverted dependencies are (annoyingly) a completely different thing than dependency inversion, and something significantly more advanced that I'm not going to get into here.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T14:28:20.813", "Id": "506225", "Score": "0", "body": "Many thanks for your detailed feedback. I will carefully read your answer and then give you a feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T13:50:52.003", "Id": "256410", "ParentId": "256404", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T11:17:52.440", "Id": "256404", "Score": "3", "Tags": [ "c#" ], "Title": "Dependency Inversion Principle with connection to a SQL Server" }
256404
<p>Here's an RPG I'm working on that uses only standard C++ libraries. I'm having trouble conceptualizing a coordinate system for characters spawned in a map, and the inventory/item system is only a shell at the moment. However, I've created a small demo including some of the features that will be present in the full product (<code>Game::Test()</code>). This is my first real attempt at a game, so I would love to hear what you think of what I have so far, and ways I could improve.</p> <p>*Note: I didn't include my inventory system, since there's barely any code for it, and what is there is all concept anyways.</p> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;vector&gt; #include &lt;cstring&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &quot;Game.h&quot; int main() { //Seed to use for run; //!FIX; OVERHAUL TO HAVE SEED GENERATED BY RUN INSTEAD OF INSTANCE srand(time(NULL)); Game myRpg; char charInput; std::string strInput; //Run Test Mode (Has Access To Basic Game Mechanics) std::cout &lt;&lt; &quot;Run test? Enter \'Y\' for test.&quot; &lt;&lt; std::endl; std::cin &gt;&gt; charInput; //Test is all that exists right now. Always enter Y to run game if (charInput == 'Y') { myRpg.Test(); } return 0; } </code></pre> <p><strong>Game.h</strong></p> <pre><code>#ifndef GAME_H #define GAME_H #include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;vector&gt; #include &quot;Characters.h&quot; #include &quot;Maps.h&quot; #include &quot;Player.h&quot; class Game { public: Game() {Clear(); Intro(); myChar.CharacterCreation();}; void Clear(); void Intro(); void Test(); void Run(); private: //!FIX; `OUT-OF-RANGE` CRASH WHEN INITIALIZING MAP LIST /*===WIP=== Maps mapLib; */ Characters charLib; //!Will use `(mapLib.size())` once Maps fixed Characters* myChars = &amp;charLib; Player myChar; Character* player = myChar.p; //Counts num turns player has made since init; Currently unused int time; }; #endif </code></pre> <p><strong>Game.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;cstring&gt; #include &lt;cstdio&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;vector&gt; #include &quot;Game.h&quot; void Game::Clear() { for(unsigned int i = 0; i &lt; 50; i++) { std::cout &lt;&lt; std::endl; } } //Displays game intro using text file &quot;intro.txt&quot; void Game::Intro() { //Opens text file &quot;intro.txt&quot; std::ifstream intro; intro.open(&quot;intro.txt&quot;); //Outputs text from file if(intro.is_open()) { std::string str; //While file has not reached the end while(!(intro.eof())) { getline(intro, str); std::cout &lt;&lt; str &lt;&lt; std::endl; } std::cout &lt;&lt; std::endl &lt;&lt; std::endl; intro.close(); } } //Mode to run basic battle functions void Game::Test() { //Clear previous screen Clear(); /*!===TEST; Test() Start=== std::cout &lt;&lt; &quot;Test Start&quot; &lt;&lt; std::endl; */ //Create character and single opponent Character opponent; opponent = charLib.CreateChar(&quot;Bandit&quot;); Character* opp = &amp;opponent; //Create Default Map Map default_map; //!FIX; Find Seg. Fault (Map.cpp) default_map.Print(); std::cout &lt;&lt; &quot;As you sail across the ocean, you come across a bandit,&quot; &lt;&lt; std::endl &lt;&lt; &quot;floating over the water. You pull him aboard, when &quot; &lt;&lt; std::endl &lt;&lt; &quot;suddenly he jolts up, knife readied in hand. It was a &quot; &lt;&lt; std::endl &lt;&lt; &quot;trick!&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Press \'enter\' to continue.&quot;; std::cin.get(); std::cin.ignore(); std::cout &lt;&lt; std::endl; player-&gt;Battle(opp); if (player-&gt;IsAlive() == 0) { std::cout &lt;&lt; &quot;The treasure remains lost. GAME OVER&quot; &lt;&lt; std::endl; return; } std::cout &lt;&lt; &quot;You won!- but the treasure is still out there somewhere...&quot; &lt;&lt; std::endl; /*!===TEST; Test() End=== std::cout &lt;&lt; &quot;Test Successful!&quot; &lt;&lt; std::endl; */ } </code></pre> <p><strong>Player.h</strong></p> <pre><code>#ifndef PLAYER_H #define PLAYER_H #include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;vector&gt; #include &quot;Character.h&quot; class Player { public: Player() {p = &amp;player; lv = 1; player.SetSym('@');} int GetLv(); void PlayerTurn(); void Battle(Character *opponent); //Option 1 void Defend(); //Option 2 void OpenInventory(); //Option 3 void RunAway(); //Option 4 void CharacterCreation(); Character* p; private: Character player; int lv; }; /*===WIP===// struct Ability { std::string name; int lv; int cost(int lv) { return (lv); } bool canAfford(int lv, int mp) { return cost(lv) &lt;= mp; } void show(int lv) { std::cout &lt;&lt; &quot;[&quot; &lt;&lt; cost() &lt;&lt; &quot;] mp\n&quot;; } }; class Job { public: void PrintAbilities(int lv); private: std::string name; std::vector&lt;Ability&gt; abilities; int numAbilities() {return abilities.size();} Ability const &amp;operator[](int index) const { return abilities.at(index); } }; //=========*/ #endif </code></pre> <p><strong>Player.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;cstdio&gt; #include &lt;vector&gt; #include &lt;iomanip&gt; #include &quot;Player.h&quot; //===WIP=== void Player::PlayerTurn() { char usrInput = ' '; std::cout &lt;&lt; &quot;Your turn. Press \'?\' for help.&quot; &lt;&lt; std::endl; usrInput = getchar(); switch(usrInput) { case 'w' || 'a' || 's' || 'd': break; case '?': break; case 'i': //!FIX; FINISH INVENTORY/ITEM SYSTEM std::cout &lt;&lt; &quot;Not functional at this time.&quot; &lt;&lt; std::endl; break; case '*': break; } if (player.IsAlive() == 0) { std::cout &lt;&lt; &quot;Your adventure has come to an end.&quot; &lt;&lt; std::endl; } } void Player::Battle(Character *opponent) { player.Battle(opponent); } void Player::CharacterCreation() { std::string usrStr; //Set Player Name std::cout &lt;&lt; &quot;What's your name? &quot;; getline(std::cin, usrStr); player.SetName(usrStr); //Set name as usrStr input std::cout &lt;&lt; std::endl; //Set Player Stats bool isYes; bool isRollOrSet; do { std::cout &lt;&lt; &quot;Would you like to \'roll\' or \'set\' your stats? &quot; &lt;&lt; &quot;Please enter \'roll\' or \'set\'&quot; &lt;&lt; std::endl; std::cin &gt;&gt; usrStr; if ((usrStr != &quot;roll&quot;) &amp;&amp; (usrStr != &quot;set&quot;)) { std::cout &lt;&lt; &quot;Please enter an appropriate response.&quot; &lt;&lt; std::endl; } else { do { bool setOrRoll = (usrStr == &quot;roll&quot;); switch (setOrRoll) { case 1: //Rolls stats player.RollStats(); break; case 0: //Use a stat pool player.SetStats(); break; } //Confirm with user that they want these stats; Display Stats std::cout &lt;&lt; &quot;Are these stats okay? Enter \'YES\' if so, or enter &quot; &lt;&lt; &quot;\'roll\' / \'set\' to redo your stats accordingly.\n&quot;; std::cout &lt;&lt; std::setw(2); std::cout &lt;&lt; &quot;HP: &quot; &lt;&lt; player.GetHp() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;MP: &quot; &lt;&lt; player.GetMp() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;STR: &quot; &lt;&lt; player.GetStr() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;DEF: &quot; &lt;&lt; player.GetDef() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;MAG: &quot; &lt;&lt; player.GetMag() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;SPD: &quot; &lt;&lt; player.GetSpd() &lt;&lt; std::endl; do { std::cin &gt;&gt; usrStr; isYes = (usrStr == &quot;YES&quot;); isRollOrSet = ((usrStr == &quot;roll&quot;) || (usrStr == &quot;set&quot;)); //If they entered &quot;YES&quot; if (usrStr == &quot;YES&quot;) { break; } //If they entered something other than &quot;YES&quot;, &quot;roll&quot;, or &quot;set&quot; else if ((isYes == false) &amp;&amp; (isRollOrSet == false)) { std::cout &lt;&lt; &quot;Please enter an appropriate answer.&quot; &lt;&lt; std::endl &lt;&lt; std::endl; } //Loops input } while((isYes == false) &amp;&amp; (isRollOrSet == false)); //Loops stat roll } while(isRollOrSet == true); } //Loops initial question } while(isYes == false); } /*===WIP===// Job::PrintAbilities(int lv) { for(unsigned int i = 0; i &lt; numAbilities; i++) { std::cout &lt;&lt; &quot;[&quot; &lt;&lt; i &lt;&lt; &quot;]&quot;; abilites[i].show(lv); } } //=========*/ </code></pre> <p><strong>Characters.h</strong></p> <pre><code>#ifndef CHARACTERS_H #define CHARACTERS_H #include &lt;iostream&gt; #include &lt;vector&gt; #include &quot;Character.h&quot; class Coord { public: Coord() {}; void SetData(int x, int y) { this-&gt;x = x; this-&gt;y = y; } void XShift(int a) {x += a;} void YShift (int b) {y += b;} int GetX() {return x;} int GetY() {return y;} private: int x; int y; }; /********************************************************************/ class Characters { public: Characters() {SetArchList();} Characters(int numMaps) {SetArchList(); charList.resize(numMaps);} void AddCharArch(Character _char, std::vector&lt;Character&gt; _chars); Character CreateChar(std::string archName); private: //Stores character archetypes std::vector&lt;Character&gt; archList; std::vector&lt;std::vector&lt;Character&gt;&gt; charList; /*!FIX; DYNAMICALLY ADD CHARACTERS FROM CURR MAP TO LIST * Reference == Map.cpp, `void Map::SpawnEntities() {};` */ void SetArchList(); }; #endif </code></pre> <p><strong>Characters.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;vector&gt; #include &quot;Characters.h&quot; //Adds character archetypes to characterList void Characters::AddCharArch(Character _char, std::vector&lt;Character&gt; _chars = {{&quot;null&quot;}}) { if (_chars.at(0).GetName() == &quot;null&quot;) { //Copies character data _char archList.push_back(_char); } else { //Copies data from character vector _chars for(unsigned int i = 0; i &lt; _chars.size(); i++) { archList.push_back(_chars.at(i)); } } } //Retrieves character archetype data from characterList Character Characters::CreateChar(std::string archName) { Character archType; for(unsigned int i = 0; i &lt; archList.size(); i++) { Character* charListArch = &amp;archList.at(i); //Creates a pointer for archetype in charList at i if(charListArch-&gt;GetName() == archName) { archType = charListArch-&gt;GetName(); } else { continue; } } return archType; } void Characters::SetArchList() { //Archetype Info |Name | hp| mp|str|def|mag|spd|sym| archList = {{&quot;Bandit&quot; , 15, 0, 5, 2, 0, 2,'b'}, {&quot;Crew&quot; , 24, 4, 8, 5, 2, 4,'c'}, {&quot;Captain&quot;, 32, 8, 10, 8, 5, 6,'C'}}; }; </code></pre> <p><strong>Character.h</strong></p> <pre><code>#ifndef CHARACTER_H #define CHARACTER_H #include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;vector&gt; #include &quot;Inventory.h&quot; class Character { public: Character() : name(&quot;Default&quot;), hp(6), mp(6), str(6), def(6), mag(6), spd(6) {}; Character(std::string name) : hp(12), mp(6), str(6), def(6), mag(6), spd(6) {this-&gt;name = name;} Character(std::string name, int hp, int mp, int str, int def, int mag, int spd, char symbol) { this-&gt;name = name; this-&gt;hp = hp * 3; this-&gt;mp = mp; this-&gt;str = str; this-&gt;def = def; this-&gt;mag = mag; this-&gt;spd = spd; this-&gt;symbol = symbol; } void SetName(std::string); //Create character name std::string GetName() {return name;} //Get character's name void SetStats(); //Set stat values using point pool void RollStats(); //Roll d12 for character's start stats void SetHp(int hp) {this-&gt;hp = hp;} void SetMp(int mp) {this-&gt;mp = mp;} void SetStr(int str) {this-&gt;str = str;} void SetDef(int def) {this-&gt;def = def;} void SetMag(int mag) {this-&gt;mag = mag;} void SetSpd(int spd) {this-&gt;spd = spd;} void SetSym(char symbol) {this-&gt;symbol = symbol;} int GetHp() const {return hp;} int GetMp() const {return mp;} int GetStr() const {return str;} int GetDef() const {return def;} int GetMag() const {return mag;} int GetSpd() const {return spd;} char GetSym() const {return symbol;} void Battle(Character *opponent); bool IsAlive() const {return hp &gt; 0;} //Check if character's alive void TakeDamage(Character *opponent); //Take damage int GetDamage(Character* opponent) const; private: std::string name; //Character name int hp; //Health of character int mp; //Magic points of character int str; //Strength of character int def; //Defense of character int mag; //Magic skill of character int spd; //Speed of character char symbol; }; #endif </code></pre> <p><strong>Character.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;cstdlib&gt; #include &quot;Character.h&quot; void Character::SetName(std::string name) { this-&gt;name = name; } //Allows the user to freely set their character's stats from a pool of 36 void Character::SetStats() { int pointPool = 36; for(unsigned int i = 0; i &lt; 6; i++) { int usrInt = 0; bool goodStat = false; do { std::cout &lt;&lt; &quot;You have &quot; &lt;&lt; pointPool &lt;&lt; &quot; points remaining.\n&quot;; std::cout &lt;&lt; &quot;How many points for &quot;; switch(i) { case 0: std::cout &lt;&lt; &quot;HP? &quot;; std::cin &gt;&gt; usrInt; break; case 1: std::cout &lt;&lt; &quot;MP? &quot;; std::cin &gt;&gt; usrInt; break; case 2: std::cout &lt;&lt; &quot;STR? &quot;; std::cin &gt;&gt; usrInt; break; case 3: std::cout &lt;&lt; &quot;DEF? &quot;; std::cin &gt;&gt; usrInt; break; case 4: std::cout &lt;&lt; &quot;MAG? &quot;; std::cin &gt;&gt; usrInt; break; case 5: std::cout &lt;&lt; &quot;SPD? &quot;; std::cin &gt;&gt; usrInt; break; } // Check if player choice was appropriate if (usrInt &gt; pointPool) { std::cout &lt;&lt; &quot;Not enough points.&quot; &lt;&lt; std::endl; } else if (usrInt &lt; 0) { std::cout &lt;&lt; &quot;Can't allocate less than 0 points.&quot; &lt;&lt; std::endl; } //Set Stats else { switch(i) { case 0: SetHp(usrInt * 3); break; case 1: SetMp(usrInt); break; case 2: SetStr(usrInt); break; case 3: SetDef(usrInt); break; case 4: SetMag(usrInt); break; case 5: SetSpd(usrInt); break; } goodStat = true; } } while(goodStat == false); //Subtract player choice from point pool pointPool -= usrInt; /*!===TEST; SetStats() Interval=== std::cout &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Test: Interval &quot; &lt;&lt; i &lt;&lt; std::endl; */ } } void Character::RollStats() { int pointPool = 36; for(unsigned int i = 0; i &lt; 6; i++) { int randNum; //Get random number 1-8 for stat allocation do { randNum = (rand() % 8) + 1; if(randNum &lt;= pointPool) { break; } } while(randNum &gt; pointPool); //Set stat using randNum switch(i) { case 0: if (randNum &lt;= 3) { randNum = 4; } SetHp(randNum * 3); //Set Health break; case 1: SetMp(randNum); //Set Magic Points break; case 2: SetStr(randNum); //Set Strength break; case 3: SetDef(randNum); //Set Defense break; case 4: SetMag(randNum); //Set Magic Skill break; case 5: SetSpd(randNum); //Set Speed break; } pointPool -= randNum; //Remove randNum from pointPool } } void Character::Battle(Character *opponent) { bool att; //Attacker bool opp; //Opponent do { bool whoseFaster = GetSpd() &gt; opponent-&gt;GetSpd(); switch(whoseFaster) { case 1: //Player's faster opponent-&gt;TakeDamage(this); std::cout &lt;&lt; name &lt;&lt; &quot; hits &quot; &lt;&lt; opponent-&gt;GetName() &lt;&lt; &quot; for &quot; &lt;&lt; opponent-&gt;GetDamage(this) &lt;&lt; &quot; points.&quot; &lt;&lt; std::endl; //If the opponent died from attack, end battle if (IsAlive() == false) { break; } TakeDamage(opponent); std::cout &lt;&lt; opponent-&gt;GetName() &lt;&lt; &quot; hits &quot; &lt;&lt; name &lt;&lt; &quot; for &quot; &lt;&lt; GetDamage(opponent) &lt;&lt; &quot; points.&quot; &lt;&lt; std::endl; break; case 0: //Opponent's faster TakeDamage(opponent); std::cout &lt;&lt; opponent-&gt;GetName() &lt;&lt; &quot; hits &quot; &lt;&lt; name &lt;&lt; &quot; for &quot; &lt;&lt; GetDamage(opponent) &lt;&lt; &quot; points.&quot; &lt;&lt; std::endl; //If player died from attack, end battle if (IsAlive() == false) { break; } //Else, player attacks opponent-&gt;TakeDamage(this); std::cout &lt;&lt; name &lt;&lt; &quot; hits &quot; &lt;&lt; opponent-&gt;GetName() &lt;&lt; &quot; for &quot; &lt;&lt; opponent-&gt;GetDamage(this) &lt;&lt; &quot; points.&quot; &lt;&lt; std::endl; break; } std::cout &lt;&lt; GetName() &lt;&lt; &quot; has &quot; &lt;&lt; GetHp() &lt;&lt; &quot; HP remaining.&quot; &lt;&lt; std::endl &lt;&lt; opponent-&gt;GetName() &lt;&lt; &quot; has &quot; &lt;&lt; opponent-&gt;GetHp() &lt;&lt; &quot; hp remaining.&quot; &lt;&lt; std::endl &lt;&lt; std::endl; att = IsAlive(); opp = opponent-&gt;IsAlive(); } while( (att == true) &amp;&amp; (opp == true) ); switch(att) { case 1: std::cout &lt;&lt; opponent-&gt;GetName() &lt;&lt; &quot; was slain.&quot; &lt;&lt; std::endl; break; case 0: std::cout &lt;&lt; name &lt;&lt; &quot; was cut down.&quot; &lt;&lt; std::endl; break; } } //Character takes damage from parameter // |Recipient| |Attacker| void Character::TakeDamage(Character *opponent) { int dmg = GetDamage(opponent); hp -= dmg; } //Returns damage value // |Recipient| |Attacker| int Character::GetDamage(Character* opponent) const { int dmg = (opponent-&gt;GetStr() - def); if (dmg &lt; 1) { dmg = 1; } return dmg; } </code></pre> <p><strong>Maps.h</strong></p> <pre><code>#ifndef MAPS_H #define MAPS_H #include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;vector&gt; #include &quot;Map.h&quot; class Maps { public: Maps() {SetMapTypes(); SetMapNumTypes(); GenMaps(1);} Maps(int numMaps) {SetMapTypes(); SetMapNumTypes(); GenMaps(numMaps);} void SetCurrMap(); void PrintCurrMap() const; private: //Map types and num of maps per type std::vector&lt;std::string&gt; mapTypes; std::vector&lt;int&gt; mapNumTypes; //Collection of Map std::vector&lt;Map&gt; maps; //Copy of map for gameplay Map currMap; void SetMapTypes(); void SetMapNumTypes(); void GenMaps(int numMaps); }; #endif </code></pre> <p><strong>Maps.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;vector&gt; #include &lt;cstdlib&gt; #include &quot;Maps.h&quot; #include &quot;Map.h&quot; void Maps::SetMapTypes() { mapTypes = {&quot;test_area&quot;, &quot;ship_battle&quot;}; } void Maps::SetMapNumTypes() { // test_area, ship_battles mapNumTypes = { 1, 1}; } void Maps::GenMaps(int numMaps) { srand(time(NULL)); for(int k = 0; k &lt; numMaps; k++) { //Set random map type from library int randType = rand() % mapTypes.size(); std::string mapType = mapTypes.at(randType); //Get num of maps for type; Set random map variation int mapVars = mapNumTypes.at(randType); int randMapVar = rand() % mapVars; //Set map name std::string mapName = mapType; mapName.push_back(randMapVar); mapName.append(&quot;.txt&quot;); //Generate and store map copy Map map(mapName); maps.push_back(map); } } </code></pre> <p><strong>Map.h</strong></p> <pre><code>#ifndef MAP_H #define MAP_H #include &lt;iostream&gt; #include &lt;cstring&gt; #include &lt;vector&gt; #include &quot;Characters.h&quot; class Map { public: Map() {this-&gt;name = &quot;default&quot;; GenMap(); SpawnEntities();} Map(std::string name) {this-&gt;name = name; GenMap(); SpawnEntities();} void Print() const; private: std::string name; std::vector&lt;std::vector&lt;char&gt;&gt; map; void GenMap(); void SpawnEntities(); }; #endif </code></pre> <p><strong>Map.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;cstring&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;vector&gt; #include &quot;Map.h&quot; void Map::GenMap() { /*!===TEST; GenMap() Start=== std::cout &lt;&lt; &quot;Map Gen Start&quot; &lt;&lt; std::endl; */ int width = 0; int height = 0; //If name is &quot;default&quot;, generate pre-made test map if (name == &quot;default&quot;) { map = {{'~','~','~','~','~','~','~','~','~'}, {'~','~','~','~','~','~','~','~','~'}, {'~','~','~','~','-','~','~','~','~'}, {'~','~','~','|','*','|','~','~','~'}, {'~','~','~','|','b','|','~','~','~'}, {'~','~','~','|','@','|','~','~','~'}, {'~','~','~','~','-','~','~','~','~'}, {'~','~','~','~','~','~','~','~','~'}, {'~','~','~','~','~','~','~','~','~'}}; } else { //Open map file of the same name as parameter std::ifstream mapFile; mapFile.open(name); //Copy contents of map to 2D vector if (mapFile.is_open()) { std::string str; getline(mapFile, str); } //Closes if statement mapFile.close(); } //Closes else statement /*!===TEST; GenMap() END=== std::cout &lt;&lt; &quot;Map Gen Successful!&quot; &lt;&lt; std::endl; */ } //===WIP=== void Map::SpawnEntities() { //Do not spawn entities when map is default if (name == &quot;default&quot;) { return; } int randNum1 = rand() % 16; //Spawn Player for(size_t i = 0; i &lt; map.size(); i++) { //Row size bool placedPlayer = false; for(size_t k = 0; k &lt; map.at(i).size(); k++) { //Column size int thisRandNum = rand() % 16; if((thisRandNum == randNum1) &amp;&amp; (map[i][k] == '*')) { map[i][k] = '@'; placedPlayer = true; break; } } if(placedPlayer == true) { break; } } //Spawn enemies int mapSeverity = (rand() % 5) + 1; //Enemy # multiplier between 1-5 int numEntities = ((rand() % 4) + 1) * mapSeverity; //# of enemies spawned std::vector&lt;char&gt; includeEntities; std::vector&lt;int&gt; numSpawns; //!===TEST; mapSeverity Setting=== if(name == &quot;default&quot;) { mapSeverity = 1; numEntities = 3; } switch(mapSeverity) { case 5: case 4: includeEntities.push_back('C'); case 3: includeEntities.push_back('c'); case 2: case 1: includeEntities.push_back('b'); } int randNum2 = rand() % 16; for(size_t i = 0; i &lt; map.size(); i++) { //Row for(size_t k = 0; k &lt; map.at(i).size(); k++) { //Column int thisRandNum = rand() % 16; if((thisRandNum == randNum2) &amp;&amp; (map[i][k] == '*')) { /*!===Finish Coding Entitiy Spawner=== //Needs: - Spawn number of each entity // using int numEntities */ } } } } void Map::Print() const { for(size_t i = 0; i &lt; map.size(); i++) { for(size_t k = 0; k &lt; map.at(i).size(); k++) { std::cout &lt;&lt; map[i][k]; } std::cout &lt;&lt; std::endl; } } </code></pre>
[]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Use the appropriate <code>#include</code>s</h2>\n<p>The code uses <code>std::string</code> but uses <code>#include &lt;cstring&gt;</code>. That's an error, because <code>std::string</code> is in <code>&lt;string&gt;</code> and not in the legacy C <code>&lt;cstring&gt;</code> header. Similarly, <code>main</code> does not need and should not <code>#include &lt;vector&gt;</code> because nothing from that header is used there.</p>\n<h2>Label intentional fallthrough</h2>\n<p>The code includes this switch:</p>\n<pre><code>switch(mapSeverity) {\n case 5:\n case 4:\n includeEntities.push_back('C');\n case 3:\n includeEntities.push_back('c');\n case 2:\n case 1:\n includeEntities.push_back('b');\n}\n</code></pre>\n<p>This has a number of fallthroughs, which are when execution continues from previous cases. It's not clear whether these are intentional or not. If they are not, it's an error and you need to insert <code>break;</code> statements. If they are, and if your compiler is C++17 compliant, you should use the <a href=\"https://en.cppreference.com/w/cpp/language/attributes/fallthrough\" rel=\"noreferrer\"><code>[[fallthrough]]</code> attribute</a>. At the very least, a comment would be useful.</p>\n<h2>Consider using a better random number generator</h2>\n<p>The code contains a number of attempts at random number generation that look like this:</p>\n<pre><code>int mapSeverity = (rand() % 5) + 1; //Enemy # multiplier between 1-5\nint numEntities = ((rand() % 4) + 1) * mapSeverity; //# of enemies spawned\n</code></pre>\n<p>If you are using a compiler that supports at least C++11, consider using a better random number generator. In particular, instead of <code>rand</code>, you might want to look at <a href=\"http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"noreferrer\"><code>std::uniform_int_distribution</code></a> and friends in the <code>&lt;random&gt;</code> header.</p>\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n<h2>Don't loop on <code>eof()</code></h2>\n<p>The code currently contains this in <code>Game.cpp</code>:</p>\n<pre><code>void Game::Intro() {\n //Opens text file &quot;intro.txt&quot;\n std::ifstream intro;\n intro.open(&quot;intro.txt&quot;);\n \n //Outputs text from file\n if(intro.is_open()) {\n std::string str;\n //While file has not reached the end\n while(!(intro.eof())) {\n getline(intro, str);\n std::cout &lt;&lt; str &lt;&lt; std::endl;\n }\n std::cout &lt;&lt; std::endl &lt;&lt; std::endl;\n intro.close();\n }\n}\n</code></pre>\n<p>It's almost always incorrect to loop on <code>eof()</code> while reading a file. The reason is that the <code>eof</code> indication is only set when an attempt is made to read something from the file when we're already at the end. See <a href=\"https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong\">this question</a> for more details on why using <code>eof</code> is usually wrong.</p>\n<p>Here's how I'd rewrite that function:</p>\n<pre><code>void Game::Intro() {\n std::ifstream intro{&quot;intro.txt&quot;};\n std::string str;\n while (std::getline(intro, str)) {\n std::cout &lt;&lt; str &lt;&lt; '\\n';\n }\n std::cout &lt;&lt; &quot;\\n\\n&quot;;\n}\n</code></pre>\n<p>Better still:</p>\n<pre><code>void Game::Intro() {\n std::ifstream intro{&quot;intro.txt&quot;};\n std::cout &lt;&lt; intro.rdbuf() &lt;&lt; &quot;\\n\\n&quot;;\n}\n</code></pre>\n<h2>Don't write getters and setters for every class</h2>\n<p>C++ isn't Java and writing getter and setter functions for every C++ class is not good style. Instead, move setter functionality into constructors and think very carefully about whether a getter is needed at all. In this code, the <code>Character</code> class is littered with code like this:</p>\n<pre><code>void SetHp(int hp) {this-&gt;hp = hp;}\nint GetHp() const {return hp;}\n</code></pre>\n<p>If anything can modify the value, then it is not an invariant and so there is no advantage to having these functions. Simply declare such data members <code>public</code> instead. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c131-avoid-trivial-getters-and-setters\" rel=\"noreferrer\">C.131</a> for details.</p>\n<h2>Prefer in-class member initializers to constructors</h2>\n<p>The <code>Character</code> class has these three constructors:</p>\n<pre><code>Character() : name(&quot;Default&quot;), hp(6), mp(6), str(6), def(6), mag(6), spd(6) {};\nCharacter(std::string name) : hp(12), mp(6), str(6), def(6), mag(6), spd(6) {this-&gt;name = name;}\nCharacter(std::string name, int hp, int mp, int str, int def, int mag, int spd, char symbol) { \n this-&gt;name = name;\n this-&gt;hp = hp * 3;\n this-&gt;mp = mp;\n // etc. \n}\n</code></pre>\n<p>There's a lot that could be improved here. In particular, simply setting the values for each data member in the declaration makes this much more readable. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c45-dont-define-a-default-constructor-that-only-initializes-data-members-use-in-class-member-initializers-instead\" rel=\"noreferrer\">C.45</a> for details. As an aside, why would you triple only the received value for <code>hp</code>? And why would you have two different default values for <code>hp</code>?</p>\n<h2>Avoid confusing file names</h2>\n<p>There are a few files that differ only by one letter. There is <code>Character.h</code> and <code>Characters.h</code> and a similar situtation for <code>Map.h</code> and <code>Maps.h</code>. It would be a bit kinder to your fellow programmers (and yourself!) if you rename those to make confusion less likely. I'd suggest <code>CharacterCollection</code> for example.</p>\n<h2>Don't return pointers to <code>private</code> data</h2>\n<p>The <code>Player</code> class currently contains this:</p>\n<pre><code>class Player {\npublic:\n Player() {p = &amp;player; lv = 1; player.SetSym('@');}\n // other stuff\n Character* p;\nprivate:\n Character player;\n int lv;\n};\n</code></pre>\n<p>The effect is that we have a public pointer <code>p</code> to private data <code>player</code>! This is bad because it means that any code can reach in and mess with the supposedly private data within the class, a violation of the <em>information hiding</em> principle. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c9-minimize-exposure-of-members\" rel=\"noreferrer\">C.9</a> for details.</p>\n<p>The underlying problem appears to be some confusion about class structure. If a <code>Player</code> is a <code>Character</code>, which appears to be the intent here, then the better way to do this would be to have <code>Character</code> be a base class for <code>Player</code>. After I did a partial refactoring of your code, here's what it looks like:</p>\n<pre><code>// the Player class is derived from the Character class\nclass Player : public Character {\npublic:\n Player() : Character() { symbol ='@'; }\n int GetLv() const;\n void PlayerTurn();\n void Defend();\n void OpenInventory();\n void RunAway();\n void CharacterCreation();\nprivate:\n int lv = 1;\n};\n</code></pre>\n<p>There are a couple things to note here. First, I left the <code>GetLv()</code> function but made it <code>const</code>. Second, I removed the <code>Battle</code> function because the base class <code>Character</code> already implements what we need. Third, because I removed all of the trivial getters and setters from the <code>Character</code> class, the <code>symbol</code> is set directly within the constructor.</p>\n<h2>Simplify your code</h2>\n<p>The <code>Battle()</code> member function of the <code>Character</code> class is much more complex than it needs to be, especially if you take the previous bit of advice and have <code>Player</code> be a derived class of <code>Character</code>. Here's the rewritten <code>Battle()</code> function:</p>\n<pre><code>void Character::Battle(Character *opponent) {\n Character *attacker = this;\n Character *defender = opponent;\n // For the first round, the faster Character is attacker\n // Thereafter, they alternate\n if (attacker-&gt;spd &lt; opponent-&gt;spd) {\n std::swap(attacker, defender);\n }\n while (defender-&gt;IsAlive()) {\n int damage = defender-&gt;TakeDamage(attacker);\n std::cout &lt;&lt; attacker-&gt;name &lt;&lt; &quot; hits &quot; &lt;&lt; defender-&gt;name\n &lt;&lt; &quot; for &quot; &lt;&lt; damage &lt;&lt; &quot; points.\\n&quot;;\n std::swap(attacker, defender);\n // always report the player status\n std::cout &lt;&lt; name &lt;&lt; &quot; has &quot; &lt;&lt; hp &lt;&lt; &quot; HP remaining.\\n&quot;\n &lt;&lt; opponent-&gt;name &lt;&lt; &quot; has &quot; &lt;&lt; opponent-&gt;hp \n &lt;&lt; &quot; hp remaining.\\n\\n&quot;;\n }\n // somebody is dead -- who was it?\n if (IsAlive()) {\n std::cout &lt;&lt; opponent-&gt;name &lt;&lt; &quot; was slain.\\n&quot;;\n } else {\n std::cout &lt;&lt; name &lt;&lt; &quot; was cut down.\\n&quot;;\n }\n}\n</code></pre>\n<h2>Understand overloading</h2>\n<p>The code currently contains this member function:</p>\n<pre><code>void Characters::AddCharArch(Character _char, std::vector&lt;Character&gt; _chars = {{&quot;null&quot;}}) {\n if (_chars.at(0).GetName() == &quot;null&quot;) {\n //Copies character data _char\n archList.push_back(_char);\n }\n else {\n //Copies data from character vector _chars\n for(unsigned int i = 0; i &lt; _chars.size(); i++) {\n archList.push_back(_chars.at(i));\n }\n }\n}\n</code></pre>\n<p>There's a lot going on here that really cries out for refactoring! First, it looks like you're intending to allow either a single character or a collection of them to be appended to the internal <code>archList</code>. If that's the case, make two functions. Here's how I'd do that:</p>\n<pre><code>void Characters::AddCharArch(Character ch) {\n archList.emplace_back(ch);\n}\n\nvoid Characters::AddCharArch(const std::vector&lt;Character&gt;&amp; chars) {\n archList.insert(archList.end(), chars.begin(), chars.end());\n}\n</code></pre>\n<p>Note also that we use <code>emplace_back</code> for the first version since <code>ch</code> is already passed by value and that we use <code>insert</code> to append the list of passed characters to the end of <code>archList</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T19:00:06.507", "Id": "506237", "Score": "0", "body": "Thank you for your advice! I'll definitely take this advice to heart and revise some of the things you mentioned in my program (the one about `AddCharArch()` is especially intriguing to me, and could help with how I've been managing class vectors). However, two notes:\n1) The bleed-through in my case list was intentional, but considering you're the second person to mention it, I should have a comment mentioning it at the very least." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T19:07:10.067", "Id": "506238", "Score": "0", "body": "2) Part of the reason I made this was for a project where we a) could not use public member variables and b) had to initialize members through constructors. However, I think your point about my readability is valid despite these factors, and I'll take that into consideration when revising my code.\n3) I don't wholly understand the point you made about having a direct pointer to a private member, or what a \"base class\" is. Pointers are something I struggle with, but even so if you could explain your point a bit more, I would greatly appreciate it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T20:49:03.257", "Id": "506242", "Score": "0", "body": "I've added more information to the answer to attempt to address your questions. As for your project requiring that members be initialized through constructors, these still are; it just takes a form you might not yet be used to seeing. Generally, it *is* good practice to have private member variables, but trivial getters and setters as you had, defeats the purpose and so you're better off without them in this case, and likely with your `Coord` class as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T22:54:18.753", "Id": "506249", "Score": "0", "body": "I see what you mean. When it comes to the Coord class, that's an unfinished class which I was planning to use to store the coordinates of characters on a 2d vector, but I haven't figured out how I want to do it yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T23:35:08.537", "Id": "506252", "Score": "0", "body": "In regards to your comments about `<random>`, I've looked at it, I've stared at it, I've rolled my eyes at it, and I've gone back to the easy-to-use `rand()`. It's a horribly over-engineered monstrosity if all you want is a sequence of arbitrary numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T23:56:04.040", "Id": "506254", "Score": "0", "body": "@Mark, yes, there are many legitimate criticisms of `<random>`, but as with many things in C++, a little work in deriving something \"better\" (whatever that means to you) often pays dividends well beyond the initial work involved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T03:38:06.847", "Id": "506258", "Score": "0", "body": "I would argue that there doesn't even need to be a `Player` class at all. Conceptually it's a `Character` that is controlled by the user but is otherwise the same. Both `PlayerTurn` and `Battle` can be handled by `Game` or `Map` that just take `Character*` types: `Game::HandlePlayerInput(Character* player);`, `Map::Battle(Character* a, Character* b);`" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T14:50:59.700", "Id": "256412", "ParentId": "256405", "Score": "10" } } ]
{ "AcceptedAnswerId": "256412", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T12:10:34.753", "Id": "256405", "Score": "5", "Tags": [ "c++" ], "Title": "Work-In-Progress RPG" }
256405
<p>I am a beginner coder and was wondering how to improve my c# console code. It makes a tic-tac-toe game.</p> <pre><code> using System; namespace TicTacToe { class Program { static string[] options = { &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot; }; //stores the variables to change static bool Playing = true; //stops the game once someone wins static int turn = 0; static void Main(string[] args) { Intro(); Board(); while (Playing) //is to stop the game once someone wins { if (turn%2 == 0) { Console.WriteLine(&quot;Player 1's turn&quot;); } else { Console.WriteLine(&quot;Player 2's turn&quot;); } int playerInput1; Console.WriteLine(&quot;type in your responce player&quot;); bool torf = int.TryParse(Console.ReadLine(), out playerInput1); playerInput1--; // makes sure the input is put in a valid value if (torf &amp;&amp; playerInput1 &lt; 9 &amp;&amp; playerInput1 &gt; -1) //makes sure again the input is valid and continues { if (options[playerInput1] == &quot;x&quot; || options[playerInput1] == &quot;o&quot;) { Console.WriteLine(&quot;Stop stealing othe people's place&quot;); } else { if (turn%2 == 0) { options[playerInput1] = &quot;x&quot;; turn++; Board(); WinCondition(); Tie(); } else { options[playerInput1] = &quot;o&quot;; turn++; Board(); WinCondition(); Tie(); } /*int playerInput2; Console.WriteLine(&quot;o&quot;); bool torf2 = int.TryParse(Console.ReadLine(), out playerInput2); playerInput2--; if (torf2 &amp;&amp; playerInput2 &lt; 9 &amp;&amp; playerInput2 &gt; -1) { if (options[playerInput2] == &quot;x&quot; || options[playerInput2] == &quot;o&quot;) { Console.WriteLine(&quot;Stop stealing other people's space&quot;); } else { options[playerInput2] = &quot;o&quot;; Board(); WinCondition(); torf2 = false; torf = false; } }*/ } } else { Console.WriteLine(&quot;Please input a valid expression&quot;); } } } public static void Board() // makes the board { Console.Clear(); Console.WriteLine(&quot; | | &quot;); Console.WriteLine($&quot; {options[0]} | {options[1]} | {options[2]}&quot;); Console.WriteLine(&quot;_____|_____|_____ &quot;); Console.WriteLine(&quot; | | &quot;); Console.WriteLine($&quot; {options[3]} | {options[4]} | {options[5]}&quot;); Console.WriteLine(&quot;_____|_____|_____ &quot;); Console.WriteLine(&quot; | | &quot;); Console.WriteLine($&quot; {options[6]} | {options[7]} | {options[8]}&quot;); Console.WriteLine(&quot; | | &quot;); } public static void WinCondition() { if (options[0] == options[1] &amp;&amp; options[1] == options[2]) { Playing = false; if(turn % 2 == 0) { Console.WriteLine(&quot;Congrats on winning player 1, better luck next time player 2&quot;); } else { Console.WriteLine(&quot;Congrats on winning player 2, better luck next time player 1&quot;); } } else if (options[3] == options[4] &amp;&amp; options[4] == options[5]) { Playing = false; if(turn % 2 == 0) { Console.WriteLine(&quot;Congrats on winning player 1, better luck next time player 2&quot;); } else { Console.WriteLine(&quot;Congrats on winning player 2, better luck next time player 1&quot;); } } else if (options[6] == options[7] &amp;&amp; options[7] == options[8]) { Playing = false; if(turn % 2 == 0) { Console.WriteLine(&quot;Congrats on winning player 1, better luck next time player 2&quot;); } else { Console.WriteLine(&quot;Congrats on winning player 2, better luck next time player 1&quot;); } } // checks for horizontal wins else if (options[0] == options[3] &amp;&amp; options[3] == options[6]) { Playing = false; if(turn % 2 == 0) { Console.WriteLine(&quot;Congrats on winning player 1, better luck next time player 2&quot;); } else { Console.WriteLine(&quot;Congrats on winning player 2, better luck next time player 1&quot;); } } else if (options[1] == options[4] &amp;&amp; options[4] == options[7]) { Playing = false; if(turn % 2 == 0) { Console.WriteLine(&quot;Congrats on winning player 1, better luck next time player 2&quot;); } else { Console.WriteLine(&quot;Congrats on winning player 2, better luck next time player 1&quot;); } } else if (options[2] == options[5] &amp;&amp; options[5] == options[8]) { Playing = false; if(turn % 2 == 0) { Console.WriteLine(&quot;Congrats on winning player 1, better luck next time player 2&quot;); } else { Console.WriteLine(&quot;Congrats on winning player 2, better luck next time player 1&quot;); } } // checks for vertical wins else if (options[0] == options[4] &amp;&amp; options[4] == options[8]) { Playing = false; if(turn % 2 == 0) { Console.WriteLine(&quot;Congrats on winning player 1, better luck next time player 2&quot;); } else { Console.WriteLine(&quot;Congrats on winning player 2, better luck next time player 1&quot;); } } else if (options[2] == options[4] &amp;&amp; options[4] == options[6]) { Playing = false; if (turn%2 == 0) { Console.WriteLine(&quot;Congrats on winning player 1, better luck next time player 2&quot;); } else { Console.WriteLine(&quot;Congrats on winning player 2, better luck next time player 1&quot;); } } // checks for diagonal wins } public static void Intro() { Console.WriteLine(&quot;Welcome to\n&quot;); Console.WriteLine(@&quot;____________ ________ ________ &quot;); Console.WriteLine(@&quot;___ __/__(_)______ ___ __/_____ _______ ___ __/__________ &quot;); Console.WriteLine(@&quot;__ / __ /_ ___/________ / _ __ `/ ___/________ / _ __ \ _ \&quot;); Console.WriteLine(@&quot;_ / _ / / /__ _/_____/ / / /_/ // /__ _/_____/ / / /_/ / __/&quot;); Console.WriteLine(@&quot;/_/ /_/ \___/ /_/ \__,_/ \___/ /_/ \____/\___/ &quot;); Console.WriteLine(&quot;\n1.The game is played on a grid that's 3 squares by 3 squares.\n\n2.Player 1 is \&quot;X\&quot; and Player 2 is \&quot;O\&quot;. Players take turns putting their marks in empty squares.\n\n3.The first player to get 3 of her marks in a row(horizontally, vertically or diagonally) is the winner.\n\n4.When all 9 squares are full, the game is over. If no player has 3 marks in a row, the game ends in a tie.\n\n5.You can put x or o in by typing the number you want to put it at&quot;); Console.ReadKey(false); Console.Clear(); } public static void Tie() { if (options[0] != &quot;1&quot; &amp;&amp; options[1]!= &quot;2&quot; &amp;&amp; options[2] != &quot;3&quot; &amp;&amp; options[3] != &quot;4&quot; &amp;&amp; options[4] != &quot;5&quot; &amp;&amp; options[5] != &quot;6&quot; &amp;&amp; options[6] != &quot;7&quot; &amp;&amp; options[7] != &quot;8&quot; &amp;&amp; options[8] != &quot;9&quot;) { Console.WriteLine(&quot;The game is a tie&quot;); Playing = false; } } } } </code></pre>
[]
[ { "body": "<p><strong>Choosing good identifiers</strong></p>\n<ul>\n<li><p>When I see a name like <code>options</code> I think of something a player can choose from like &quot;single player&quot; (i.e., play against the computer) or &quot;multiplayer&quot;. A better name would be <code>board</code> because that's what it is.</p>\n</li>\n<li><p><code>torf</code>? Does it mean &quot;true or false&quot;? Every Boolean is true or false. This does not reflect the meaning it has in this context. Better: <code>isValidInt</code>. But I would inline this variable (see later).</p>\n</li>\n<li><p><code>Board()</code>. A board is a thing, but here it stands for an action. Better <code>PrintBoard()</code>. Same for <code>PrintIntro()</code>.</p>\n</li>\n<li><p>The field <code>Playing</code> starts with an upper case and is therefore said to be PascalCase. This is reserved for type names, method names and property names. Use camelCase for fields, parameters and variables.\nSee <a href=\"https://github.com/ktaranov/naming-convention/blob/master/C%23%20Coding%20Standards%20and%20Naming%20Conventions.md\" rel=\"nofollow noreferrer\">C# Coding Standards and Naming Conventions</a> for a full list.</p>\n</li>\n</ul>\n<p><strong>Logic and structure can be simplified and clarified.</strong></p>\n<ul>\n<li><p>At many places you calculate <code>turn % 2 == 0</code>. Instead, I suggest directly calculating the player number. We would declare <code>static int player = 0;</code> and a method getting the next player as well as a method switching between players</p>\n<pre><code>private static int NextPlayer()\n{\n return 1 - player;\n}\n\nprivate static void SwitchPlayer()\n{\n player = NextPlayer();\n}\n</code></pre>\n</li>\n<li><p>This leads to another simplification. The first if-else statement can be replaced by (I am using <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/string-interpolation\" rel=\"nofollow noreferrer\">string interpolation</a> here)</p>\n<pre><code>Console.WriteLine($&quot;Player {player + 1}'s turn&quot;); // Display player as 1-based number.\n</code></pre>\n</li>\n<li><p>I would inline the variable you called <code>torf</code> and declare <code>playerInput</code> in a <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#out-variables\" rel=\"nofollow noreferrer\">out variable declaration</a> like this.</p>\n<pre><code>if (Int32.TryParse(Console.ReadLine(), out int playerInput) &amp;&amp; \n playerInput is &gt;= 1 and &lt;= 9)\n{\n playerInput--; // Make it a 0-based index.\n ...\n}\n</code></pre>\n<p>I used <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements\" rel=\"nofollow noreferrer\">pattern matching</a> to test if the value is in a valid range. But you can replace it by a classic Boolean expression if you prefer or if you are using a pre C# 9.0 version.</p>\n</li>\n<li><p>You differentiate two cases doing the same with a small exception (shown with the new identifiers):</p>\n<pre><code>if (player == 0) {\n board[playerInput] = &quot;x&quot;;\n SwitchPlayer();\n\n PrintBoard();\n WinCondition();\n Tie();\n} else {\n board[playerInput] = &quot;o&quot;;\n SwitchPlayer();\n\n PrintBoard();\n WinCondition();\n Tie();\n}\n</code></pre>\n<p>This can easily be simplified by declaring a new field <code>playerMark</code> as array. Since we're at it, we can do the same for player names. This saves us the base-0 to base-1 conversion of player numbers for display and could easily be extended to store real names.</p>\n<pre><code>static readonly char[] playerMark = { 'x', 'o' };\nstatic readonly string[] playerName = { &quot;1&quot;, &quot;2&quot; };\n</code></pre>\n<p>It becomes</p>\n<pre><code>board[playerInput] = playerMark[player];\nPrintBoard();\nWinCondition();\nTie();\nSwitchPlayer(); // Doing this after printing winner!\n</code></pre>\n<p>Even without this new static field, you could move all but the first line out of the if-else statement, since they are exactly the same in both cases:</p>\n<pre><code>if (player == 0) {\n board[playerInput] = 'x';\n} else {\n board[playerInput] = 'o';\n}\nPrintBoard();\nWinCondition();\nTie();\nSwitchPlayer();\n</code></pre>\n</li>\n<li><p>The <code>WinCondition</code> method tests conditions and prints to the console. And it does so by repeating the same print statements over and over. Better separate the two concerns.</p>\n<pre><code>private static bool IsWinCondition()\n{\n return\n board[0] == board[1] &amp;&amp; board[1] == board[2] ||\n board[3] == board[4] &amp;&amp; board[4] == board[5] ||\n board[6] == board[7] &amp;&amp; board[7] == board[8] ||\n board[0] == board[3] &amp;&amp; board[3] == board[6] ||\n board[1] == board[4] &amp;&amp; board[4] == board[7] ||\n board[2] == board[5] &amp;&amp; board[5] == board[8] ||\n board[0] == board[4] &amp;&amp; board[4] == board[8] ||\n board[2] == board[4] &amp;&amp; board[4] == board[6];\n }\n}\n</code></pre>\n<p>and call it with (yet another simplification here)</p>\n<pre><code>if (IsWinCondition()) {\n playing = false;\n Console.WriteLine(\n $&quot;Congrats player {playerName[player]}, better luck next time player {playerName[NextPlayer()]}&quot;);\n}\n</code></pre>\n</li>\n<li><p>Same issue as above with <code>Tie</code>. Also, it does not test whether we have a tie but only if the board is full. We only have a tie if we do not have a win situation at the same time. Therefore, I changed the method to (requires a <code>using System.Linq;</code> before the namespace)</p>\n<pre><code>private static bool IsBoardFull()\n{\n return board.All(square =&gt; square &gt; '9'); // Because 'x' and 'o' are greater\n}\n</code></pre>\n<p>To make this work I changed the type of <code>board</code> and <code>playerMark</code> to <code>char[]</code>. <code>char</code> is considered to be a numeric type in C# and can be compared like numbers. (You must change the corresponding double quotes to single quotes.)</p>\n<p>See: <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.all?f1url=%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(System.Linq.Enumerable.All%60%601);k(DevLang-csharp)%26rd%3Dtrue&amp;view=net-5.0\" rel=\"nofollow noreferrer\">Enumerable.All</a> extension method.</p>\n<p>The conditions then become</p>\n<pre><code>if (IsWinCondition()) {\n playing = false;\n Console.WriteLine(\n $&quot;Congrats player {playerName[player]}, better luck next time player {playerName[NextPlayer()]}&quot;);\n} else if (IsBoardFull()) {\n playing = false;\n Console.WriteLine(&quot;The game is a tie&quot;);\n}\n</code></pre>\n</li>\n<li><p>Now <code>playing</code> can be made a local variable since it is not used or set in other methods</p>\n<pre><code>bool playing = true; //stops the game once someone wins\nwhile (playing) //is to stop the game once someone wins\n{\n ...\n}\n</code></pre>\n</li>\n</ul>\n<p><strong>The full solution</strong> (without the enclosing namespace and class):</p>\n<pre><code>static char[] board = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; //stores the variables to change\nstatic readonly char[] playerMark = { 'x', 'o' };\nstatic readonly string[] playerName = { &quot;1&quot;, &quot;2&quot; };\nstatic int player = 0;\n\npublic static void Main()\n{\n PrintIntro();\n PrintBoard();\n bool playing = true; // Stops the game once someone wins\n while (playing)\n {\n Console.WriteLine($&quot;Player {playerName[player]}'s turn&quot;);\n\n Console.WriteLine(&quot;Please, type in your response: &quot;);\n if (int.TryParse(Console.ReadLine(), out int playerInput) &amp;&amp; playerInput is &gt;= 1 and &lt;= 9) {\n playerInput--; // Make it a 0-based index.\n if (board[playerInput] is 'x' or 'o') {\n Console.WriteLine(&quot;Stop stealing other people's place&quot;);\n } else {\n board[playerInput] = playerMark[player];\n PrintBoard();\n if (IsWinCondition()) {\n playing = false;\n Console.WriteLine(\n $&quot;Congrats player {playerName[player]}, better luck next time player {playerName[NextPlayer()]}&quot;);\n } else if (IsBoardFull()) {\n playing = false;\n Console.WriteLine(&quot;The game is a tie&quot;);\n }\n SwitchPlayer();\n }\n } else {\n Console.WriteLine(&quot;Please input a valid expression&quot;);\n }\n }\n}\n\nprivate static int NextPlayer()\n{\n return 1 - player;\n}\n\nprivate static void SwitchPlayer()\n{\n player = NextPlayer();\n}\n\nprivate static bool IsBoardFull()\n{\n return board.All(square =&gt; square &gt; '9');\n}\n\nprivate static bool IsWinCondition()\n{\n return\n board[0] == board[1] &amp;&amp; board[1] == board[2] ||\n board[3] == board[4] &amp;&amp; board[4] == board[5] ||\n board[6] == board[7] &amp;&amp; board[7] == board[8] ||\n board[0] == board[3] &amp;&amp; board[3] == board[6] ||\n board[1] == board[4] &amp;&amp; board[4] == board[7] ||\n board[2] == board[5] &amp;&amp; board[5] == board[8] ||\n board[0] == board[4] &amp;&amp; board[4] == board[8] ||\n board[2] == board[4] &amp;&amp; board[4] == board[6];\n}\n\nprivate static void PrintBoard() // makes the board\n{\n Console.Clear();\n\n Console.WriteLine(&quot; | | &quot;);\n Console.WriteLine($&quot; {board[0]} | {board[1]} | {board[2]}&quot;);\n Console.WriteLine(&quot;_____|_____|_____ &quot;);\n Console.WriteLine(&quot; | | &quot;);\n Console.WriteLine($&quot; {board[3]} | {board[4]} | {board[5]}&quot;);\n Console.WriteLine(&quot;_____|_____|_____ &quot;);\n Console.WriteLine(&quot; | | &quot;);\n Console.WriteLine($&quot; {board[6]} | {board[7]} | {board[8]}&quot;);\n Console.WriteLine(&quot; | | &quot;);\n}\n\nprivate static void PrintIntro()\n{\n // ...\n}\n</code></pre>\n<p><strong>Additional thought</strong></p>\n<p>You are storing the game board in a one-dimensional array. There exist <a href=\"https://en.wikipedia.org/wiki/Tic-tac-toe#Variations\" rel=\"nofollow noreferrer\">variations of Tic-tac-toe</a> having more rows and columns. Using a 2-d array would make the game more extensible, because this would allow testing win conditions and printing the board by simply iterating rows and columns. Now we use a manually composed win condition. This is okay as the board is very small. But doing this on lager boards would be both tedious and error prone.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-27T13:57:29.147", "Id": "506441", "Score": "0", "body": "My solution calls `SwitchPlayer` at exactly one place and produces alternately the player numbers 0 and 1 as expected. `(player + 1) % 2` (or `player = 1 - player`) is necessary: when player is 0, it produces 1 and when player is 1 it produces 0. So, I don't know what you mean by \"not usable\" and \"tweaked everywhere\". Also, there is no \"off by one\" dilemma in the logic. Only for display one is added. But you are right that for display we could use a data based approach; however, I would simply use an array: `string playerName = { \"one\", \"two\" }`. Get name with `playerName[player]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-27T14:00:39.650", "Id": "506442", "Score": "0", "body": "We would print the player numbers with `Console.WriteLine($\"Congrats player {playerName[player]}, better luck next time player {playerName[1 - player]}\");`. (We still have to use the `1 - player` trick to get the other player.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T16:52:06.723", "Id": "506579", "Score": "0", "body": "`1 - player` is necessary : `Player` is a simple variable but how it must be tweaked all over the place is a code smell. Make a `Player` class so a client has methods like `nextPlayer`, `currentPlayer`, `otherPlayer`. Small code exercises like TTT don't \"motivate\" using \"tiny, pointless\" classes. It may be tiny, but far from pointless, As code grows, complexity easily gets out of control where there is nothing to build upon, so to speak; without encapsulation and abstraction that starts at the core." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-01T17:53:42.037", "Id": "506589", "Score": "0", "body": "Yes, we could also create a `Game` class, a `Board` class, use interfaces etc. I suggested already a lot of improvements. I fear that further refactorings might be overwhelming for a beginner. Maybe classes (except static ones) and objects were not yet the subject of his lessons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-03T03:30:03.860", "Id": "506737", "Score": "1", "body": "I grok the concern for over-enthusiasm in answers. Certainly your answer reflects this concern with player code tweaks complementing the measured (C#) language feature and program flow changes. I want to convey the impetus for thinking about a player class in context . I mean to observe, not critique. I am commenting rather than answering the OP because I can see the implementation being too disruptive." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T15:39:20.513", "Id": "256414", "ParentId": "256411", "Score": "14" } }, { "body": "<p>In this review let me try to focus on the longest part of your code: <code>WinCondition</code>.</p>\n<ul>\n<li>Try to separate condition checks from user interaction, do not mix them</li>\n<li>Try to use better naming, like: <code>CheckVictory</code>, <code>HasAWinner</code>, <code>HasGameEnded</code>, etc.</li>\n<li>Try to separate data and logic during condition checks</li>\n</ul>\n<p>When they are not separated</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var conditions = new List&lt;bool&gt;\n{\n // checks for horizontal wins\n options[0] == options[1] &amp;&amp; options[1] == options[2],\n options[3] == options[4] &amp;&amp; options[4] == options[5],\n options[6] == options[7] &amp;&amp; options[7] == options[8],\n // checks for vertical wins\n options[0] == options[3] &amp;&amp; options[3] == options[6],\n options[1] == options[4] &amp;&amp; options[4] == options[7],\n options[2] == options[5] &amp;&amp; options[5] == options[8],\n // checks for diagonal wins\n options[0] == options[4] &amp;&amp; options[4] == options[8],\n options[2] == options[4] &amp;&amp; options[4] == options[6]\n\n};\n\nreturn conditions.FirstOrDefault(condition =&gt; condition));\n</code></pre>\n<p>When they are separated</p>\n<pre class=\"lang-cs prettyprint-override\"><code>//Data\nvar horizontalMarks = new List&lt;(int, int, int)&gt;\n{\n (0, 1, 2),\n (3, 4, 5),\n (6, 7, 8)\n};\n\nvar verticalMarks = new List&lt;(int, int, int)&gt;\n{\n (0, 3, 6),\n (1, 4, 7),\n (2, 5, 8)\n};\n\nvar diagonalMarks = new List&lt;(int, int, int)&gt;\n{\n (0, 4, 8),\n (2, 4, 6)\n};\nvar marks = horizontalMarks.Union(verticalMarks).Union(diagonalMarks);\n\n//Logic\nbool hasAWinner = false;\nforeach (var (first, second, third) in marks)\n{\n //If all data in this three positions are the same then we have found a winner\n if (new[] {options[first], options[second], options[third]}.Distinct().Count() != 1) continue;\n hasAWinner = true;\n break;\n}\n\nreturn hasAWinner;\n</code></pre>\n<p>If you wish you can introduce a helper class instead of relying on ValueTuples.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T23:19:19.663", "Id": "506251", "Score": "1", "body": "That should be `(0, 3, 6)` on the first line after `var verticalMarks`, but I doubt that this is easier to read/maintain regardless. If you're doing this because it's more general (and e.g. can be extended to an NxN board), one can directly search on the rows, columns, and diagonals using standard for loops. For a new programmer, it might even be useful practice with the modulo and integer division operations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-25T07:07:03.573", "Id": "506260", "Score": "0", "body": "@YonatanN Thanks I've fixed that line. Please feel free to post an answer with your proposed solution." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T16:45:49.010", "Id": "256415", "ParentId": "256411", "Score": "7" } }, { "body": "<p>Olivier Jacot-Descombes already gave some really good feedback. I want to go on from his solution. You're only using static methods, which is basically procedural programing. C# has a strong support from object-oriented programming, and I want to show you, how you might introduce it to your program.</p>\n<p>In OOP, you store data that belongs together in an object. You don't give direct access to this data, but rather have some methods that help you to manipulate the objects state.</p>\n<p>In your case, it is quite natural to introduce an object that represents the game board. I also introduce an enum to mark the state of each field instead of storing it in strings. The class for your object might look like this:</p>\n<pre><code>public enum FieldValue\n{\n Unmarked,\n MarkedByPlayer1,\n MarkedByPlayer2\n}\n\npublic class Gameboard\n{\n private FieldValue[] fields = new FieldValue[9];\n\n public FieldValue GetFieldValue(int col, int row)\n {\n return fields[col*3 + row];\n }\n\n public void SetFieldValue(int col, int row, FieldValue value)\n {\n fields[col*3 + row] = value;\n }\n\n public override string ToString()\n {\n StringBuilder sb = new StringBuilder();\n sb.AppendLine(&quot; | | &quot;);\n sb.AppendLine($&quot; {FieldValueToString(fields[0],0)} | {FieldValueToString(fields[1],1)} | {FieldValueToString(fields[2],2)}&quot;);\n sb.AppendLine(&quot;_____|_____|_____ &quot;);\n sb.AppendLine(&quot; | | &quot;);\n sb.AppendLine($&quot; {FieldValueToString(fields[3],3)} | {FieldValueToString(fields[4],4)} | {FieldValueToString(fields[5],5)}&quot;);\n sb.AppendLine(&quot;_____|_____|_____ &quot;);\n sb.AppendLine(&quot; | | &quot;);\n sb.AppendLine($&quot; {FieldValueToString(fields[6],6)} | {FieldValueToString(fields[7],7)} | {FieldValueToString(fields[8],8)}&quot;);\n sb.AppendLine(&quot; | | &quot;);\n return sb.ToString();\n }\n\n private string FieldValueToString(FieldValue fieldValue, int index)\n {\n return fieldValue switch\n {\n FieldValue.Unmarked =&gt; index.ToString(),\n FieldValue.MarkedByPlayer1 =&gt; &quot;X&quot;,\n FieldValue.MarkedByPlayer2 =&gt; &quot;O&quot;\n _ =&gt; &quot;&quot;\n };\n }\n\n public void Clear() // you can use this method if you want to use your GameBoard object for several games\n {\n for(int i = 0; i &lt; fields.Length; i++)\n {\n fields[i] = FieldStatus.Unmarked;\n }\n }\n\n public bool IsBoardFull()\n {\n return fields.All(x =&gt; x != FieldValue.Unmarked);\n }\n\n public bool IsWinner(int player)\n {\n FieldValue winnerValue = player == 1 ? FieldValue.MarkedByPlayer1 : FieldValue.MarkedByPlayer2;\n List&lt;(int,int,int)&gt; colsAndRows = new List&lt;(int,int,int)&gt;();\n colsAndRows.Add((0,1,2));\n colsAndRows.Add((3,4,5));\n colsAndRows.Add((6,7,8));\n colsAndRows.Add((0,3,6));\n colsAndRows.Add((1,4,7));\n colsAndRows.Add((2,5,8));\n colsAndRows.Add((0,4,8));\n colsAndRows.Add((2,4,6));\n foreach(var colOrRow in colsAndRows)\n {\n if(fields[colOrRow.Item1] == winnerValue &amp;&amp;\n fields[colOrRow.Item2] == winnerValue &amp;&amp;\n fields[colOrRow.Item3] == winnerValue)\n {\n return true;\n }\n }\n return false;\n }\n}\n</code></pre>\n<p>You can use this class by adding</p>\n<pre><code>private static GameBoard gameBoard = new GameBoard();\n</code></pre>\n<p>in your <code>Program</code> class an call its method. For example, the <code>PrintBoard()</code> method would become:</p>\n<pre><code>private static void PrintBoard() // makes the board\n{\n Console.Clear();\n Console.WriteLine(gameBoard.ToString());\n}\n</code></pre>\n<p>All of this results in a separation of concerns: You have your <code>Program</code> class, which reads input from the user, displays information on the screen and manages the player's turns. You also have the <code>GameBoard</code> class, which stores the data, and delivers information about the game's state: Did a player win? Is another turn possible? You could even go on and put the logic, which player has the next turn into a separate class. Quite important is also, that this class has no reference to the <code>Console</code> class. That means you have a better separation between logic and UI: If you decide at some point, you don't want to have this class in a console, but a winforms or WPF application, you don't have to touch this class.</p>\n<p>Notice also that from outside of the class, one doesn't know that the information is stored in a one-dimensional array. From the outside, we only see the public methods, but not the fields, which are marked as private. If you want to change this to a two-dimensional array, you only have to modify your <code>GameBoard</code> class and can leave all the other classes unchanged. I just show you some of your methods how they might look with a two-dimensional array:</p>\n<pre><code>public class Gameboard\n{\n private const int size = 3;\n private FieldValue[,] fields = new FieldValue[size,size];\n\n public FieldValue GetFieldValue(int col, int row)\n {\n return fields[col,row];\n }\n\n public void SetFieldValue(int col, int row, FieldValue value)\n {\n fields[col,row] = value;\n }\n\n public bool IsWinner(int player)\n {\n FieldValue winnerValue = player == 1 ? FieldValue.MarkedByPlayer1 : FieldValue.MarkedByPlayer2;\n \n for(int i = 0; i &lt; size; i++)\n {\n // check columns\n if(gameBoard[i,0] == winnerValue &amp;&amp; gameBoard[i,1] == winnerValue &amp;&amp; gameBoard[i,2] == winnerValue)\n {\n return true;\n }\n\n // check rows\n if(gameBoard[0,i] == winnerValue &amp;&amp; gameBoard[1,i] == winnerValue &amp;&amp; gameBoard[2,i] == winnerValue)\n {\n return true;\n }\n }\n\n // check diagonals\n if(gameBoard[0,0] == winnerValue &amp;&amp; gameBoard[1,1] == winnerValue &amp;&amp; gameBoard[2,2] == winnerValue)\n {\n return true;\n }\n\n if(gameBoard[size,size] == winnerValue &amp;&amp; gameBoard[size-1,size-1] == winnerValue &amp;&amp; gameBoard[size-2,size-2] == winnerValue)\n {\n return true;\n }\n return false;\n }\n\n // implementation of ToString(), Clear(), and IsBoardFull() is left as an exercise to the reader\n}\n</code></pre>\n<p>From that, it is only a small step to a tic tac toe game with different game size (e.g. 5x5 fields)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-08T06:08:47.703", "Id": "256862", "ParentId": "256411", "Score": "2" } } ]
{ "AcceptedAnswerId": "256414", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-24T14:12:18.917", "Id": "256411", "Score": "9", "Tags": [ "c#", "beginner", "console", "tic-tac-toe" ], "Title": "Tic-Tac-Toe code using c#" }
256411