body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have a web server that can send websites, images, mp3 and other things and I was wondering how I could improve the code and make the server more efficient.</p> <pre><code>//this is where you enter the default file directories char *defaultDir1 = &quot;/Users/rowan/Desktop/webServer(Mac)/website/displaySite/&quot;; char *defaultDir2 = &quot;/Users/rowan/Desktop/webServer(Mac)/&quot;; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;string.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;errno.h&gt; #include &lt;pthread.h&gt; struct sockaddr_in sockaddr; char webFileDir[9000]; char servFileDir[9000]; #define THREAD_POOL_SIZE 200 #define BACKLOG 200 pthread_t thread_pool[THREAD_POOL_SIZE]; //creates a lock and unlock system for enqueue and dequeue pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //creates a sleep timer for the threads/does something until given a signal or condition. pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; struct node { int client_socket; struct node *next; }; typedef struct node node_t; node_t *head = NULL; node_t *tail = NULL; void enqueue(int client_socket) { node_t *newnode = malloc(sizeof(node_t)); //create node newnode-&gt;client_socket = client_socket; //assign client socket newnode-&gt;next = NULL; //add node to the end of the list if (tail == NULL) { //checks if there is nothing on the tail and if so adds a head head = newnode; } else { //if there is a tail then add a new node onto the tail tail-&gt;next = newnode; } tail = newnode; //this all basically creates a new node then moves it over over and over again until stopped } int dequeue() { if (head == NULL) return -1;//if the head is empty or nothing has been enqueued then return null if (head != NULL) { //else... int result = head-&gt;client_socket; node_t *temp = head; head = head-&gt;next; if (head == NULL) {tail = NULL;} free(temp); return result; } //this function removes everything off of the queue and returns the socket return 0; } int *handleClient(int pclientSock) { FILE *fpointer; char *findExtention; char *clientIP; char *endDir; int freadErr; int fsize; int bin; int readSock; char recvLine[2]; char fileDir[9000]; char recvLineGET[60]; char httpResponseReport[1000]; char *fileLine; char httpResponse[1000]; char *endOfPost; char fullResp[100000]; int checkSend; char *startDir; char *getEnd; int responseCode = 200; bzero(fileDir, sizeof(fileDir)); bzero(recvLineGET, sizeof(recvLineGET)); //get client ip int acceptSock = pclientSock; socklen_t addrSize = sizeof(struct sockaddr_in); getpeername(acceptSock, (struct sockaddr *)&amp;sockaddr, &amp;addrSize); clientIP = inet_ntoa(sockaddr.sin_addr); fullResp[0] = '\0'; //handles reading client http request while (1) { if ((readSock = read(acceptSock, recvLine, 1)) != 1) { perror(&quot;error reading from socket&quot;); //error 500: internal server error send(acceptSock, &quot;HTTP/1.1 500\r\n\r\n&quot;, 16, MSG_NOSIGNAL); bzero(recvLine, sizeof(recvLine)); bzero(fullResp, sizeof(fullResp)); close(acceptSock); return 0; } recvLine[1] = '\0'; strcat(fullResp, recvLine); if ((endOfPost = strstr(fullResp, &quot;\n&quot;)) != NULL) { break; } else if (readSock &lt; 0) { //perror(&quot;endOfHttpBody error&quot;); bzero(fullResp, sizeof(fullResp)); close(acceptSock); return 0; } bzero(recvLine, sizeof(recvLine)); } strcpy(fileDir, webFileDir); if ((getEnd = strstr(fullResp, &quot;HTTP&quot;)) == NULL) { perror(&quot;error reading from socket&quot;); bzero(fullResp, sizeof(fullResp)); //error 400: bad request send(acceptSock, &quot;HTTP/1.0 400\r\n\r\n&quot;, 16, MSG_NOSIGNAL); close(acceptSock); return 0; } strcpy(getEnd, &quot;&quot;); if ((startDir = strchr(fullResp, '/')) == NULL) { perror(&quot;this shouldnt happen .-.&quot;); printf(&quot;startDir: %s\n&quot;, startDir); //error 400: bad request send(acceptSock, &quot;HTTP/1.0 400\r\n\r\n&quot;, 16, MSG_NOSIGNAL); bzero(fullResp, sizeof(fullResp)); close(acceptSock); return 0; } //handles the file retrieving if ((endDir = strchr(startDir, ' ')) == NULL) { perror(&quot;endDir error&quot;); //error 500: internal server error send(acceptSock, &quot;HTTP/1.0 500\r\n\r\n&quot;, 16, MSG_NOSIGNAL); bzero(fileDir, sizeof(fileDir)); bzero(fullResp, sizeof(fullResp)); close(acceptSock); return 0; } strcpy(endDir, &quot;&quot;); //checks for requested directory if (strcmp(startDir, &quot;/&quot;) == 0) { findExtention = &quot;.html&quot;; strcpy(fileDir, webFileDir); strcat(fileDir, &quot;index.html&quot;); responseCode = 200; } else { if ((findExtention = strchr(startDir, '.')) == NULL) { perror(&quot;invalid webpage&quot;); findExtention = &quot;.html&quot;; strcpy(fileDir, servFileDir); strcat(fileDir, &quot;err404.html&quot;); responseCode = 404; } strcat(fileDir, startDir); } if ((fpointer = fopen(fileDir, &quot;rb&quot;)) != NULL) { fseek(fpointer, 0L, SEEK_END); fsize = ftell(fpointer); } else if (strcmp(startDir-1, &quot;/favicon.ico&quot;) == 0 &amp;&amp; access(fileDir, F_OK) != 0) { strcpy(fileDir, servFileDir); strcat(fileDir, &quot;favicon.ico&quot;); if (access(fileDir, F_OK) != 0) { printf(&quot;\n\n\nERROR: please do not delete the default favicon.ico file. the program will not work properly if it is deleted\n\n\n&quot;); //error 500: internal server error send(acceptSock, &quot;HTTP/1.0 500\r\n\r\n&quot;, 16, MSG_NOSIGNAL); exit(1); } if ((fpointer = fopen(fileDir, &quot;rb&quot;)) == NULL) { perror(&quot;fopen error&quot;); //error 500: internal server error send(acceptSock, &quot;HTTP/1.0 500\r\n\r\n&quot;, 16, MSG_NOSIGNAL); bzero(fullResp, sizeof(fullResp)); close(acceptSock); return 0; } fseek(fpointer, 0L, SEEK_END); fsize = ftell(fpointer); } else if (access(fileDir, F_OK) != 0) { perror(&quot;webpage doesnt exist&quot;); findExtention = &quot;.html&quot;; strcpy(fileDir, servFileDir); strcat(fileDir, &quot;err404.html&quot;); responseCode = 404; if ((fpointer = fopen(fileDir, &quot;r&quot;)) == NULL) { perror(&quot;fopen error&quot;); //error 500: internal server error send(acceptSock, &quot;HTTP/1.0 500\r\n\r\n&quot;, 16, MSG_NOSIGNAL); bzero(fullResp, sizeof(fullResp)); close(acceptSock); return 0; } fseek(fpointer, 0L, SEEK_END); fsize = ftell(fpointer); } fclose(fpointer); //sets the server http response if ((strcmp(findExtention, &quot;.jpeg&quot;)) == 0 || (strcmp(findExtention, &quot;.jpg&quot;)) == 0) { bin = 1; sprintf(httpResponse, &quot;HTTP/1.0 %d\r\nConnection: close\r\nContent-Type: image/jpeg\r\nContent-Length: %d\r\nContent-Transfer-Encoding: binary\r\n\r\n&quot;, responseCode, fsize); } else if ((strcmp(findExtention, &quot;.png&quot;)) == 0) { bin = 1; sprintf(httpResponse, &quot;HTTP/1.0 %d\r\nConnection: close\r\nContent-Type: image/png\r\nContent-Length: %d\r\nContent-Transfer-Encoding: binary\r\n\r\n&quot;, responseCode, fsize); } else if ((strcmp(findExtention, &quot;.ico&quot;)) == 0) { bin = 1; sprintf(httpResponse, &quot;HTTP/1.0 %d\r\nConnection: close\r\nContent-Type: image/x-icon\r\nContent-Length: %d\r\nContent-Transfer-Encoding: binary\r\n\r\n&quot;, responseCode, fsize); } else if ((strcmp(findExtention, &quot;.mp3&quot;)) == 0) { bin = 1; sprintf(httpResponse, &quot;HTTP/1.0 %d\r\nConnection: close\r\nContent-Type: audio/mpeg\r\nContent-length: %d\r\nContent-Transfer-Encoding: binary\r\n\r\n&quot;, responseCode, fsize); } else if ((strcmp(findExtention, &quot;.html&quot;)) == 0) { bin = 0; sprintf(httpResponse, &quot;HTTP/1.0 %d\r\nConnection: close\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n&quot;, responseCode, fsize); } else { strcpy(fileDir, &quot;err404.html&quot;); if ((fpointer = fopen(fileDir, &quot;r&quot;)) == NULL) { perror(&quot;fopen error&quot;); bzero(fullResp, sizeof(fullResp)); close(acceptSock); return 0; } fseek(fpointer, 0L, SEEK_END); fsize = ftell(fpointer); fclose(fpointer); bin = 0; sprintf(httpResponse, &quot;HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n&quot;, fsize); } strcpy(httpResponseReport, httpResponse); if (readSock &lt; 0) { perror(&quot;readsock is less than 0&quot;); //error 500: internal server error send(acceptSock, &quot;HTTP/1.0 500\r\n\r\n&quot;, 16, MSG_NOSIGNAL); bzero(fullResp, sizeof(fullResp)); bzero(fileDir, sizeof(fileDir)); bzero(httpResponseReport, sizeof(httpResponseReport)); bzero(httpResponse, sizeof(httpResponse)); close(acceptSock); return 0; } //checks if i need to read plaintext or binary if (bin == 0) { fpointer = fopen(fileDir, &quot;r&quot;); } else if (bin == 1) { fpointer = fopen(fileDir, &quot;rb&quot;); } if (fpointer == NULL) { perror(&quot;file open error&quot;); //error 500: internal server error send(acceptSock, &quot;HTTP/1.0 500\r\n\r\n&quot;, 16, MSG_NOSIGNAL); bzero(fullResp, sizeof(fullResp)); bzero(fileDir, sizeof(fileDir)); bzero(httpResponseReport, sizeof(httpResponseReport)); bzero(httpResponse, sizeof(httpResponse)); close(acceptSock); return 0; } //sends server http response to client fseek(fpointer, 0L, SEEK_END); fsize = ftell(fpointer); fclose(fpointer); //checks if i need to read plaintext or binary (again) if (bin == 0) { fpointer = fopen(fileDir, &quot;r&quot;); } else if (bin == 1) { fpointer = fopen(fileDir, &quot;rb&quot;); } if (fpointer == NULL) { perror(&quot;fopen error&quot;); //error 500: internal server error send(acceptSock, &quot;HTTP/1.0 500\r\n\r\n&quot;, 16, MSG_NOSIGNAL); bzero(fullResp, sizeof(fullResp)); bzero(fileDir, sizeof(fileDir)); bzero(httpResponse, sizeof(httpResponse)); bzero(httpResponseReport, sizeof(httpResponseReport)); close(acceptSock); return 0; } fileLine = malloc(fsize * sizeof(char)); while ((freadErr = fread(fileLine, fsize, fsize, fpointer)) &gt; 0); if (feof(fpointer) &lt; 0) { perror(&quot;fread error&quot;); //error 500: internal server error send(acceptSock, &quot;HTTP/1.0 500\r\n\r\n&quot;, 16, MSG_NOSIGNAL); bzero(fullResp, sizeof(fullResp)); bzero(fileDir, sizeof(fileDir)); bzero(httpResponseReport, sizeof(httpResponseReport)); bzero(httpResponse, sizeof(httpResponse)); close(acceptSock); return 0; } //set 5 second socket timeout struct timeval timeout; timeout.tv_sec = 15; timeout.tv_usec = 0; if (setsockopt(acceptSock, SOL_SOCKET, SO_SNDTIMEO, &amp;timeout, sizeof(timeout)) &lt; 0) { perror(&quot;setsockopt error&quot;); //error 500: internal server error send(acceptSock, &quot;HTTP/1.0 500\r\n\r\n&quot;, 16, MSG_NOSIGNAL); close(acceptSock); return 0; } while (1) { if ((checkSend = send(acceptSock, httpResponse, strlen(httpResponse), MSG_NOSIGNAL)) == -1) { break; } //send full response if ((checkSend = send(acceptSock, fileLine, fsize, MSG_NOSIGNAL)) == -1) { break; } sleep(1); } bzero(httpResponse, sizeof(httpResponse)); bzero(fullResp, sizeof(fullResp)); fclose(fpointer); close(acceptSock); free(fileLine); //handles the clearing of variables and logs client ip and requested directory printf(&quot;\nclient with the ip: %s has requested %s.\n&quot;, clientIP, fileDir);//added server response but i don't think i need it anymore bzero(fileDir, sizeof(fileDir)); bzero(httpResponseReport, sizeof(httpResponseReport)); return 0; } //assign work to each thread void *giveThreadWork() { while (1) { int pclient; pthread_mutex_lock(&amp;mutex); //makes thread wait until signaled while ((pclient = dequeue()) == -1) { pthread_cond_wait(&amp;condition_var, &amp;mutex); } pthread_mutex_unlock(&amp;mutex); handleClient(pclient); } } int main() { int clientSock; int sock; int portNum; int defaultOrNo; printf(&quot;\n\n\nWeb Server\nBy: Rowan Rothe\n\n\n&quot;); printf(&quot;would you like to use default directories (1 = yes, 0 = no): &quot;); scanf(&quot;%d&quot;, &amp;defaultOrNo); if (defaultOrNo == 0) { printf(&quot;enter the directory of the files to be served (with '/' at the end): &quot;); scanf(&quot;%s&quot;, webFileDir); printf(&quot;enter the directory of the web server folder (with '/' at the end): &quot;); scanf(&quot;%s&quot;, servFileDir); } else if (defaultOrNo == 1) { strcpy(webFileDir, defaultDir1); strcpy(servFileDir, defaultDir2); } printf(&quot;what port would you like to host the site on?: &quot;); scanf(&quot;%d&quot;, &amp;portNum); sock = socket(AF_INET, SOCK_STREAM, 0); if (sock &lt; 0) { perror(&quot;sock error&quot;); } sockaddr.sin_family = AF_INET; sockaddr.sin_addr.s_addr = htonl(INADDR_ANY); sockaddr.sin_port = htons(portNum); if ((bind(sock, (struct sockaddr *) &amp;sockaddr, sizeof(sockaddr))) &lt; 0) { perror(&quot;bind error&quot;); exit(1); } printf(&quot;socket bind success\n&quot;); //create all the threads for the thread pool for (int i = 0; i &lt; THREAD_POOL_SIZE; i++) { pthread_create(&amp;thread_pool[i], NULL, giveThreadWork, NULL); } printf(&quot;created thread pool of size %d successfully\n&quot;, THREAD_POOL_SIZE); if ((listen(sock, BACKLOG)) &lt; 0) { perror(&quot;listen error&quot;); } printf(&quot;listen success\n&quot;); while (1) { //checks for client connection if ((clientSock = accept(sock, NULL, NULL)) &lt; 0) { perror(&quot;accept error&quot;); } else { pthread_mutex_lock(&amp;mutex); enqueue(clientSock); pthread_cond_signal(&amp;condition_var); pthread_mutex_unlock(&amp;mutex); } } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T20:34:05.850", "Id": "534180", "Score": "1", "body": "[Related SO question](https://stackoverflow.com/q/70118629/1014587)." } ]
[ { "body": "<h1>Calling <code>strcat</code> in a loop is inefficient</h1>\n<p>The function <code>strcat</code> works the following way:</p>\n<p>It must first search the entire the destination string until it finds the terminating null character at the end. It then appends the source string.</p>\n<p>Therefore, calling the function <code>strcat</code> in a loop in order to append one character at a time is highly inefficient. This is because whenever you append a single character, it must search the entire destination string again for the terminating null character.</p>\n<p>If you want to add a single character at a time, then you should not use the function <code>strcat</code>, but should rather remember the position of the end of the string (for example using a pointer or by remembering the length of the string) and add the new character yourself, by overwriting the terminating null character with that character. You can add a new terminating null character at the end of the string after you have finished adding all characters. Or, if you need the character sequence to be a valid null-terminated string after every intermediate step, then you can add a new null-terminating character after every character added.</p>\n<h1>System calls are expensive</h1>\n<p>The function <code>read</code> is not a simple function call. It is a <a href=\"https://en.wikipedia.org/wiki/System_call\" rel=\"nofollow noreferrer\">system call</a> which must be handled by the operating system's kernel. The overhead of this system call is probably somewhere between 1000 and 3000 CPU cycles. See <a href=\"https://stackoverflow.com/questions/23599074/system-calls-overhead\">this question</a> for more information. Also, see the comments section of my answer for some further comments regarding recent increase in system call overhead due to <a href=\"https://en.wikipedia.org/wiki/Meltdown_(security_vulnerability)\" rel=\"nofollow noreferrer\">Meltdown</a>/<a href=\"https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)\" rel=\"nofollow noreferrer\">Spectre</a> mitigations.</p>\n<p>Therefore, it is a big waste to call this function once for every single character, instead of attempting to read as much as you can at once, using a single system call.</p>\n<h1>Zeroing large amounts of memory is inefficient</h1>\n<p>You are using the function <code>bzero</code> to zero out large amounts of memory in several places in your program. It seems that you are zeroing out more than 100 KB of memory for every HTTP request.</p>\n<p>While it is not much of a problem to do this once at program startup, doing this for every HTTP request seems excessive.</p>\n<p>Also, it is unclear why you are zeroing out memory, in particular whether you are doing this</p>\n<ol>\n<li>to ensure that all strings are null-terminated, or</li>\n<li>to erase sensitive data, such as passwords.</li>\n</ol>\n<p>If it is #1, then there are other more efficient ways to ensure that strings are always null-terminated.</p>\n<p>If it is #2, then you should be using <a href=\"https://man7.org/linux/man-pages/man3/bzero.3.html\" rel=\"nofollow noreferrer\"><code>explicit_bzero</code></a> instead of <code>bzero</code>, because it is possible that <code>bzero</code> will be optimized away by the compiler.</p>\n<h1>Not guarding against buffer overflows</h1>\n<p>You don't seem to be guarding against <a href=\"https://en.wikipedia.org/wiki/Buffer_overflow\" rel=\"nofollow noreferrer\">buffer overflows</a> in your program. This means that a malicious client could crash your server by sending a request in which the first line is larger than <code>100 KB</code>.</p>\n<h1>This loop is inefficient</h1>\n<p>For the reasons stated in the previous 4 sections, this loop is inefficient and prone to a buffer overflow:</p>\n<pre><code>fullResp[0] = '\\0';\n//handles reading client http request\nwhile (1) {\n if ((readSock = read(acceptSock, recvLine, 1)) != 1) {\n //handle error (code omitted)\n }\n recvLine[1] = '\\0';\n strcat(fullResp, recvLine);\n if ((endOfPost = strstr(fullResp, &quot;\\n&quot;)) != NULL) {\n break;\n } else if (readSock &lt; 0) {\n //handle error (code omitted)\n }\n bzero(recvLine, sizeof(recvLine));\n}\n</code></pre>\n<p>Also, after every character added, you are searching the entire string again for the newline character, although it would only be necessary to check the last character added.</p>\n<p>However, since you are only processing a single line with this inefficient loop, it probably won't matter much. But if a (possibly malicious) client sends you a very long line, your server will spend a significant amount of time processing this line. This vulnerability could be used in a <a href=\"https://en.wikipedia.org/wiki/Denial-of-service_attack\" rel=\"nofollow noreferrer\">DoS attack</a> against your server.</p>\n<p>Also, the variable <code>readSock</code> does not seem appropriately named, as it implies that it contains the value of a socket file descriptor.</p>\n<p>An efficient version of the loop, which also protects against buffer overflow, would look like this:</p>\n<pre><code>//fullResp[0] = '\\0'; //this line is no longer needed\nsize_t offset = 0;\n\ndo {\n char *p_read_buf = fullResp + offset;\n size_t to_read = sizeof fullResp - offset - 1;\n\n if ( to_read == 0 ) {\n //handle error (code omitted)\n }\n\n if ( ( readSock = read( acceptSock, p_read_buf, to_read ) ) &lt;= 0 ) {\n //handle error (code omitted)\n }\n\n offset += readSock;\n\n} while ( ( endOfPost = memchr( p_read_buf, '\\n', readSock ) ) == NULL );\n\n//add null terminating character\nfullResp[offset] = '\\0';\n</code></pre>\n<h1>Rewind files instead of closing and reopening them</h1>\n<p>You seem to be opening files, in order to determine their length, and then closing them again, only to reopen them again shortly afterwards. This does not seem meaningful. You can use the function <a href=\"https://en.cppreference.com/w/c/io/rewind\" rel=\"nofollow noreferrer\"><code>rewind</code></a> to reset the file position indicator to the start of the file.</p>\n<h1>This loop seems to be buggy</h1>\n<p>The following loop appears to be buggy:</p>\n<pre><code>while (1) {\n if ((checkSend = send(acceptSock, httpResponse, strlen(httpResponse), MSG_NOSIGNAL)) == -1) {\n break;\n }\n\n //send full response\n if ((checkSend = send(acceptSock, fileLine, fsize, MSG_NOSIGNAL)) == -1) {\n break;\n }\n\n sleep(1);\n}\n</code></pre>\n<p>It is unclear what this loop is attempting to accomplish.</p>\n<p>You seem to be first sending the HTTP response header, then the HTTP response body. However, it is unclear why you are doing this in an infinite loop.</p>\n<p>Also, it should not be necessary to call <code>sleep(1)</code> in this loop. If your program does not behave properly without that call, then this is a sign of a bug in your program.</p>\n<p>My guess is that you need this wait in order to give the client time to close the connection, so that the first call to <code>send</code> in the second iteration of the loop fails, which causes the loop to break. Otherwise, if the client does not close the connection, you will send the HTTP response to the client in an infinite loop. However, this is not the proper way of solving the problem.</p>\n<p>The proper way to solve this is to not use an infinite loop:</p>\n<pre><code>//send HTTP response header\nsize_t len = strlen( httpReponse );\nif ( ( checkSend = send( acceptSock, httpResponse, len, MSG_NOSIGNAL) ) != len ) {\n //handle error (code omitted)\n}\n\n//send HTTP response body\nif ( ( checkSend = send(acceptSock, fileLine, fsize, MSG_NOSIGNAL ) ) != fsize ) {\n //handle error (code omitted)\n}\n</code></pre>\n<h1>Your usage of <code>fread</code> is wrong</h1>\n<p>The line</p>\n<pre><code>while ((freadErr = fread(fileLine, fsize, fsize, fpointer)) &gt; 0);\n</code></pre>\n<p>is wrong. You are instructing <a href=\"https://en.cppreference.com/w/c/io/fread\" rel=\"nofollow noreferrer\"><code>fread</code></a> to attempt to read <code>fsize</code> items each of size <code>fsize</code> bytes, i.e. a total of <code>fsize*fsize</code> bytes. Also, the <code>while</code> loop does not make sense.</p>\n<p>You should write either</p>\n<pre><code>if ( ( freadErr = fread( fileLine, fsize, 1, fpointer ) ) != 1 )\n{\n //handle error (code omitted)\n}\n</code></pre>\n<p>or this:</p>\n<pre><code>if ( ( freadErr = fread( fileLine, 1, fsize, fpointer ) ) != fsize )\n{\n //handle error (code omitted)\n}\n</code></pre>\n<h1>Your usage of <code>feof</code> is wrong</h1>\n<p>The line</p>\n<pre><code>if (feof(fpointer) &lt; 0) {\n</code></pre>\n<p>does not make sense.</p>\n<p>The function <a href=\"https://en.cppreference.com/w/c/io/feof\" rel=\"nofollow noreferrer\"><code>feof</code></a> will return a nonzero value (i.e. true) if the end-of-file indicator has been set on the stream, otherwise zero (i.e. false). Therefore, comparing the returned value with <code> &lt; 0</code> does not make sense.</p>\n<p>Also, the function <code>feof</code> does not check the file position indicator itself. Instead, it merely checks whether the end-of-file indicator on the stream has been set. This end-of-file indicator will only be set if a previous I/O function attempted to read past the end of the file. The end-of-file indicator will not be set if the file position indicator has merely reached the end of the file, so that the next input operation will fail.</p>\n<p>For this reason, it does not make sense to call <code>feof</code>. You should check the return value of the previous I/O operation instead (which you are already doing). Only if that I/O operation reports an error or does not read all of the requested input, will it make sense to call <code>feof</code> or <code>ferror</code> to determine the cause.</p>\n<h1>Redundant <code>if</code> statement</h1>\n<p>In the function</p>\n<pre><code>int dequeue() {\n if (head == NULL) return -1;//if the head is empty or nothing has been enqueued then return null\n\n\n if (head != NULL) { //else...\n int result = head-&gt;client_socket;\n node_t *temp = head;\n head = head-&gt;next;\n if (head == NULL) {tail = NULL;}\n free(temp);\n return result;\n }\n //this function removes everything off of the queue and returns the socket\n return 0;\n}\n</code></pre>\n<p>the second <code>if</code> statement is redundant and the <code>return 0</code> in the last line is unreachable. You can simply write:</p>\n<pre><code>int dequeue() {\n if (head == NULL) return -1;//if the head is empty or nothing has been enqueued then return null\n\n int result = head-&gt;client_socket;\n node_t *temp = head;\n head = head-&gt;next;\n if (head == NULL) {tail = NULL;}\n free(temp);\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T06:27:50.240", "Id": "534198", "Score": "2", "body": "System calls are somewhat more expensive even than that 2017 benchmark showed: Modern systems do Spectre mitigation before entering the kernel; for example Intel microcode updates added a way to flush branch-predictor history. (The API is to make later branches not influenced by previous branch history or something; the implementation is somewhat slow especially on CPUs designed before Spectre was even discovered, so they didn't have HW already designed to make that cheaper.) So that extra absolute time raises the relative cost significantly for very cheap/simple syscalls. ~600 cycles?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T06:28:54.017", "Id": "534199", "Score": "0", "body": "Some experiments in [Does the Meltdown mitigation, in combination with \\`calloc()\\`s CoW \"lazy allocation\", imply a performance hit for calloc()-allocated memory?](https://stackoverflow.com/a/50196439) in early 2018 re: soft page-fault cost; things may well have changed again since then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T16:25:58.233", "Id": "534226", "Score": "0", "body": "@PeterCordes: Thanks for your comments. I have modified my answer to refer to them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:35:25.603", "Id": "534249", "Score": "0", "body": "@AndreasWenzel, How does ```p_read_buf``` get copied to fullResp?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:40:25.733", "Id": "534251", "Score": "1", "body": "@logsInMyEyes69: It doesn't. The pointer `p_read_buf` points inside `fullResp`. It is initialized to point to the start of the unwritten area of `fullResp`. In the first loop iteration, it points to the start of `fullResp`; in subsequent loop iterations, it points one character after the last character written by `read` in the previous loop iteration, which is where the function `read` should continue writing and where `memchr` should start searching for the newline character after the `read` call. There is no need for `memchr` to search all of `fullResp` in every loop iteration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:50:23.553", "Id": "534252", "Score": "0", "body": "Also with the buggy loop, if I don't include it, the client doesn't receive the data and says \"connection closed while page was loading\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:53:45.260", "Id": "534253", "Score": "0", "body": "@logsInMyEyes69: That is strange. Maybe the client aborts the connection if it receives unexpected additional data, due to you sending the HTTP response an infinite number of times in your loop. Does it work if you replace it with my code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:55:06.437", "Id": "534254", "Score": "0", "body": "No, it doesn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:55:59.953", "Id": "534255", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/131883/discussion-between-andreas-wenzel-and-logsinmyeyes69)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T17:34:37.953", "Id": "270469", "ParentId": "270459", "Score": "18" } }, { "body": "<p>I didn't read the whole code thing, just looked at some parts. Also, Andreas already mentioned some of the major things, like making one system call per byte being a performance disaster.</p>\n<hr />\n<p>Some of those local arrays, especially <code>char fullResp[100000];</code>, are a bit large to keep on the stack. Most mainstream systems give you at least 1MiB of stack space (e.g. Windows, with Linux defaulting to a <code>ulimit -s</code> of 8MiB which pthreads uses when allocating thread stacks). So 100k is fine here, where that's the only really big thing, and you don't have a large stack depth of other function calls.</p>\n<p>Since this is multithreaded, you can't just make it <code>static</code>, although you could in theory make it thread-local static like <code>static __thread char fullResp[100000];</code>. But if you want to avoid stack space, probably better to dynamically allocate it with <code>calloc</code>/<code>free</code>. But you'd probably want to avoid alloc/free on every request, perhaps allocating the buffer in <code>giveThreadWork</code> and passing it as an arg to <code>handleClient</code> (although that's a pretty ugly optimization). 100k is small enough that it's not painful for each thread to keep that much allocated. (If you never make a huge response, some of those pages will never be dirtied, if you avoid naive <code>bzero</code> of the whole thing.)</p>\n<hr />\n<p><code>strstr(fullResp, &quot;\\n&quot;)</code> is very silly. <code>strchr</code> is specifically optimized for searching for a single char. Or better, keep track of the used length in the buffer so you can avoid <code>str</code> functions that scan from the beginning every time. Actually, this is inside your loop that reads and appends 1 char at a time inefficiently (as discussed in @Andreas Wenzel's answer) with <code>strcat</code>, so you could just be checking <code>recvLine[0] == '\\n'</code>.</p>\n<p>You assign the <code>strstr</code> return value to <code>endOfPost</code> but never use that variable (except in the <code>if( (endOfPost = strstr()) )</code> where it's assigned), so it should be removed.</p>\n<p>For cases where you do actually want to concatenate multiple strings whose length isn't known to be 1, you can use POSIX / GNU <code>stpcpy</code>.</p>\n<p>Unfortunately ISO C <code>str</code> functions all suck and don't help you avoid redundant work scanning for a terminating <code>0</code> in the string. e.g. <code>strcpy</code> and <code>strcat</code> return the start of the string, not the new end. And <code>strlen</code> + <code>memcpy</code> would scan the source string twice. See <a href=\"https://stackoverflow.com/questions/3561427/strcpy-return-value/51547604#51547604\">strcpy() return value</a> for some C ancient history about where those poorly designed functions came from, and details about <code>stpcpy</code>.</p>\n<hr />\n<pre><code> //handles the file retrieving\n if ((endDir = strchr(startDir, ' ')) == NULL) {\n perror(&quot;endDir error&quot;);\n</code></pre>\n<p><code>strchr</code> doesn't set <code>errno</code>; there's no meaningful strerror() error string that perror can append to this. It will either be &quot;: Success&quot; or some old error code.</p>\n<hr />\n<p><strong>It's redundant to check <code>access(fileDir, F_OK)</code> if you're about to open it</strong> (like in the favico fallback path), <strong>or after a failed <code>fopen()</code></strong>. If you want to know why an open failed, check <code>errno</code>. On POSIX systems, <code>fopen()</code> failure is guaranteed to set <code>errno</code> as <code>open()</code> would have (<a href=\"https://en.cppreference.com/w/c/io/fopen\" rel=\"noreferrer\">cppreference</a>). So use <code>strerror</code> or copy <code>errno</code> early, before doing other system calls that might overwrite errno again.</p>\n<p>Your use of <code>access</code> introduces a TOCTOU problem (Time-of-check vs. Time-of-use). The file could be deleted, created, or change permission, between fopen() and access().</p>\n<p>If you're checking before open, opening can still fail. That makes it hard to test the failed-open path of execution because it normally doesn't happen. Also as <a href=\"https://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c#comment98168_230068\">discussed on SO</a>, <code>access</code> uses your &quot;real&quot; UID/GID, not the current effective UID/GID, which matters for setuid root programs. (Such as a web server that opens port 80 and then drops root privileges.)</p>\n<hr />\n<p><strong>Instead of fseek/ftell (+ rewind) to find file length, use POSIX <code>fstat</code></strong> (With a file descriptor from <code>fileno</code> if you want to keep using C stdio). Your code is already using POSIX pthreads and the POSIX socket API, so other POSIX functions are fine. (Although arguably you could keep the threading part OS-specific or switch to <a href=\"http://threads.h\" rel=\"noreferrer\">C11 <code>thread.h</code></a> and keep the rest of the code using pure ISO C as much as possible.)</p>\n<p>But <code>fseek/ftell</code> <a href=\"https://stackoverflow.com/questions/55826796/ftell-fseek-is-different-from-the-actual-readable-data-length-in-a-sys-class-fi/55828019#55828019\">isn't portably guaranteed</a> to give you file lengths. (That SO link correctly explains why, despite not being the answer to the question it's posted under.) , <code>ftell</code> on a binary stream isn't guaranteed to be the length you can actually read, and <code>ftell</code> on a non-binary stream is not guaranteed to have any particular meaning.<br />\nIt does happen to work (or is in fact well defined) on most systems, and is a common idiom.</p>\n<p>However, <strong><code>ftell</code> returns a <code>long</code> which is 32-bit on some systems</strong> (including 32-bit systems running Linux, and x86-64 Windows), so it won't handle large files correctly there. <code>ftello</code> returns an <code>off_t</code>, but as per <a href=\"https://stackoverflow.com/questions/8236/how-do-you-determine-the-size-of-a-file-in-c#comment123927082_37661250\">other discussion on SO</a>, <code>ftello</code> isn't available under that name on Windows despite being specified by ISO C.</p>\n<hr />\n<p><code>stat(2)</code> / <a href=\"https://man7.org/linux/man-pages/man2/lstat.2.html\" rel=\"noreferrer\"><code>fstat(2)</code></a> work fine on regular files, and you can probably assume you aren't serving up block device files (which do have a size, unlike a pipe or socket, but not one that <code>stat</code> reports.) Note that using <code>fstat</code> avoids some TOCTOU problems and is more efficient (only one path lookup by the kernel), but if the file length is changing while the server is running, reads could still eventually get more data from the file than the reported size.</p>\n<p>See <a href=\"https://stackoverflow.com/questions/238603/how-can-i-get-a-files-size-in-c/238644#238644\">How can I get a file's size in C?</a> on Stack Overflow.</p>\n<pre><code>#include &lt;sys/types.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;unistd.h&gt;\n\n struct stat buf;\n fstat(fileno(fp), &amp;buf);\n off_t size = buf.st_size;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T15:04:52.657", "Id": "534219", "Score": "0", "body": "In Windows you can use `_stat64` or `_ftelli64` but both of them are not portable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T15:10:54.023", "Id": "534220", "Score": "2", "body": "@jdt: Right, worth mentioning those by name here I guess, for possible future readers. Those were mentioned in one of the links in this answer. (With `_fstat64` and `_fileno`, I think?). The code in the question is already using many POSIX calls, so I didn't spend space in my answer describing how to actually port it to other OSes, just pointing out that the pure ISO C way doesn't help as much as you'd hope with portability so we might as well do it the POSIX way with `fstat`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T07:49:34.757", "Id": "270485", "ParentId": "270459", "Score": "6" } } ]
{ "AcceptedAnswerId": "270469", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T02:39:26.540", "Id": "270459", "Score": "11", "Tags": [ "performance", "c", "multithreading", "http" ], "Title": "Multi-threaded web server serving HTML, images, etc" }
270459
<p>This query is a part of Conway’s game of life. Currently, this program takes about 70 lines of code in Python to return the functionality of the game, which can be simplified to fewer lines of code and it ends when a keyboard interrupt occurs. I eventually want to eliminate the keyboard interrupt and improve this code with maybe a try and except function to have the game show a message stating that it is over. Any recommendations for cleaning this code up with maybe some additional functions?</p> <blockquote> <p>Like any game, there are rules! Here's a quick overview. At the heart of this game are four rules that determine if a cell is live or dead. It all depends on how many of that cell's neighbors are alive.</p> <ol> <li>Births: Each dead cell adjacent to exactly three live neighbors will become live in the next generation.</li> <li>Death by isolation: Each live cell with one or fewer live neighbors will die in the next generation.</li> <li>Death by overcrowding: Each live cell with four or more live neighbors will die in the next generation.</li> <li>Survival: Each live cell with either two or three live neighbors will remain alive for the next generation.</li> </ol> <p>Rules apply to all cells at the same time.</p> </blockquote> <pre><code># Conway's Game of Life import random import time import copy WIDTH = 60 HEIGHT = 20 # Create a list of list for the cells: nextCells = [] for x in range(WIDTH): column = [] # Create a new column. for y in range(HEIGHT): if random.randint(0, 1) == 0: column.append('#') # Add a living cell. else: column.append(' ') # Add a dead cell. nextCells.append(column) # nextCells is a list of column lists. while True: # Main program loop. print('\n\n\n\n\n') # Separate each step with newlines. currentCells = copy.deepcopy(nextCells) # Print currentCells on the screen: for y in range(HEIGHT): for x in range(WIDTH): print(currentCells[x][y], end='') # Print the # or space. print() # Print a newline at the end of the row. # Calculate the next step's cells based on current step's cells: for x in range(WIDTH): for y in range(HEIGHT): # Get neighboring coordinates: # `% WIDTH` ensures leftCoord is always between 0 and WIDTH - 1 leftCoord = (x - 1) % WIDTH rightCoord = (x + 1) % WIDTH aboveCoord = (y - 1) % HEIGHT belowCoord = (y + 1) % HEIGHT # Count number of living neighbors: numNeighbors = 0 if currentCells[leftCoord][aboveCoord] == '#': numNeighbors += 1 # Top-left neighbor is alive. if currentCells[x][aboveCoord] == '#': numNeighbors += 1 # Top neighbor is alive. if currentCells[rightCoord][aboveCoord] == '#': numNeighbors += 1 # Top-right neighbor is alive. if currentCells[leftCoord][y] == '#': numNeighbors += 1 # Left neighbor is alive. if currentCells[rightCoord][y] == '#': numNeighbors += 1 # Right neighbor is alive. if currentCells[leftCoord][belowCoord] == '#': numNeighbors += 1 # Bottom-left neighbor is alive. if currentCells[x][belowCoord] == '#': numNeighbors += 1 # Bottom neighbor is alive. if currentCells[rightCoord][belowCoord] == '#': numNeighbors += 1 # Bottom-right neighbor is alive. # Set cell based on Conway's Game of Life rules: if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3): # Living cells with 2 or 3 neighbors stay alive: nextCells[x][y] = '#' elif currentCells[x][y] == ' ' and numNeighbors == 3: # Dead cells with 3 neighbors become alive: nextCells[x][y] = '#' else: # Everything else dies or stays dead: nextCells[x][y] = ' ' time.sleep(1) # Add a 1-second pause to reduce flickering. </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T15:39:55.953", "Id": "534146", "Score": "1", "body": "'Eliminate the keyboard interrupt' and replace it with what?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T16:38:50.050", "Id": "534154", "Score": "0", "body": "Please try a 3by3 board primed with a \"blinker\" (3 cells alive: either middle row or column): Does it blink?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T17:06:54.970", "Id": "534157", "Score": "0", "body": "I'm tempted to make a cell have integer values, and 1 means alive, 0 means dead. This would make counting living neighbors clearer and possibly more compact by eliminating the need for `if` statements and just summing the neighboring cells." } ]
[ { "body": "<p><strong>Indentation</strong></p>\n<p>Please fix your code indentation, as it is now it's painful to figure out what's supposed to be happening. The comments provide the corect suggestions to make it easy for you as well.</p>\n<hr />\n<p><strong>CONSTANTS</strong></p>\n<p>The characters for living and dead cells should be module-level constants. Makes them easily changeable and the code more readable:</p>\n<pre><code>LIVING_CELL = '#'\nDEAD_CELL = ' '\nCELLS = (LIVING_CELL, DEAD_CELL)\n</code></pre>\n<hr />\n<p><strong><code>variable_names</code></strong></p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP8</a> states that variable and function names should follow <code>snake_case</code>.</p>\n<p><code>nextCells</code> -&gt; <code>next_cells</code></p>\n<hr />\n<p><strong>List creation</strong></p>\n<p><a href=\"https://www.w3schools.com/python/python_lists_comprehension.asp\" rel=\"nofollow noreferrer\">List comprehensions</a> are often times preferrable to manual list comprehensions. Consider this improved creation of <code>next_cells</code>:</p>\n<pre><code>import random\n\nnext_cells = []\n\nfor _ in range(WIDTH):\n column = [random.choice(CELLS) for _ in range(HEIGHT)]\n next_cells.append(column)\n</code></pre>\n<p>You might even go a step further and go for a nested comprehension:</p>\n<pre><code>next_cells = [[random.choice(CELLS) for _ in range(HEIGHT)] for _ in range(WIDTH)]\n</code></pre>\n<p>I'd say this one-liner is still pretty readable, probably even more so than the first suggestion, therefore I recommend it.</p>\n<p><a href=\"https://docs.python.org/3/library/random.html#functions-for-sequences\" rel=\"nofollow noreferrer\"><code>random.choice</code></a> is a better choice for expressing your intention in this snippet.</p>\n<p>Naming iteration variables <code>_</code> is a convention to signal that the variable value is never actually used.</p>\n<hr />\n<p><strong>Main logic</strong></p>\n<p>You're doing way too much manual checking when counting the neighbors. You should not manually construct all possible combinations of coordinates. Instead, think about the underlying logic and how to translate that into more concise code. I'm sure there are also many resources available (probably on this site alone) for proper checking / counting neighbors for a given coordinate.</p>\n<p>Please also note that the original game rules are designed for a board of infinite size, as far as I know there are no &quot;official&quot; rules for boards of limited sizes.</p>\n<hr />\n<p><code>print('\\n\\n\\n\\n\\n')</code> is better expressed as <code>print('\\n' * 5)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T17:25:49.970", "Id": "534163", "Score": "0", "body": "My whole goal also is to get the coordinate combinations into more concise code. However, I'm stuck on the thought process and came here for tips." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T17:55:34.777", "Id": "534170", "Score": "0", "body": "Would your logic for list creation work since there has to be both an x and y coordinate on the board? Also, using your nested approach, the variable \"column\" and \"CELLS\" is not defined, so what direction would you take for correcting that when simplifying those lines in particular? I added the changes and not the output returns trueFalse instead of random #'s" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T10:08:12.690", "Id": "534207", "Score": "2", "body": "I've added a definition for constant `CELLS`. I did not intend to rewrite your code for you, I've merely pointed out some useful concepts that you should understand and then try to implement yourself. The code snippets can of course be used for inspiration / guidance, but they're not necessarily intended to be copy-and-pasteable. However, I've locally implemented the proposed changes and the code seems to be working fine, I cannot reporduce the errors you're describing." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T17:01:41.980", "Id": "270468", "ParentId": "270461", "Score": "2" } }, { "body": "<p>Your code works and is readable, which is nice. It also mostly follows <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> style conventions, which is nice, although this can be improved, as it was already mentioned in the other answer.</p>\n<p>Of course, there is always room for improvement.</p>\n<h1>Code structure</h1>\n<p>What your code lacks is structure: everything happens at the top level, with no use of functions or classes.</p>\n<p>This is bad, as it makes the code harder to read and follow along, less maintainable and less reusable.</p>\n<p>Breaking the code into functions allows you to focus on each aspect of the code independently. Consider the following pseudocode:</p>\n<pre><code>initialize()\n\nwhile True:\n display_cells()\n update_state()\n wait()\n</code></pre>\n<p>In this case, the main loop is very simple and easy to follow. Now, if you want to work on how to display the cells, you can easily go to the relevant function's definition and work on just that. If you want to try another way to display, for example with a graphic display instead of characters on console, you can define another function and replace just one line in the main loop to try it out.</p>\n<p>It also shows that it needs a way to keep track of the current state of the cell grid.</p>\n<p>In your code, you use a global variable called <code>nextCells</code>. Global variables are considered bad practice for a number of good reasons, mainly because it makes it hard to keep track where in the code they are acted upon, and thus what it's value is supposed to be at a given point in the code, especially once you break the code into multiple functions.</p>\n<p>One way to fix that is to pass the variable as arguments to functions:</p>\n<pre><code>cells = initialize()\nwhile True:\n display_cells(cells)\n cells = update_state(cells)\n wait()\n</code></pre>\n<p>You could argue that <code>cells</code> is still technically a global variable, as it is defined at the root level of the code. One way to deal with that is to encapsulate the game state into a class. The class should hold the game state, provide ways to act upon it and to access information about it.</p>\n<p>Implementing a class, the code now looks something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class GameOfLife:\n def __init__(self):\n pass\n def update_state(self):\n pass\n def print_cells(self)\n pass\n def run(self)\n pass\n\n\ngame = GameOfLife()\ngame.run()\n</code></pre>\n<p>Now there are just a few more things left to address.</p>\n<p>First is documentation: while the code is simple and mostly self-documenting, it is good practice to document the code using docstrings and comments, if necessary.</p>\n<p>Docstrings should describe the purpose of classes and functions, and how to use them. Should the class/function be used elsewhere, they can be accessed with the <code>help()</code> builtin function of Python, and allow users to read on how to use your work without reading actual code.</p>\n<p>Comments should provide <em>why</em> things are done a certain way, if it is unclear. If the code is made using descriptive names and logical units, there should be little need for comments.</p>\n<p>Finally is reusability. Now that the game of life is encapsulated into a convenient object, it can be useful to <code>import</code> it from another script and use it. However, as is, the last 2 lines would execute and an instance of the game would run, which is not desirable in this case.</p>\n<p>To allow <code>import</code>s and running the script, you can put the code inside a &quot;main guard&quot;.</p>\n<p>My take on the problem is:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nfrom time import sleep\n\n\nclass Life:\n '''\n An implementation of Conway's game of life on a finite and wrapping grid\n '''\n \n LIVE_CELL = '#'\n DEAD_CELL = ' '\n DELAY = 1\n\n def __init__(self, width=60, height=20):\n self.width = width\n self.height = height\n self.cells = [[random.choice([True, False]) for _ in range(self.width)] for _ in range(self.height)]\n\n def next_generation(self):\n '''\n Updates the cell grid according to Conway's rules\n '''\n next_cells = [[False for _ in range(self.width)] for _ in range(self.height)]\n for j in range(self.width):\n for i in range(self.height):\n neighbor_count = self._count_live_neighbors(i, j)\n if ((self.cells[i][j] and neighbor_count in (2, 3))\n or (not self.cells[i][j] and neighbor_count == 3)):\n next_cells[i][j] = True\n self.cells = next_cells\n\n def _count_live_neighbors(self, i, j):\n '''\n Counts the number of live neighbor of a cell, given the cell indices on the grid\n '''\n count = 0\n for di, dj in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]:\n if self.cells[(i + di) % self.height][(j + dj) % self.width]:\n count += 1\n return count\n\n def print_cells(self):\n '''\n Print the current state of the cell grid on the console\n '''\n print('\\n\\n\\n\\n\\n')\n for row in self.cells:\n chars = [self.LIVE_CELL if c else self.DEAD_CELL for c in row]\n print(''.join(chars))\n\n def run(self):\n '''\n Run the game of life until a keyboard interrupt is raise (by pressing ctrl+c)\n '''\n try:\n while(True):\n self.print_cells()\n self.next_generation()\n sleep(self.DELAY)\n except KeyboardInterrupt:\n pass\n\n\nif __name__ == '__main__':\n life = Life()\n life.run()\n</code></pre>\n<h1>Other improvements</h1>\n<p>As you can see, I also changed some of the logic, so I'll explain my reasoning.</p>\n<h2>Using an array of booleans for the cell grid</h2>\n<p><code>True</code> represent live cells, <code>False</code> dead ones. This is to improve reusability, leaving the display logic decide how to display dead or alive cells. It also simplifies some of the logic.</p>\n<h2>Using a loop to iterate over neighbors</h2>\n<p>Less copy-and-pasted code makes it less error-prone and more maintainable, while still being easy to understand in this case.</p>\n<h2>Using list comprehensions</h2>\n<p>Python one-liners can sometimes get hard to read, but list comprehensions to initialize lists is very useful and muck more efficient than iteratively appending values.</p>\n<p>In simple cases like that, it is still quite readable.</p>\n<h1>Going further</h1>\n<p>If you're interested in going further as an exercise, I can think of a few improvements that can be done to the code:</p>\n<ul>\n<li>Implement other ways to initialize the game, for example by passing a cell grid to the constructor (easy), or by parsing a file (a bit harder). This would allow to try out some patterns.</li>\n<li>The canonical game of life as described by John Conway is carried out on an infinite grid. While this is impossible in practice, it can be approximated by keeping track of the game state for some distance outside of what is actually displayed (medium)</li>\n<li>Displaying on console is not very good, as the displayed cells do not look very good, are not square, and are quite limited in number, while the console flickers. A graphical display would be more suited, but also a lot harder to implement.</li>\n<li>Updating the game state can be heavily optimized. It's fine for a small number of cells (and as such for console display), but if you eventually move to a large grid, this solution is probably not good enough. Possible improvements I can think of:\n<ul>\n<li>As of now, each time the grid state is updated, a new list is allocated, then the old one is disposed of by the garbage collector. Both of these actions are slow. A solution would be to keep 2 lists in memory, and point to either one for the current generation and the next generation.</li>\n<li>Calculating the state of the next generation is easily parallelisable, as each cell is independent from every other one.</li>\n</ul>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T13:18:18.593", "Id": "534304", "Score": "0", "body": "`My take` ack. I'd go for `next_cells[i][j] = 3 == neighbor_count or 2 == neighbor_count and cells[i][j]`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T11:40:25.457", "Id": "270536", "ParentId": "270461", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T03:59:06.753", "Id": "270461", "Score": "2", "Tags": [ "python", "functional-programming", "game-of-life" ], "Title": "Improving the Conway's Game of Life Code With Functions in Python" }
270461
<p>I am very much new to AWS Services and NodeJS. I would like to query a DynamoDB with username and if it exists return a boolean (true/false). I do not want to hard code the username anywhere in my Lambda code. Below is my code which currently returns all the contents of DDB:</p> <pre><code>var AWS = require('aws-sdk'); var docClient = new AWS.DynamoDB.DocumentClient(); exports.handler = function(event, context, callback) { if(!event.hasOwnProperty(&quot;queryStringParameters&quot;)) { console.log(&quot;NOT FOUND&quot;); var emptyparams = { TableName: &quot;DDB1&quot;, }; docClient.scan(emptyparams, onScan); return; } var params = { TableName: &quot;DDB1&quot; }; docClient.scan(params, onScan); var count = 0; function onScan(err, data) { if (err) { console.error(&quot;Unable to scan. Error JSON:&quot;, JSON.stringify(err, null, 2)); } else { console.log(&quot;Successful!.&quot;); data.Items.forEach(function(itemdata) { console.log(&quot;Item :&quot;, ++count,JSON.stringify(itemdata)); }); } var response = { &quot;statusCode&quot;: &quot;200&quot;, &quot;body&quot;: JSON.stringify(data.Items) }; callback(null, response); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T10:35:13.960", "Id": "534136", "Score": "0", "body": "Does the current code produce the required output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T16:37:03.893", "Id": "534151", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T17:07:06.270", "Id": "534158", "Score": "0", "body": "The above code is currently scanning the DynamoDB and returning all the contents of it. I would like to search with the different keys to check if those keys exist or not and return a response accordingly. The keys shouldn't be hard-coded in the code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T20:58:49.737", "Id": "534183", "Score": "0", "body": "Your code doesn't accomplish the task you want. Code Review does not write code for you; we only review code that already works." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T09:56:19.933", "Id": "270464", "Score": "0", "Tags": [ "node.js", "lambda" ], "Title": "Query DynamoDB and get a response" }
270464
<p>I was writing a social media sample application for Android in Kotlin. One of the requirements in the project is a screen which show the profile of his friend to a user. This profile screen should also update itself dynamically if that friend updates his profile when the user is viewing his profile. I can achieve this using Firestore event listeners.</p> <p>One simple way to do this is to do like this:</p> <pre><code>val friendId: String = ... // Friend's uid val isFriend: Boolean = Firebase.firestore.collection(&quot;users&quot;).document(myId).collection(&quot;friends&quot;).document(friendId).get().await() != null return if(isFriend) callbackFlow { val listener = Firebase.firestore.collection(&quot;users&quot;).document(friendId).collection(&quot;private&quot;).document(&quot;friendOnly&quot;) .addSnapshotListener { snap, error -&gt; trySend(snap?.toObject&lt;FriendOnlyInfo&gt;()) } awaitClose { listener.remove() } } else null </code></pre> <p>Suppose this flow will be collected in the fragment <code>ON_STARTED</code>. Now, if a friend unfriends this user while user is viewing his profile, then the listener will be detached and user will no longer get updates. This is good.</p> <p>But problem occurs when a non friend befriends the user while user is viewing his profile. In this case, there will be no listeners attached to the database. The same issue occurs when a friend unfriends this user, and again befriends him while user is viewing his profile.</p> <p>So, to overcome that, I implemented like this:</p> <pre><code>val friendId: String = ... // Friend's uid val isFriend: Flow&lt;Boolean&gt; = callbackFlow { val listener = Firebase.firestore.collection(&quot;users&quot;).document(myId).collection(&quot;friends&quot;).document(friendId) .addSnapshotListener { snap, error -&gt; trySend(snap != null) } awaitClose { listener.remove() } } return callbackFlow { var listener: ListenerRegistration? = null isFriend.onCompletion { listener?.remove() }.collect { isFrnd -&gt; if(isFrnd &amp;&amp; listener == null) listener = Firebase.firestore.collection(&quot;users&quot;).document(friendId).collection(&quot;private&quot;).document(&quot;friendOnly&quot;) .addSnapshotListener { snap, error -&gt; trySend(snap?.toObject&lt;FriendOnlyInfo&gt;()) } } } </code></pre> <p>This implementation listens for the <em>friend</em> value from the database and accordingly attaches itself when both are friends. When both become non-friends, firestore itself will remove the listener.</p> <p>Is this good enough? Are there any caveates?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T18:40:29.930", "Id": "270470", "Score": "0", "Tags": [ "android", "kotlin", "firebase" ], "Title": "Implementing a persistent Firestore event listener with Kotlin flows" }
270470
<p>The program is designed to take data from a MySQL database, using mysql-connector-python, and print it as a table in Python using the texttable module. The program also plots charts based on the data from MySQL database using the matplotlib library.</p> <p>For those who don’t have any data in MySQL, the program will assist a bit to insert data into a few tables.</p> <p>Relevant MySQL information:</p> <pre class="lang-sql prettyprint-override"><code>mysql&gt; use ip_project; Database changed mysql&gt; show tables; +----------------------+ | Tables_in_ip_project | +----------------------+ | exam | | student | | subject | +----------------------+ 3 rows in set (0.05 sec) mysql&gt; desc exam; +----------+------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+------------+------+-----+---------+-------+ | sub_code | varchar(3) | NO | | NULL | | | roll_no | int | NO | | NULL | | | marks | int | YES | | NULL | | | test | varchar(3) | NO | | NULL | | +----------+------------+------+-----+---------+-------+ 4 rows in set (0.01 sec) mysql&gt; desc student; +---------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+-------------+------+-----+---------+-------+ | roll_no | int | NO | PRI | NULL | | | name | varchar(20) | NO | | NULL | | | stream | varchar(5) | NO | | NULL | | +---------+-------------+------+-----+---------+-------+ 3 rows in set (0.00 sec) mysql&gt; desc subject; +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | sub_code | varchar(3) | NO | PRI | NULL | | | name | varchar(30) | NO | | NULL | | +----------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) </code></pre> <p>The coding was done in a conda environment with Python 3.7.11. The following packages/modules/libraries were used:</p> <ul> <li>spyder</li> <li>pandas</li> <li>numpy</li> <li>matplotlib</li> <li>mysql-connector-python</li> <li>texttable</li> </ul> <p>Python code:</p> <pre class="lang-py prettyprint-override"><code># Importing from getpass import getpass from mysql.connector import connect import pandas as pd import numpy as np import matplotlib.pyplot as plt import texttable ################################# #Defining/Assigning create_db_query = &quot;&quot;&quot;CREATE DATABASE IF NOT EXISTS ip_project;&quot;&quot;&quot; use_db_query = &quot;USE ip_project;&quot; crt_examtbl_query = &quot;&quot;&quot;CREATE TABLE IF NOT EXISTS `exam` ( `sub_code` varchar(3) NOT NULL, `roll_no` int NOT NULL, `marks` int DEFAULT NULL, `test` varchar(3) NOT NULL );&quot;&quot;&quot; crt_stutbl_query = &quot;&quot;&quot;CREATE TABLE IF NOT EXISTS `student` ( `roll_no` int NOT NULL, `name` varchar(20) NOT NULL, `stream` varchar(5) NOT NULL, PRIMARY KEY (`roll_no`) );&quot;&quot;&quot; crt_subtbl_query = &quot;&quot;&quot;CREATE TABLE IF NOT EXISTS `subject` ( `sub_code` varchar(3) NOT NULL, `name` varchar(30) NOT NULL, PRIMARY KEY (`sub_code`) ); &quot;&quot;&quot; tbl_structure = '''You can now see the table structures to get a better idea: 'exam' table: ============ +----------+------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+------------+------+-----+---------+-------+ | sub_code | varchar(3) | NO | | NULL | | | roll_no | int | NO | | NULL | | | marks | int | YES | | NULL | | | test | varchar(3) | NO | | NULL | | +----------+------------+------+-----+---------+-------+ 'student' table: =============== +---------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+-------------+------+-----+---------+-------+ | roll_no | int | NO | PRI | NULL | | | name | varchar(20) | NO | | NULL | | | stream | varchar(5) | NO | | NULL | | +---------+-------------+------+-----+---------+-------+ 'subject' table: =============== +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | sub_code | varchar(3) | NO | PRI | NULL | | | name | varchar(30) | NO | | NULL | | +----------+-------------+------+-----+---------+-------+ ''' insert_stu_query = '''INSERT INTO student(roll_no, name, stream) VALUES(%s, %s, %s);''' stream_human_lst = ''' 1. MPC 2. BiPC 3. MEC 4. CEIP ''' stream_list = [&quot;MPC&quot;,&quot;BiPC&quot;,&quot;MEC&quot;,&quot;CEIP&quot;] stream_inp_stat = &quot;Choose one of the these streams (by typing the number): &quot; select_stu_query = &quot;SELECT * FROM student;&quot; insert_sub_query = '''INSERT INTO subject VALUES (&quot;301&quot;,&quot;English&quot;), (&quot;041&quot;,&quot;Maths&quot;), (&quot;042&quot;,&quot;Physics&quot;), (&quot;043&quot;,&quot;Chemistry&quot;), (&quot;065&quot;,&quot;Informatics Practices&quot;), (&quot;055&quot;,&quot;Accountancy&quot;), (&quot;030&quot;,&quot;Economics&quot;), (&quot;054&quot;,&quot;Business Studies&quot;), (&quot;044&quot;,&quot;Biology&quot;); ''' select_sub_query = &quot;SELECT * FROM subject;&quot; exam_tbl = &quot;We request you to insert data in 'exam' table using MySQL.&quot; ####################################################################### menu = '''Choose one of the options by typing the number: 1. See the marks of the student 2. See the total marks and percentage of each test of the student 3. See graphs/charts made using the marks of the student ''' Q1 = &quot;SELECT * FROM student;&quot; marks_query = &quot;&quot;&quot; SELECT exam.test Test, exam.sub_code 'Code', subject.name Subject, exam.marks Marks FROM exam LEFT JOIN subject ON exam.sub_code = subject.sub_code WHERE roll_no=%s ORDER BY exam.test,exam.sub_code ASC; &quot;&quot;&quot; total_query = ''' SELECT test Test, SUM(marks) Total, SUM(marks)/250*100 &quot;Percentage (%)&quot; FROM exam WHERE roll_no=%s GROUP BY test ORDER BY test ASC; ''' plot_menu = '''Choose one of the options by typing the number: 1. Bar graph 2. Line graph ''' mpc_query = '''SELECT * FROM student WHERE stream=&quot;MPC&quot;;''' bipc_query = '''SELECT * FROM student WHERE stream=&quot;BiPC&quot;;''' mec_query = '''SELECT * FROM student WHERE stream=&quot;MEC&quot;;''' ceip_query = '''SELECT * FROM student WHERE stream=&quot;CEIP&quot;;''' bar_query = &quot;&quot;&quot; SELECT exam.test, exam.sub_code, subject.name, exam.marks FROM exam LEFT JOIN subject ON exam.sub_code = subject.sub_code WHERE exam.roll_no=%s ORDER BY exam.test,exam.sub_code ASC; &quot;&quot;&quot; line_query = &quot;&quot;&quot; SELECT exam.test, exam.sub_code, subject.name, exam.marks FROM exam LEFT JOIN subject ON exam.sub_code = subject.sub_code WHERE exam.roll_no=%s ORDER BY exam.sub_code,exam.test ASC; &quot;&quot;&quot; uni_subnames = &quot;&quot;&quot; SELECT DISTINCT subject.name FROM exam LEFT JOIN subject ON exam.sub_code = subject.sub_code WHERE exam.roll_no=%s ORDER BY exam.sub_code,exam.test ASC; &quot;&quot;&quot; ######################################################################## # Welcoming user print(&quot;Hello! Welcome to the report card management software.&quot;) print() print(&quot;&quot;&quot;Do you have a MySQL database which has the marks data of students? Press y or n.&quot;&quot;&quot;) print() database_inp = input() print() if database_inp == &quot;n&quot;: print() print(&quot;OK. Let's create a database for you.&quot;) print() print(&quot;Firstly, let's connect to MySQL.&quot;) db_cnnt = connect( host=&quot;localhost&quot;, user=input(&quot;Enter username: &quot;), password=getpass(&quot;Enter password: &quot;)) #Cursor db_cursor = db_cnnt.cursor() db_cursor.execute(create_db_query) print() print(&quot;We have created a database named 'ip_project' for you.&quot;) print() db_cursor.execute(use_db_query) db_cursor.execute(crt_examtbl_query) db_cursor.execute(crt_stutbl_query) db_cursor.execute(crt_subtbl_query) print(&quot;We have also created three tables for you. The tables are 'exam', 'student' and 'subject'.&quot;) print() print(tbl_structure) print() print(&quot;Now let's insert data in 'student' table.&quot;) stu_no = int(input(&quot;How many rows do you want to add in student table (type number)? &quot;)) main_l = [] for i in range(stu_no): c1 = int(input(&quot;Enter roll number of the student: &quot;)) c2 = input(&quot;Enter name of the student: &quot;) print(stream_inp_stat, stream_human_lst) print(&quot;For example: Type 1 for MPC.&quot;) print() stream_choice = int(input()) if stream_choice == 1: c3 = stream_list[0] elif stream_choice == 2: c3 = stream_list[1] elif stream_choice == 3: c3 = stream_list[2] elif stream_choice == 4: c3 = stream_list[3] l1 = [c1,c2,c3] t1 = tuple(l1) main_l.append(t1) db_cursor.executemany(insert_stu_query,main_l) db_cnnt.commit() print() db_cursor.execute(select_stu_query) stu_sql_tbl = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description]) print(&quot;This is the 'student' table:&quot;) print() print(stu_sql_tbl.to_markdown(index = False, tablefmt=&quot;grid&quot;)) db_cursor.execute(insert_sub_query) db_cnnt.commit() db_cursor.execute(select_sub_query) sub_sql_tbl = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description]) print() print(&quot;We have inserted the data in 'subject' table. This is the subject table:&quot;) print() print(sub_sql_tbl.to_markdown(index = False, tablefmt=&quot;grid&quot;)) print() print(exam_tbl) print(&quot;After inserting data in 'exam' table through MySQL, you can see other things like total and graphs in this program.&quot;) db_cursor.close() db_cnnt.close() elif database_inp == &quot;y&quot;: print(&quot;Let's connect to the MySQL database!&quot;) db_cnnt = connect( host=&quot;localhost&quot;, user=input(&quot;Enter username: &quot;), password=getpass(&quot;Enter password: &quot;), database=&quot;ip_project&quot;) #print(db_cnnt) #Cursor db_cursor = db_cnnt.cursor() #Getting basic details of all students db_cursor.execute(Q1) stu_table = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description], index = range(1,21)) #Taking input while True: try: inp = int(input(&quot;Please type the roll number of the student whose details you would like to see: &quot;)) except ValueError: print(&quot;Please type a valid input.&quot;) continue else: break print() print(menu) menu_inp = int(input()) if menu_inp == 1: print() db_cursor.execute(marks_query, (inp,)) marks_df = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description]) marks_df1 = marks_df marks_df1.loc[marks_df1['Test'].duplicated(), 'Test'] = '' if marks_df1[&quot;Marks&quot;].isnull().values.any() == True: marks_df1[&quot;Marks&quot;] = marks_df1[&quot;Marks&quot;].fillna(&quot;Absent&quot;) marks_col = marks_df1.columns marks_val = marks_df1.values.tolist() tableObj = texttable.Texttable() tableObj.set_cols_align([&quot;l&quot;, &quot;l&quot;, &quot;l&quot;, &quot;r&quot;]) tableObj.set_cols_dtype([&quot;t&quot;, &quot;t&quot;, &quot;t&quot;, &quot;a&quot;]) tableObj.set_cols_valign([&quot;m&quot;, &quot;m&quot;, &quot;m&quot;, &quot;m&quot;]) tableObj.header(marks_col) tableObj.add_rows(marks_val,header=False) print(&quot;Name of student:&quot;, stu_table.loc[inp,&quot;name&quot;]) print(&quot;Grade: XII&quot;) print(&quot;Stream:&quot;, stu_table.loc[inp,&quot;stream&quot;]) print() print(tableObj.draw()) print() ############################################################################## elif menu_inp==2: db_cursor.execute(total_query, (inp,)) total_df = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description]) total_col = total_df.columns total_val = total_df.values.tolist() tableObj = texttable.Texttable() tableObj.set_cols_align([&quot;l&quot;, &quot;l&quot;, &quot;l&quot;]) tableObj.set_cols_dtype([&quot;t&quot;, &quot;i&quot;, &quot;f&quot;]) tableObj.set_cols_valign([&quot;l&quot;, &quot;m&quot;, &quot;m&quot;]) tableObj.header(total_col) tableObj.add_rows(total_val,header=False) print(tableObj.draw()) ####################################################### elif menu_inp==3: print(plot_menu) plot_menu_inp = int(input()) if plot_menu_inp == 1: db_cursor.execute(bar_query, (inp,)) bar_df = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description]) #print(bar_df) ######################################################## m1_values = bar_df.loc[0:4, 'marks'].to_list() m2_values = bar_df.loc[5:9, 'marks'].to_list() m3_values = bar_df.loc[10:14, 'marks'].to_list() sub_list = bar_df.loc[0:4, 'name'].to_list() ######################################################### db_cursor.execute(mpc_query) mpc_df = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description]) mpc_list = mpc_df.roll_no.to_list() db_cursor.execute(bipc_query) bipc_df = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description]) bipc_list = bipc_df.roll_no.to_list() db_cursor.execute(mec_query) mec_df = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description]) mec_list = mec_df.roll_no.to_list() db_cursor.execute(ceip_query) ceip_df = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description]) ceip_list = ceip_df.roll_no.to_list() if inp in mpc_list or inp in bipc_list: sub_list[3]=&quot;IP&quot; elif inp in mec_list: sub_list[2]=&quot;B.St.&quot; sub_list[3]=&quot;Acct.&quot; elif inp in ceip_list: sub_list[1]=&quot;B.St.&quot; sub_list[2]=&quot;Acct.&quot; sub_list[3]=&quot;IP&quot; #print(sub_list) ######################################################### N = len(sub_list) ind = np.arange(N) width = 0.25 plt.grid(axis='y', zorder=0) plt.bar(ind, m1_values, width, label=&quot;MT1&quot;, color='xkcd:pink', zorder=3) plt.bar(ind+width, m2_values, width, label=&quot;MT2&quot;, color='xkcd:light blue', zorder=3) plt.bar(ind+width*2, m3_values, width, label=&quot;MT3&quot;, color='xkcd:mint', zorder=3) plt.xticks(ind+width,sub_list) plt.yticks(np.arange(0, 51, 5)) plt.legend(loc=(1.05, 0.5)) plt.tight_layout() plt.show() ##################################################################### elif plot_menu_inp == 2: db_cursor.execute(line_query, (inp,)) line_df = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description]) #print(line_df) db_cursor.execute(uni_subnames, (inp,)) uni_subnames_df = pd.DataFrame(db_cursor.fetchall(), columns=[item[0] for item in db_cursor.description]) #print(uni_subnames_df) uni_sub_list = uni_subnames_df.name.to_list() mt_list = [&quot;MT1&quot;,&quot;MT2&quot;,&quot;MT3&quot;] ######################################################## sub1_marks = line_df.loc[0:2, 'marks'].to_list() sub2_marks = line_df.loc[3:5, 'marks'].to_list() sub3_marks = line_df.loc[6:8, 'marks'].to_list() sub4_marks = line_df.loc[9:11, 'marks'].to_list() sub5_marks = line_df.loc[12:14, 'marks'].to_list() plt.grid() plt.plot(sub1_marks, label=uni_sub_list[0], marker=&quot;s&quot;) plt.plot(sub2_marks, label=uni_sub_list[1], marker=&quot;s&quot;) plt.plot(sub3_marks, label=uni_sub_list[2], marker=&quot;s&quot;) plt.plot(sub4_marks, label=uni_sub_list[3], marker=&quot;s&quot;) plt.plot(sub5_marks, label=uni_sub_list[4], marker=&quot;s&quot;) plt.xticks(np.arange(0,3),mt_list) plt.legend(loc=(1.05, 0.5)) plt.xlabel(r&quot;Monthly Test $\rightarrow$&quot;) plt.ylabel(r&quot;Marks $\rightarrow$&quot;) plt.tight_layout() plt.show() ####################################################### db_cursor.close() db_cnnt.close() input(&quot;Program complete. Press any key to exit.&quot;) </code></pre> <p>SQL queries used to create the database and insert data:</p> <pre class="lang-sql prettyprint-override"><code>-- Creating database CREATE DATABASE IF NOT EXISTS ip_project; USE ip_project; -- Creating tables: CREATE TABLE IF NOT EXISTS `exam` ( `sub_code` varchar(3) NOT NULL, `roll_no` int NOT NULL, `marks` int DEFAULT NULL, `test` varchar(3) NOT NULL ); CREATE TABLE IF NOT EXISTS `student` ( `roll_no` int NOT NULL, `name` varchar(20) NOT NULL, `stream` varchar(5) NOT NULL, PRIMARY KEY (`roll_no`) ); CREATE TABLE IF NOT EXISTS `subject` ( `sub_code` varchar(3) NOT NULL, `name` varchar(30) NOT NULL, PRIMARY KEY (`sub_code`) ); -- Inserting data -- student table INSERT INTO Student VALUES (1,&quot;Abhinash&quot;,&quot;MPC&quot;), (2,&quot;Aditi&quot;,&quot;MEC&quot;), (3,&quot;Alekhya&quot;,&quot;BiPC&quot;), (4,&quot;Amit&quot;,&quot;CEIP&quot;), (5,&quot;Anuhitha&quot;,&quot;BiPC&quot;), (6,&quot;Hari&quot;,&quot;MPC&quot;), (7,&quot;Jay&quot;,&quot;MEC&quot;), (8,&quot;Kiran&quot;,&quot;CEIP&quot;), (9,&quot;Madhav&quot;,&quot;CEIP&quot;), (10,&quot;Manohar&quot;,&quot;MPC&quot;), (11,&quot;Manoj&quot;,&quot;CEIP&quot;), (12,&quot;Neha&quot;,&quot;MEC&quot;), (13,&quot;Pawan&quot;,&quot;MEC&quot;), (14,&quot;Ravi&quot;,&quot;MPC&quot;), (15,&quot;Ritwik&quot;,&quot;CEIP&quot;), (16,&quot;Samraddhi&quot;,&quot;BiPC&quot;), (17,&quot;Smita&quot;,&quot;MPC&quot;), (18,&quot;Swathi&quot;,&quot;MEC&quot;), (19,&quot;Veena&quot;,&quot;MPC&quot;), (20,&quot;Yogesh&quot;,&quot;MPC&quot;); -- subject table INSERT INTO subject VALUES (&quot;301&quot;, &quot;English&quot;), (&quot;041&quot;,&quot;Maths&quot;), (&quot;042&quot;,&quot;Physics&quot;), (&quot;043&quot;,&quot;Chemistry&quot;), (&quot;065&quot;,&quot;Informatics Practices&quot;), (&quot;055&quot;,&quot;Accountancy&quot;), (&quot;030&quot;,&quot;Economics&quot;), (&quot;054&quot;,&quot;Business Studies&quot;), (&quot;044&quot;,&quot;Biology&quot;); -- exam table -- MT1 -- Accountancy: INSERT INTO exam VALUES (&quot;055&quot;, 2, 32, &quot;MT1&quot;), (&quot;055&quot;, 4, 39, &quot;MT1&quot;), (&quot;055&quot;, 7, 42, &quot;MT1&quot;), (&quot;055&quot;, 8, 40, &quot;MT1&quot;), (&quot;055&quot;, 9, NULL, &quot;MT1&quot;), (&quot;055&quot;, 11, 40, &quot;MT1&quot;), (&quot;055&quot;, 12, 39, &quot;MT1&quot;), (&quot;055&quot;, 13, 29, &quot;MT1&quot;), (&quot;055&quot;, 15, 42, &quot;MT1&quot;), (&quot;055&quot;, 18, 45, &quot;MT1&quot;); -- Maths: INSERT INTO exam VALUES (&quot;041&quot;, 1 , 29, &quot;MT1&quot;), (&quot;041&quot;, 2, 43, &quot;MT1&quot; ), (&quot;041&quot;, 6, 37, &quot;MT1&quot;), (&quot;041&quot;, 7, 33, &quot;MT1&quot;), (&quot;041&quot;, 10, 40, &quot;MT1&quot;), (&quot;041&quot;, 12, 44, &quot;MT1&quot;), (&quot;041&quot;, 13, 23, &quot;MT1&quot;), (&quot;041&quot;, 14, 25, &quot;MT1&quot;), (&quot;041&quot;, 17, 30, &quot;MT1&quot;), (&quot;041&quot;, 18, 39, &quot;MT1&quot;), (&quot;041&quot;, 19, 27, &quot;MT1&quot;), (&quot;041&quot;, 20, 28, &quot;MT1&quot;); -- IP: INSERT INTO exam VALUES (&quot;065&quot;, 1, 46, &quot;MT1&quot;), (&quot;065&quot; ,3, 39, &quot;MT1&quot;), (&quot;065&quot;, 4, 39, &quot;MT1&quot;), (&quot;065&quot;, 5, 35, &quot;MT1&quot;), (&quot;065&quot;, 6, 44, &quot;MT1&quot;), (&quot;065&quot;, 8, 41, &quot;MT1&quot;), (&quot;065&quot;, 9, 49, &quot;MT1&quot;), (&quot;065&quot;, 10, 46, &quot;MT1&quot;), (&quot;065&quot;, 11, 40, &quot;MT1&quot;), (&quot;065&quot;, 14, 29, &quot;MT1&quot;), (&quot;065&quot;, 15, 35, &quot;MT1&quot;), (&quot;065&quot;, 16, 38, &quot;MT1&quot;), (&quot;065&quot;, 17, 44, &quot;MT1&quot;), (&quot;065&quot;, 19, 30, &quot;MT1&quot;), (&quot;065&quot;, 20, 30, &quot;MT1&quot;); -- Eco: INSERT INTO exam VALUES (&quot;030&quot;, 2, 37, &quot;MT1&quot;), (&quot;030&quot;, 4, 44 , &quot;MT1&quot;), (&quot;030&quot;, 7, 35, &quot;MT1&quot;), (&quot;030&quot;, 8, 38, &quot;MT1&quot;), (&quot;030&quot;, 9, 34, &quot;MT1&quot;), (&quot;030&quot;, 11, 39, &quot;MT1&quot;), (&quot;030&quot;, 12, 43, &quot;MT1&quot;), (&quot;030&quot;, 13, 35, &quot;MT1&quot;), (&quot;030&quot;, 15, 40, &quot;MT1&quot;), (&quot;030&quot;, 18, 35, &quot;MT1&quot;); -- BST: INSERT INTO exam VALUES (&quot;054&quot;, 2, 34, &quot;MT1&quot;), (&quot;054&quot;, 4, 47, &quot;MT1&quot;), (&quot;054&quot;, 7, 26, &quot;MT1&quot;), (&quot;054&quot;, 8, 37, &quot;MT1&quot;), (&quot;054&quot;, 9 , 34, &quot;MT1&quot;), (&quot;054&quot;, 11, 37, &quot;MT1&quot;), (&quot;054&quot;, 12, 41, &quot;MT1&quot;), (&quot;054&quot;, 13, 38, &quot;MT1&quot;), (&quot;054&quot;,15 , 35, &quot;MT1&quot;), (&quot;054&quot;,18 , 29, &quot;MT1&quot;); -- Chem: INSERT INTO exam VALUES (&quot;043&quot;, 1, 42, &quot;MT1&quot;), (&quot;043&quot;, 3, 37, &quot;MT1&quot;), (&quot;043&quot;, 5, 42, &quot;MT1&quot;), (&quot;043&quot;, 6, 42, &quot;MT1&quot;), (&quot;043&quot;, 10, 30, &quot;MT1&quot;), (&quot;043&quot;, 14, NULL, &quot;MT1&quot;), (&quot;043&quot;, 16, 35, &quot;MT1&quot;), (&quot;043&quot;, 17, 29, &quot;MT1&quot;), (&quot;043&quot;, 19, 28, &quot;MT1&quot;), (&quot;043&quot;, 20, 30, &quot;MT1&quot;); -- Bio: INSERT INTO exam VALUES (&quot;044&quot;,3,29,&quot;MT1&quot;), (&quot;044&quot;,5,39,&quot;MT1&quot;), (&quot;044&quot;,16,43,&quot;MT1&quot;); -- Physics: INSERT INTO exam VALUES (&quot;042&quot;,1,36,&quot;MT1&quot;), (&quot;042&quot;,3,34,&quot;MT1&quot;), (&quot;042&quot;,5,40,&quot;MT1&quot;), (&quot;042&quot;,6,39,&quot;MT1&quot;), (&quot;042&quot;,10,37,&quot;MT1&quot;), (&quot;042&quot;,14,32,&quot;MT1&quot;), (&quot;042&quot;,16,39,&quot;MT1&quot;), (&quot;042&quot;,17,38,&quot;MT1&quot;), (&quot;042&quot;,19,45,&quot;MT1&quot;), (&quot;042&quot;,20,34,&quot;MT1&quot;); -- English: INSERT INTO exam VALUES (&quot;301&quot;, 1, 38, &quot;MT1&quot;), (&quot;301&quot;, 2, 45, &quot;MT1&quot;), (&quot;301&quot;, 3, 40, &quot;MT1&quot;), (&quot;301&quot;, 4, 44, &quot;MT1&quot;), (&quot;301&quot;, 5, 44, &quot;MT1&quot;), (&quot;301&quot;, 6, 40, &quot;MT1&quot;), (&quot;301&quot;, 7, 37, &quot;MT1&quot;), (&quot;301&quot;, 8, 39, &quot;MT1&quot;), (&quot;301&quot;, 9, 29, &quot;MT1&quot;), (&quot;301&quot;, 10, 43, &quot;MT1&quot;), (&quot;301&quot;, 11, 44, &quot;MT1&quot;), (&quot;301&quot;, 12, 40, &quot;MT1&quot;), (&quot;301&quot;, 13, 28, &quot;MT1&quot;), (&quot;301&quot;, 14, 21, &quot;MT1&quot;), (&quot;301&quot;, 15, 40, &quot;MT1&quot;), (&quot;301&quot;, 16, 39, &quot;MT1&quot;), (&quot;301&quot;, 17, 47, &quot;MT1&quot;), (&quot;301&quot;, 18, 35, &quot;MT1&quot;), (&quot;301&quot;, 19, 39, &quot;MT1&quot;), (&quot;301&quot;, 20, 37, &quot;MT1&quot;); -- MT2 -- Maths: INSERT INTO exam VALUES (&quot;041&quot;, 1 , 37, &quot;MT2&quot;), (&quot;041&quot;, 2, 44, &quot;MT2&quot; ), (&quot;041&quot;, 6, 41, &quot;MT2&quot;), (&quot;041&quot;, 7, 38, &quot;MT2&quot;), (&quot;041&quot;, 10, 43, &quot;MT2&quot;), (&quot;041&quot;, 12, 44, &quot;MT2&quot;), (&quot;041&quot;, 13, 30, &quot;MT2&quot;), (&quot;041&quot;, 14, 28, &quot;MT2&quot;), (&quot;041&quot;, 17, 35, &quot;MT2&quot;), (&quot;041&quot;, 18, 40, &quot;MT2&quot;), (&quot;041&quot;, 19, 39, &quot;MT2&quot;), (&quot;041&quot;, 20, 29, &quot;MT2&quot;); -- Chem: INSERT INTO exam VALUES (&quot;043&quot;, 1, 45, &quot;MT2&quot;), (&quot;043&quot;, 3, 43, &quot;MT2&quot;), (&quot;043&quot;, 5, 39, &quot;MT2&quot;), (&quot;043&quot;, 6, 39, &quot;MT2&quot;), (&quot;043&quot;, 10, 25, &quot;MT2&quot;), (&quot;043&quot;, 14, 38, &quot;MT2&quot;), (&quot;043&quot;, 16, 44, &quot;MT2&quot;), (&quot;043&quot;, 17, 37, &quot;MT2&quot;), (&quot;043&quot;, 19, 37, &quot;MT2&quot;), (&quot;043&quot;, 20, 35, &quot;MT2&quot;); -- BST: INSERT INTO exam VALUES (&quot;054&quot;, 2, 40 , &quot;MT2&quot;), (&quot;054&quot;, 4, 45, &quot;MT2&quot;), (&quot;054&quot;, 7, 38, &quot;MT2&quot;), (&quot;054&quot;, 8, 43, &quot;MT2&quot;), (&quot;054&quot;, 9 , 32, &quot;MT2&quot;), (&quot;054&quot;, 11, 39, &quot;MT2&quot;), (&quot;054&quot;, 12, 38, &quot;MT2&quot;), (&quot;054&quot;, 13, 33, &quot;MT2&quot;), (&quot;054&quot;, 15 , 42, &quot;MT2&quot;), (&quot;054&quot;, 18 , 38, &quot;MT2&quot;); -- Eco: INSERT INTO exam VALUES (&quot;030&quot;, 2, 38, &quot;MT2&quot;), (&quot;030&quot;, 4, 39 , &quot;MT2&quot;), (&quot;030&quot;, 7, 30, &quot;MT2&quot;), (&quot;030&quot;, 8, 40, &quot;MT2&quot;), (&quot;030&quot;, 9, 44, &quot;MT2&quot;), (&quot;030&quot;, 11, 40, &quot;MT2&quot;), (&quot;030&quot;, 12, 40, &quot;MT2&quot;), (&quot;030&quot;, 13, 35, &quot;MT2&quot;), (&quot;030&quot;, 15, 38, &quot;MT2&quot;), (&quot;030&quot;, 18, 37, &quot;MT2&quot;); -- IP INSERT INTO exam VALUES (&quot;065&quot;, 1, 48, &quot;MT2&quot;), (&quot;065&quot; ,3, 42, &quot;MT2&quot;), (&quot;065&quot;, 4, 44, &quot;MT2&quot;), (&quot;065&quot;, 5, 40, &quot;MT2&quot;), (&quot;065&quot;, 6, 38, &quot;MT2&quot;), (&quot;065&quot;, 8, 38, &quot;MT2&quot;), (&quot;065&quot;, 9, 42, &quot;MT2&quot;), (&quot;065&quot;,10, 33, &quot;MT2&quot;), (&quot;065&quot;, 11, 43, &quot;MT2&quot;), (&quot;065&quot;, 14, 33, &quot;MT2&quot;), (&quot;065&quot;, 15, 40, &quot;MT2&quot;), (&quot;065&quot;, 16, 42, &quot;MT2&quot;), (&quot;065&quot;, 17, 40, &quot;MT2&quot;), (&quot;065&quot;, 19, 39, &quot;MT2&quot;), (&quot;065&quot;, 20, 37, &quot;MT2&quot;); -- Phy: INSERT INTO exam VALUES (&quot;042&quot;, 1, 43, &quot;MT2&quot;), (&quot;042&quot;, 3, 35, &quot;MT2&quot;), (&quot;042&quot;, 5, 42, &quot;MT2&quot;), (&quot;042&quot;, 6, 42, &quot;MT2&quot;), (&quot;042&quot;, 10, 19, &quot;MT2&quot;), (&quot;042&quot;, 14, 22, &quot;MT2&quot;), (&quot;042&quot;, 16, 41, &quot;MT2&quot;), (&quot;042&quot;, 17, 43, &quot;MT2&quot;), (&quot;042&quot;, 19, 28, &quot;MT2&quot;), (&quot;042&quot;, 20, 39, &quot;MT2&quot;); -- Accountancy INSERT INTO exam VALUES (&quot;055&quot;, 2, 29, &quot;MT2&quot;), (&quot;055&quot;, 4, 41, &quot;MT2&quot;), (&quot;055&quot;, 7, 40, &quot;MT2&quot;), (&quot;055&quot;, 8, 39, &quot;MT2&quot;), (&quot;055&quot;, 9, 43, &quot;MT2&quot;), (&quot;055&quot;, 11, 37, &quot;MT2&quot;), (&quot;055&quot;, 12, 41, &quot;MT2&quot;), (&quot;055&quot;, 13, 28, &quot;MT2&quot;), (&quot;055&quot;, 15, 47, &quot;MT2&quot;), (&quot;055&quot;, 18, 37, &quot;MT2&quot;); -- English: INSERT INTO exam VALUES (&quot;301&quot;, 1, 40, &quot;MT2&quot;), (&quot;301&quot;, 2, 45, &quot;MT2&quot;), (&quot;301&quot;, 3, 49, &quot;MT2&quot;), (&quot;301&quot;, 4, 45, &quot;MT2&quot;), (&quot;301&quot;, 5, 41, &quot;MT2&quot;), (&quot;301&quot;, 6, 44, &quot;MT2&quot;), (&quot;301&quot;, 7, 40, &quot;MT2&quot;), (&quot;301&quot;, 8, 44, &quot;MT2&quot;), (&quot;301&quot;, 9, 33, &quot;MT2&quot;), (&quot;301&quot;, 10, 40, &quot;MT2&quot;), (&quot;301&quot;, 11, 40, &quot;MT2&quot;), (&quot;301&quot;, 12, 37, &quot;MT2&quot;), (&quot;301&quot;, 13, 31, &quot;MT2&quot;), (&quot;301&quot;, 14, 26, &quot;MT2&quot;), (&quot;301&quot;, 15, 33, &quot;MT2&quot;), (&quot;301&quot;, 16, 42, &quot;MT2&quot;), (&quot;301&quot;, 17, 39, &quot;MT2&quot;), (&quot;301&quot;, 18, 41, &quot;MT2&quot;), (&quot;301&quot;, 19, 41, &quot;MT2&quot;), (&quot;301&quot;, 20, NULL, &quot;MT2&quot;); -- Bio INSERT INTO exam VALUES (&quot;044&quot;,3,33,&quot;MT2&quot;), (&quot;044&quot;,5,40,&quot;MT2&quot;), (&quot;044&quot;,16,NULL,&quot;MT2&quot;); -- MT3 -- Maths: INSERT INTO exam VALUES (&quot;041&quot;, 1 , 42, &quot;MT3&quot;), (&quot;041&quot;, 2, 37, &quot;MT3&quot; ), (&quot;041&quot;, 6, 43, &quot;MT3&quot;), (&quot;041&quot;, 7, 42, &quot;MT3&quot;), (&quot;041&quot;, 10, 36, &quot;MT3&quot;), (&quot;041&quot;, 12, 40, &quot;MT3&quot;), (&quot;041&quot;, 13, 45, &quot;MT3&quot;), (&quot;041&quot;, 14, 40, &quot;MT3&quot;), (&quot;041&quot;, 17, 40, &quot;MT3&quot;), (&quot;041&quot;, 18, 44, &quot;MT3&quot;), (&quot;041&quot;, 19, 42, &quot;MT3&quot;), (&quot;041&quot;, 20, 35, &quot;MT3&quot;); -- Chem: INSERT INTO exam VALUES (&quot;043&quot;, 1, 37, &quot;MT3&quot;), (&quot;043&quot;, 3, 44, &quot;MT3&quot;), (&quot;043&quot;, 5, 43, &quot;MT3&quot;), (&quot;043&quot;, 6, 41, &quot;MT3&quot;), (&quot;043&quot;, 10, 28, &quot;MT3&quot;), (&quot;043&quot;, 14, 40, &quot;MT3&quot;), (&quot;043&quot;, 16, 38, &quot;MT3&quot;), (&quot;043&quot;, 17, 43, &quot;MT3&quot;), (&quot;043&quot;, 19, 42, &quot;MT3&quot;), (&quot;043&quot;, 20, 39, &quot;MT3&quot;); -- Eco: INSERT INTO exam VALUES (&quot;030&quot;, 2, 33, &quot;MT3&quot;), (&quot;030&quot;, 4, 40 , &quot;MT3&quot;), (&quot;030&quot;, 7, NULL, &quot;MT3&quot;), (&quot;030&quot;, 8, 43, &quot;MT3&quot;), (&quot;030&quot;, 9, 45, &quot;MT3&quot;), (&quot;030&quot;, 11, 42, &quot;MT3&quot;), (&quot;030&quot;, 12, 39, &quot;MT3&quot;), (&quot;030&quot;, 13, 43, &quot;MT3&quot;), (&quot;030&quot;, 15, 45, &quot;MT3&quot;), (&quot;030&quot;, 18, 42, &quot;MT3&quot;); -- IP INSERT INTO exam VALUES (&quot;065&quot;, 1, 45, &quot;MT3&quot;), (&quot;065&quot; ,3, 47, &quot;MT3&quot;), (&quot;065&quot;, 4, 42, &quot;MT3&quot;), (&quot;065&quot;, 5, 39, &quot;MT3&quot;), (&quot;065&quot;, 6, 40, &quot;MT3&quot;), (&quot;065&quot;, 8, 40, &quot;MT3&quot;), (&quot;065&quot;, 9, 48, &quot;MT3&quot;), (&quot;065&quot;,10, 30, &quot;MT3&quot;), (&quot;065&quot;, 11, NULL, &quot;MT3&quot;), (&quot;065&quot;, 14, 42, &quot;MT3&quot;), (&quot;065&quot;, 15, 42, &quot;MT3&quot;), (&quot;065&quot;, 16, 39, &quot;MT3&quot;), (&quot;065&quot;, 17, 39, &quot;MT3&quot;), (&quot;065&quot;, 19, 43, &quot;MT3&quot;), (&quot;065&quot;, 20, 40, &quot;MT3&quot;); -- BST INSERT INTO exam VALUES (&quot;054&quot;, 2, 42 , &quot;MT3&quot;), (&quot;054&quot;, 4, 44, &quot;MT3&quot;), (&quot;054&quot;, 7, 40, &quot;MT3&quot;), (&quot;054&quot;, 8, 36, &quot;MT3&quot;), (&quot;054&quot;, 9 , 42, &quot;MT3&quot;), (&quot;054&quot;, 11, 45, &quot;MT3&quot;), (&quot;054&quot;, 12, 45, &quot;MT3&quot;), (&quot;054&quot;, 13, 40, &quot;MT3&quot;), (&quot;054&quot;, 15 , 46, &quot;MT3&quot;), (&quot;054&quot;, 18 , 42, &quot;MT3&quot;); -- Eng: INSERT INTO exam VALUES (&quot;301&quot;, 1, 45, &quot;MT3&quot;), (&quot;301&quot;, 2, 43, &quot;MT3&quot;), (&quot;301&quot;, 3, 46, &quot;MT3&quot;), (&quot;301&quot;, 4, 40, &quot;MT3&quot;), (&quot;301&quot;, 5, 45, &quot;MT3&quot;), (&quot;301&quot;, 6, 45, &quot;MT3&quot;), (&quot;301&quot;, 7, 44, &quot;MT3&quot;), (&quot;301&quot;, 8, 47, &quot;MT3&quot;), (&quot;301&quot;, 9, 42, &quot;MT3&quot;), (&quot;301&quot;, 10, 30, &quot;MT3&quot;), (&quot;301&quot;, 11, 47, &quot;MT3&quot;), (&quot;301&quot;, 12, 42, &quot;MT3&quot;), (&quot;301&quot;, 13, 42, &quot;MT3&quot;), (&quot;301&quot;, 14, 38, &quot;MT3&quot;), (&quot;301&quot;, 15, 45, &quot;MT3&quot;), (&quot;301&quot;, 16, 44, &quot;MT3&quot;), (&quot;301&quot;, 17, 42, &quot;MT3&quot;), (&quot;301&quot;, 18, 45, &quot;MT3&quot;), (&quot;301&quot;, 19, 45, &quot;MT3&quot;), (&quot;301&quot;, 20, 44, &quot;MT3&quot;); -- Bio: INSERT INTO exam VALUES (&quot;044&quot;, 3, 40, &quot;MT3&quot;), (&quot;044&quot;, 5, 42,&quot;MT3&quot;), (&quot;044&quot;, 16, 40,&quot;MT3&quot;); -- Accountancy INSERT INTO exam VALUES (&quot;055&quot;, 2, 41, &quot;MT3&quot;), (&quot;055&quot;, 4, 45, &quot;MT3&quot;), (&quot;055&quot;, 7, 45, &quot;MT3&quot;), (&quot;055&quot;, 8, 43, &quot;MT3&quot;), (&quot;055&quot;, 9, 47, &quot;MT3&quot;), (&quot;055&quot;, 11, 42, &quot;MT3&quot;), (&quot;055&quot;, 12, 44, &quot;MT3&quot;), (&quot;055&quot;, 13, 36, &quot;MT3&quot;), (&quot;055&quot;, 15, 45, &quot;MT3&quot;), (&quot;055&quot;, 18, 41, &quot;MT3&quot;); -- Physics: INSERT INTO exam VALUES (&quot;042&quot;, 1, 40, &quot;MT3&quot;), (&quot;042&quot;, 3, 40, &quot;MT3&quot;), (&quot;042&quot;, 5, 39, &quot;MT3&quot;), (&quot;042&quot;, 6, 40, &quot;MT3&quot;), (&quot;042&quot;, 10, 27, &quot;MT3&quot;), (&quot;042&quot;, 14, 37, &quot;MT3&quot;), (&quot;042&quot;, 16, 40, &quot;MT3&quot;), (&quot;042&quot;, 17, 37, &quot;MT3&quot;), (&quot;042&quot;, 19, 41, &quot;MT3&quot;), (&quot;042&quot;, 20, 43, &quot;MT3&quot;); </code></pre> <hr /> <p>The Python program was made for my project. I am a Python and MySQL beginner.</p> <p>Are there any chances of SQL injections?</p> <p>Is my method of calculating sum directly in MySQL better than importing it to pandas and finding the total? Any opinion is welcome :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T19:34:10.947", "Id": "534176", "Score": "0", "body": "Why not use object-relational mapping (ORM) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T14:34:38.807", "Id": "534216", "Score": "1", "body": "@Kevin It's an option, but it's not crazy to avoid ORMs. Particularly as a beginner learning about SQL syntax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T20:10:58.603", "Id": "534234", "Score": "0", "body": "@Kevin I agree with you. Also, my teachers haven't taught me anything about ORM " } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T19:10:11.517", "Id": "270471", "Score": "2", "Tags": [ "python", "python-3.x", "sql", "mysql", "matplotlib" ], "Title": "Student report card management Python program" }
270471
<p>So I built a method containing three for loops which essentially tried to match items in list a) with items in list b). It worked fine, but to try and improve it for reasons which are not (I think) germane here, I tried to incorporate an array list () into the comparison so as to remove the entries on the b) list that could not be matched.</p> <p>Now, the mysterious thing is that the latter method returns a AOoR exception. I have have striped both versions down to their basics, and one runs whereas the other gets the exception, but the two implementations are almost exactly the same. Some code below.</p> <p>array version:</p> <pre><code>for (int s = 0; s &lt; size; s++) { Item thisItem = itemList[s]; int itemCount = thisItem.Connections.Count; this.connections[s] = new int[itemCount ]; for (int c = 0; c &lt; itemCount ; c++) { if (thisItem.Connections[c] != null) { bool match = false; for (int a = 0; a &lt; size; a++) { match = IsHash(itemIDs[a], thisItem.Connections[c].ID); if (match) { this.connections[s][c] = a; break; } } if (!found) { //not germane code } } } } </code></pre> <p>List version:</p> <pre><code>for (int s = 0; s &lt; size; s++) { Item thisItem = itemList[s]; int itemCount = thisItem.Connections.Count; List&lt;int&gt; potentialConnections = new List&lt;int&gt;(itemCount); for (int c = 0; c &lt; itemCount ; c++) { if (thisItem.Connections[c] != null) { bool match = false; for (int a = 0; a &lt; size; a++) { match = IsHash(itemIDs[a], thisItem.Connections[c].ID); if (match) { potentialConnections[c] = a; break; } } if (!found) { //not germane code } } } } </code></pre> <p>The failure will be at <code>potentialConnections[c] = a;</code> in the latter version. Again, I've simplified this for presentation here, leaving out some things that are not important.</p> <p>Am I missing something?</p> <p>//edit For clarity I should just add that the first array being set is a jagged double array. The second implementation is meant to set the second array after removing all the faulty entries.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T23:50:28.860", "Id": "534194", "Score": "1", "body": "Code Review is applicable only to working as intended code. Thus the question is off-topic here. Try asking on StackOverflow instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T06:35:56.333", "Id": "534200", "Score": "0", "body": "Yes you missed something. If you create a `List` althought using the ctor to initialize the capacity you don't add any items to that `List` hence it is empty. Thats why you get an ArgumentOutOfRangeException. Nevertheless you question is off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T21:53:03.050", "Id": "534245", "Score": "0", "body": "Oh sorry. Last time I asked a code question (on broken code), somebody told me to ask here. Thanks for clarifying." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T20:43:31.863", "Id": "270472", "Score": "-2", "Tags": [ "c#" ], "Title": "Mysterious ArgumentOutOfRangeException between array and List implementation" }
270472
<p>I am having trouble with applying to 3 steps needed to proof correctness, most likely because I did not formally study CS or Mathematics and am still learning about loop and class invariants. The three steps:</p> <ol> <li>Initialization</li> <li>Maintenance</li> <li>Termination</li> </ol> <p>My understanding of the invariant is that, at the end of the partitioning process, we will have split the array into 3 regions. One where all elements are less than pivot, the pivot itself, and the region where all elements are larger or equal to the pivot.</p> <p>Assuming the invariant I stated above is correct, I do not see how it is true before, and after the each iteration (which I believe is a requirement for correctness)</p> <pre><code>private static void sort (Comparable[] a, int lo, int hi){ // a has been shuffled using fisher-yates-knuth if (hi &lt;= lo) return; // pivot is chosen, a[j], rearranges a[lo:hi], such that all elements a[lo:j-1] are less than pivot a[j] and all elements a[j+1:hi] are greater than pivot int partitionIndex = partition(a, lo, hi); sort(a, lo, partitionIndex - 1); sort(a, partitionIndex + 1, hi); } /** * * @param a array to sort * @param lo start index of segment that needs to be partitioned * @param hi end index of segment that needs to be partitioned * @return index of the pivot */ private static int partition(Comparable[] a, int lo, int hi){ // arbitrarily choose pivot Comparable pivot = a[hi]; int partitionIndex = lo; // scan array from lo to hi - 1, we skip hi because this is the pivot element // iterate over elements lo to hi - 1, since hi is already pivot there is no need for (int i = lo; i &lt; hi; i ++){ if (isLessThan(a[i], pivot)){ exchange(a, i, partitionIndex); partitionIndex++; } } exchange(a, hi, partitionIndex); // at this point, our array should be partitioned (divided) in three regions // region 1: pivot should be greater than all elements to its left // region 2: pivot should be less than or equal to all elements to its right // region 3: pivot was placed in the middle of the partition (the two regions) assert leftRegionCorrect(a, lo, partitionIndex) &amp;&amp; rightRegionCorrect(a, lo, partitionIndex) &amp;&amp; a[partitionIndex] == pivot; return partitionIndex; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T20:46:41.080", "Id": "270473", "Score": "0", "Tags": [ "java", "beginner", "sorting", "quick-sort" ], "Title": "Quicksort Invariant and steps to determine correcteness" }
270473
<p>I have data in JSON format.</p> <pre><code>{&quot;ts&quot;:1393631983,&quot;visitor_uuid&quot;:&quot;ade7e1f63bc83c66&quot;,&quot;visitor_source&quot;:&quot;external&quot;,&quot;visitor_device&quot;:&quot;browser&quot;,&quot;visitor_useragent&quot;:&quot;Opera/9.80 (Windows NT 6.1) Presto/2.12.388 Version/12.16&quot;,&quot;visitor_ip&quot;:&quot;b5af0ba608ab307c&quot;,&quot;visitor_country&quot;:&quot;BR&quot;,&quot;visitor_referrer&quot;:&quot;53c643c16e8253e7&quot;,&quot;env_type&quot;:&quot;reader&quot;,&quot;env_doc_id&quot;:&quot;140222143932-91796b01f94327ee809bd759fd0f6c76&quot;,&quot;event_type&quot;:&quot;pagereadtime&quot;,&quot;event_readtime&quot;:1010,&quot;subject_type&quot;:&quot;doc&quot;,&quot;subject_doc_id&quot;:&quot;140222143932-91796b01f94327ee809bd759fd0f6c76&quot;,&quot;subject_page&quot;:3} {&quot;ts&quot;:1393631983,&quot;visitor_uuid&quot;:&quot;232eeca785873d35&quot;,&quot;visitor_source&quot;:&quot;internal&quot;,&quot;visitor_device&quot;:&quot;browser&quot;,&quot;visitor_useragent&quot;:&quot;Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36&quot;,&quot;visitor_ip&quot;:&quot;fcf9c67037f993f0&quot;,&quot;visitor_country&quot;:&quot;MX&quot;,&quot;visitor_referrer&quot;:&quot;63765fcd2ff864fd&quot;,&quot;env_type&quot;:&quot;stream&quot;,&quot;env_ranking&quot;:10,&quot;env_build&quot;:&quot;1.7.118-b946&quot;,&quot;env_name&quot;:&quot;explore&quot;,&quot;env_component&quot;:&quot;editors_picks&quot;,&quot;event_type&quot;:&quot;impression&quot;,&quot;subject_type&quot;:&quot;doc&quot;,&quot;subject_doc_id&quot;:&quot;100713205147-2ee05a98f1794324952eea5ca678c026&quot;,&quot;subject_page&quot;:1} </code></pre> <p>My task requires me to take a &quot;subject_doc_id&quot; as input from the user and check for a match.</p> <p>Then display a histogram showing the count for the countries with that id.</p> <p>I know how to plot a histogram with values but I am not familiar on how to extract the data I need and count it and then generate the histogram using that data.</p> <p>Any kind of help is appreciated.Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T22:51:04.060", "Id": "534188", "Score": "0", "body": "Can you show us what you've tried? If you're not sure how to get started, check out the tag wiki for [tag:json] for some helpful links." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T23:20:15.670", "Id": "534191", "Score": "1", "body": "Code Review is for code that already works correctly. If you need help getting code to work, please post your attempted code to [Stack Overflow](https://stackoverflow.com)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T23:24:03.383", "Id": "534192", "Score": "3", "body": "@tdy I just noticed that they actually did post it on [Stack Overflow](https://stackoverflow.com/questions/70147142/making-a-histogram-from-json-data) and have an accepted answer. OP didn't share their attempt there, either." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T21:11:51.050", "Id": "270474", "Score": "-3", "Tags": [ "python", "json" ], "Title": "Create a histogram using JSON data in Python" }
270474
<p>I have completed my project which simulates the path of a particle trapped in a device known as a <a href="https://en.wikipedia.org/wiki/Magnetic_mirror" rel="nofollow noreferrer">magnetic mirror.</a> I would like your thoughts and improvements on my implementation.</p> <p>Here is the code:</p> <pre><code>from numba import jit import numpy as np import matplotlib.pyplot as plt # Plot attribute settings plt.rc(&quot;xtick&quot;, labelsize=&quot;large&quot;) plt.rc(&quot;ytick&quot;, labelsize=&quot;large&quot;) plt.rc(&quot;axes&quot;, labelsize=&quot;xx-large&quot;) plt.rc(&quot;axes&quot;, titlesize=&quot;xx-large&quot;) plt.rc(&quot;figure&quot;, figsize=(8,8)) # constants mu_0 = np.pi * 4.0 * pow(10, -7) # permeability of free space [kg*m*s^-2*A^-2] q_p = 1.6022 * pow(10, -19) # proton charge [coulombs] m_p = 1.6726 * pow(10, -27) # proton mass [kg] mu = 10000.0 * np.array([0.0, 0.0, 1.0]) # set magnetic moment to point in z direction ''' Calculates magnetic bottle field ''' ''' This function will come in handy when we illustrate the field along and ultimately illustrate the particle motion in field ''' def bot_field(x,y,z): z_disp = 10.0 # displacement of the two magnetic dipoles with respect to zero (one at z = -z_disp, the other at +z_disp) # point dipole A pos_A = np.array([0.0, 0.0, z_disp]) # set the position of the first dipole r_A = np.array([x,y,z]) - pos_A # find the difference between this point and point of the observer rmag_A = np.sqrt(sum(r_A**2)) B1_A = 3.0*r_A*np.dot(mu,r_A) / (rmag_A**5) # calculate the first term to the magnetic field B2_A = -1.0 * mu / (rmag_A**3) # calculate the second term # point dipole B pos_B = np.array([0.0, 0.0, -z_disp]) # set the position of the first dipole r_B = np.array([x,y,z]) - pos_B # find the difference between this position and the observation position rmag_B = np.sqrt(sum(r_B**2)) B1_B = 3.0*r_B*np.dot(mu,r_B) / (rmag_B**5) # calculate the first term to the magnetic field B2_B = -1.0 * mu / (rmag_B**3) # calculate the second term return ((mu_0/(4.0*np.pi)) * (B1_A + B2_A + B1_B + B2_B)) # return field due to magnetic bottle '''Setting up graph for dipole magnetic field''' y = np.arange(-10.0, 10.0, .1) # create a grid of points from y = -10 to 10 z = np.arange(-10.0, 10.0, .1) # create a grid of points from z = -10 to 10 Y, Z = np.meshgrid(y,z) # create a rectangular grid out of y and z len_i, len_j = np.shape(Y) # define dimensions, for use in iteration Bf = np.zeros((len_i,len_j,3)) # initialize all points with zero magnetic field ''' iterate through the grid and set magnetic field values at each point ''' for i in range(0, len_i): for j in range(0, len_j): Bf[i,j] = bot_field(0.0, Y[i,j], Z[i,j]) plt.streamplot(Y,Z, Bf[:,:,1], Bf[:,:,2], color='orange') # plot the magnetic field plt.xlim(-10.0,10.0) plt.ylim(-10.0,10.0) plt.xlabel(&quot;$y$ (m)&quot;) plt.ylabel(&quot;$z$ (m)&quot;) plt.title(&quot;Magnetic Field in a Magnetic Bottle&quot;) q = 2.0*q_p # charge of helium-4 m = 4.0*m_p # mass of helium-4 QoverM = q/m dt = pow(10, -5) # timestep t = np.arange(0.0, 1.0, dt) # array for times rp = np.zeros((len(t), 3)) # array for position values vp = np.zeros((len(t), 3)) # array for velocity values v_o = 100 # set the initial velocity to 100 m/s rp[0,:] = np.array([0.0, -5.0, 0.0]) # initialize the position to y=-5, 5m above the lower dipole vp[0,:] = np.array([0.0, 0.0, v_o]) # initialize the velocity to be in the z-direction ''' Model the particle motion in the field at each time step (Foward Euler Method) ''' for it in np.arange(0, len(t)-1,1): Bp = bot_field(rp[it,0], rp[it, 1], rp[it,2]) # input the current particle position into to get the magnetic field Ap = QoverM * np.cross(vp[it,:], Bp) # calculate the magnetic force on the particle vp[it+1] = vp[it] + dt*Ap # update the velocity of the particle based on this force rp[it+1] = rp[it] + dt*vp[it] # update the positon of the particle based on this velocity if (np.sqrt(np.sum(rp[it+1]**2)) &gt; 20.0): # If the particle escapes (i.e. exceeds 20 m from origin), cease calculations break ''' Plot the particle motion in the bottle ''' plt.streamplot(Y,Z, Bf[:,:,1], Bf[:,:,2], color=&quot;orange&quot;) plt.plot(rp[:,1], rp[:,2], color='navy') plt.xlim(-10.0,10.0) plt.ylim(-10.0,10.0) plt.xlabel(&quot;$y$ (m)&quot;) plt.ylabel(&quot;$z$ (m)&quot;) plt.title(&quot;Motion of Charged Particle in a Magnetic Bottle&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T23:25:08.553", "Id": "534193", "Score": "0", "body": "Related: [Phase diagrams of particles in a mirror](https://codereview.stackexchange.com/questions/269666/phase-diagrams-of-particles-in-a-mirror/269706#269706)" } ]
[ { "body": "<ul>\n<li>Rather than <code>4.0 * pow(10, -7)</code>, prefer scientific notation literals, i.e. <code>4e-7</code></li>\n<li>In nearly all cases there's no need for a <code>.0</code> suffix. Float promotion will do the right thing with an integer value.</li>\n<li>Prefer using inner tuples rather than inner lists for array initialization, since they're immutable; like <code>np.array((0, 0, 1))</code>.</li>\n<li>Add PEP484 type hints.</li>\n<li>Move your global code into functions.</li>\n<li>Prefer the object-oriented (<code>ax.</code>) rather than implicit-state (<code>plt.</code>) interface to matplotlib</li>\n<li>Factor out a function to do your dipole calculation</li>\n<li>Make proper use of <code>np.linalg.norm</code> instead of a manual square-and-square-root</li>\n<li>Do not use a loop to initialize <code>Bf</code>; vectorise this</li>\n<li>There's no need for a time array - you don't use it. All you need is a sample count, which is equal to your end time (one second) divided by your time delta.</li>\n<li>There's also no need for a velocity array. All you need is the current velocity.</li>\n<li>You do a bunch of plotting work that's entirely overwritten, including your <code>streamplot</code>. Don't do this twice - just do it once.</li>\n<li>Your constants for the proton are <a href=\"https://en.wikipedia.org/wiki/Proton\" rel=\"nofollow noreferrer\">not as accurate as they should be</a>. This error accumulates over your time iteration, and eventually makes your path deviate perceptibly from where it's supposed to go.</li>\n<li>Some typos, such as <code>Foward</code> -&gt; <code>Forward</code>, <code>positon</code> -&gt; <code>position</code></li>\n<li>You use implicit outer axis indexing in places like <code>rp[it]</code>. This is more confusing than explicitly showing what's going on - indexing the first axis, taking a slice over the second axis, like <code>rp[it, :]</code>.</li>\n<li>You don't actually care that <code>rp</code> starts off as zeros - it can start off as uninitialized (&quot;empty&quot;).</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from typing import Tuple\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# constants\nmu_0 = np.pi * 4e-7 # permeability of free space [kg*m*s^-2*A^-2]\nq_p = 1.602_176_634e-19 # proton charge [coulombs]\nm_p = 1.672_621_923_695_1e-27 # proton mass [kg]\nmu = np.array((0, 0, 1e4)) # set magnetic moment to point in z direction\n\n\ndef make_dipole(pos: np.ndarray, xyz: np.ndarray) -&gt; Tuple[np.ndarray, np.ndarray]:\n r = xyz - pos # difference between this point and point of the observer\n rmag = np.linalg.norm(r, axis=-1)\n if isinstance(rmag, np.ndarray):\n rmag = rmag[:, :, np.newaxis]\n\n '''\n https://numpy.org/doc/stable/reference/generated/numpy.dot.html\n If a is an N-D array and b is a 1-D array, \n it is a sum product over the last axis of a and b.\n '''\n\n dot = np.dot(r, mu)\n if isinstance(dot, np.ndarray):\n dot = dot[:, :, np.newaxis]\n\n B1 = 3*r*dot / rmag**5 # first term to the magnetic field\n B2 = -mu / rmag**3 # second term\n return B1, B2\n\n\ndef bot_field(xyz: np.ndarray) -&gt; np.ndarray:\n &quot;&quot;&quot;\n Calculates magnetic bottle field.\n This function will come in handy when we illustrate the field along and ultimately illustrate the\n particle motion in field\n &quot;&quot;&quot;\n z_disp = 10 # displacement of the two magnetic dipoles with respect to zero (one at z = -z_disp, the other at +z_disp)\n pos = np.array((0, 0, z_disp)) # position of the first dipole\n\n # point dipoles\n B1_A, B2_A = make_dipole(pos, xyz)\n B1_B, B2_B = make_dipole(-pos, xyz)\n\n return mu_0/4/np.pi * (B1_A + B2_A + B1_B + B2_B) # field due to magnetic bottle\n\n\ndef calculate_field() -&gt; Tuple[\n np.ndarray, # Y\n np.ndarray, # Z\n np.ndarray, # Bf\n]:\n &quot;&quot;&quot;Setting up graph for dipole magnetic field&quot;&quot;&quot;\n y = np.arange(-10, 10, 0.1) # create a grid of points from y = -10 to 10\n z = np.arange(-10, 10, 0.1) # create a grid of points from z = -10 to 10\n\n # Each 200*200\n Y, Z = np.meshgrid(y, z) # create a rectangular grid out of y and z\n X = np.zeros_like(Y)\n\n # Each 200*200*3\n XYZ = np.stack((X, Y, Z), axis=2)\n Bf = bot_field(XYZ)\n\n return Y, Z, Bf\n\n\ndef calculate_path() -&gt; np.ndarray:\n q = 2 * q_p # charge of helium-4\n m = 4 * m_p # mass of helium-4\n\n dt = 1e-5 # timestep\n end_time = 1 # seconds\n n_samples = round(end_time / dt)\n\n rp = np.empty((n_samples, 3)) # position values\n rp[0, :] = np.array((0, -5, 0)) # initial position (m), above the lower dipole\n\n v_o = 100 # initial velocity (m/s)\n vp = np.array((0, 0, v_o), dtype=np.float64) # velocity is in the z-direction\n\n # Model the particle motion in the field at each time step (Forward Euler Method)\n for it in range(n_samples - 1):\n Bp = bot_field(rp[it, :]) # input the current particle position to get the magnetic field\n rp[it+1, :] = rp[it, :] + dt*vp # update the position of the particle based on this velocity\n\n distance = np.linalg.norm(rp[it+1, :])\n if distance &gt; 20: # If the particle escapes (i.e. exceeds 20 m from origin), cease calculations\n break\n\n Ap = q / m * np.cross(vp, Bp) # calculate the magnetic force on the particle\n vp += dt*Ap # update the velocity of the particle based on this force\n\n return rp\n\n\ndef make_figure() -&gt; Tuple[plt.Figure, plt.Axes]:\n fig, ax = plt.subplots()\n ax.set_xlim(-10, 10)\n ax.set_ylim(-10, 10)\n ax.set_xlabel(&quot;$y$ (m)&quot;)\n ax.set_ylabel(&quot;$z$ (m)&quot;)\n ax.set_title(&quot;Motion of Charged Particle in a Magnetic Bottle&quot;)\n return fig, ax\n\n\ndef plot_field(ax: plt.Axes, Y: np.ndarray, Z: np.ndarray, Bf: np.ndarray) -&gt; None:\n ax.streamplot(Y, Z, Bf[:, :, 1], Bf[:, :, 2], color='orange') # plot the magnetic field\n\n\ndef plot_path(ax: plt.Axes, rp: np.ndarray) -&gt; None:\n &quot;&quot;&quot;Plot the particle motion in the bottle&quot;&quot;&quot;\n ax.plot(rp[:, 1], rp[:, 2], color='navy')\n\n\ndef main() -&gt; None:\n fig, ax = make_figure()\n\n Y, Z, Bf = calculate_field()\n plot_field(ax, Y, Z, Bf)\n\n rp = calculate_path()\n plot_path(ax, rp)\n\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/FzXMW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FzXMW.png\" alt=\"path plot\" /></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T01:41:31.703", "Id": "270479", "ParentId": "270477", "Score": "2" } } ]
{ "AcceptedAnswerId": "270479", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T22:44:21.470", "Id": "270477", "Score": "3", "Tags": [ "python", "numpy", "simulation", "matplotlib", "physics" ], "Title": "Path of a particle in a non-uniform B field" }
270477
<p><strong>Rules:</strong> You should create a function that receives a string with brackets, parentheses, or curly brackets, an example:</p> <pre><code>test('{A}') </code></pre> <p>The function must check that the opening and closing of the brackets are correct. If they are correct it should return <code>true</code>, else it should return <code>false</code>.</p> <p>Examples:</p> <pre><code>'{A}' // true '[A]' // true '(AB)' // true '({A})' // true '((A))' // true '[(A)]' // true '[A}' // false '(A]' // false '({A])' // false '([A))' // false </code></pre> <p>This is the code I did to resolve this problem:</p> <pre class="lang-javascript prettyprint-override"><code>const bracketList = ['{', '[', '(']; // This function return the reverse bracket. For example '[' returns ']'; const getReverseBracket = (bracket) =&gt; { if (bracket == '{') return '}'; if (bracket == '[') return ']'; if (bracket == '(') return ')'; } // This function return the initial bracket. For example if the string starts with '{', then it returns '{'. // In case the string does not start with any bracket, then return null const starterBracket = (string) =&gt; { for (brak of bracketList) { if (string[0] == brak) return brak } return null } // This function is called when any starter bracket has been detected. // if the string start with '(', then it checks if the reverse bracket is in the end of the string. // If this is true, then returns true, else returns false const bracketOk = (string, bracket) =&gt; { let reverseBracket = getReverseBracket(bracket); if (string.slice(-1) == reverseBracket) return true else return false; } // This function removes the brackets of the strings const removeBrackets = (string, bracket) =&gt; { let reverseBracket = getReverseBracket(bracket); return string.replace(bracket, '').replace(reverseBracket, ''); } // This function checks if the string contains any reverse or normal bracket. Depending of the result it return a number that means: // ! 0: if the string contains reverse bracket but no Starter // * 1: if the string contain starter bracket // ? 2: if the string does not contain any bracket const containAnyBracket = (string) =&gt; { const rbracketList = ['}', ']', ')']; for (brak of bracketList) { if (string.includes(brak)) return 1 } for (rbrak of rbracketList) { if (string.includes(rbrak)) return 0 } return 2; } // this function calls all other functions to find out if the string meets the requirements. function testString(string) { let bracket = starterBracket(string) if (bracket) { if (bracketOk(string, bracket)) { let noBracketString = removeBrackets(string, bracket); let containBracket = containAnyBracket(noBracketString); if (containBracket == 2) return true; else if (containBracket == 1) { bracket = starterBracket(noBracketString); if (bracketOk(noBracketString, bracket)) return true; else return false; } else if (containBracket == 0) return false; } else return false; } else return false; } </code></pre> <p>How would you improve the solution code?. I honestly think i could do it better. How you would solve this?</p> <p>Do you have any advice for me about good practices?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T16:00:08.220", "Id": "534223", "Score": "1", "body": "This is too simple to be an answer: you can replace `getReverseBracket` with a plain object that holds the opening bracket as the key, and the closing as the value, like this: `const reverseBracket = {'(': ')'}` (of course, you'd need to add all the missing mappings)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T16:44:35.980", "Id": "534227", "Score": "1", "body": "When you say `for (name of list) {...}`, you're creating a global variable called `name` (`name` is just a placeholder for your multiple times of doing this). Use `for (const name of list) {...}`. Another thing is you're inconsistent with your use of semicolons. In your `bracketOk` and `containAnyBracket` functions, you don't use `;` after `return ` statements, but you do everywhere else. In your `getReverseBracket` function, I would either make it `else if` for the second and third `if`, or make it a `switch` statement." } ]
[ { "body": "<h1>Correctness</h1>\n<p>Your code falsely identifies <code>(hi)there</code> as having unbalanced brackets.</p>\n<h1>Formatting</h1>\n<p>The <code>else return false</code> clauses can be replaced with a single <code>return false</code> at the end of the function. There is no need to treat the 0 as a special case. <code>testString()</code> is not a very descriptive name. <code>getReverseBracket()</code> could be unecessary if you restructured the bracket data. The magic numbers would better be named constants, but they are not necessary anyway.</p>\n<h1>Alternative Solution</h1>\n<p>A stack is all you need to solve this. If you see an opening bracket, add to the stack. If you see the wrong closing bracket, fail. If you see the correct closing bracket, pop the stack. When you get all the way through the string, there should be no brackets left to close.</p>\n<pre><code>const bracketPairs = { '[':']', '{':'}', '(':')' } \nconst closingBrackets = new Set(Object.values(bracketPairs)) \n \nfunction bracketsAreBalanced(text) { \n const open = [] // stack of (closing) brackets that need to be closed \n for (char of text) { \n if (closingBrackets.has(char)) { \n if (char === open[open.length-1]) open.pop() \n else return false; \n } \n if (char in bracketPairs) open.push(bracketPairs[char]) \n } \n return open.length === 0 \n} \n \nconsole.log(bracketsAreBalanced('(hi)there')) \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T11:05:50.140", "Id": "534209", "Score": "6", "body": "This is *the* classic problem for introducing stacks, either explicitly (in an imperative language) or implicitly (using tail recursion in a functional language, keeping information on the call stack). If the solution doesn't use a stack, it is pretty much guaranteed to be more complex than necessary. (In the simpler case where there is only one type of brackets, you don't even need the stack, you only need its depth.) So, I would argue that this is not just an alternative solution but *THE* solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T11:55:35.187", "Id": "534211", "Score": "1", "body": "Why `const open = []`? You intend to modify it, so wouldn't `var` be more appropriate?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T12:57:43.843", "Id": "534214", "Score": "3", "body": "@Andrakis `const` doesn't mean you can't modify the object referenced by the variable, but rather that the *reference* will not change (e.g. `open = []` later would be illegal). If it were meant to be a read-only object, you'd use `Object.freeze` for shallow modifications, or a read-only Proxy for deep modifications." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T13:04:24.390", "Id": "534215", "Score": "3", "body": "The content of the array is modified, but the variable won't be assigned a new array, `const` is more appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T16:47:39.213", "Id": "534229", "Score": "0", "body": "Your code also has the issue that the original post has: global variables in the `for` loops and inconsistent use of semicolons. See my main comment on the post for more details" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T03:37:24.993", "Id": "270481", "ParentId": "270478", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T00:08:38.860", "Id": "270478", "Score": "8", "Tags": [ "javascript", "balanced-delimiters" ], "Title": "Check for balanced brackets in JavaScript" }
270478
<p>My implementation of the lowest common ancestor (<a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" rel="nofollow noreferrer">LCA</a>) algorithm for my tree data structure. I selected the non-preprocessed (naïve) implementation for this first implementation. Support for any number of input positions (1+) seemed appropriate. The tree is not binary and a <a href="https://github.com/FrancoisCarouge/Tree/blob/f7aec81ac214ff644377935a0e21b6aa4426b8ca/include/fcarouge/tree.hpp#L194" rel="nofollow noreferrer">node-based</a> implementation. Any aspect of the code posted is fair game for feedback and criticism.</p> <pre><code>//! @brief Finds the nearest, ancestorial, common element of the positions. //! //! @details The lowest common ancestor (LCA) element of two or more elements in //! a tree is the lowest, deepest element that has both elements as descendants. //! That is the last, shared ancestor located farthest from the root. The LCA //! element of a single valid position iterator is that element iterator itself. //! The LCA element of the single end position iterator is the end iterator //! similarly, the LCA element of a collection of position iterators one or more //! of which is the end iterator is the end iterator because there exists no //! valid LCA element for the collection. //! //! @param first Tree iterator to the first element position of the collection //! to find the LCA. //! //! @param positions The optional second and other remaining element iterators //! of the collection to find the LCA. //! //! @return Iterator to the common most ancestorial element of the elements. //! Returns the `end` iterator if any position is the `end` iterator which is //! equal to the iterator to the element past the container's last element. //! //! @complexity Quadratic in the number of nodes sought from by the height of //! the tree container. [[nodiscard]] constexpr auto lowest_common_ancestor_element(TreeIterator auto first, TreeIterator auto... positions) { if constexpr (sizeof...(positions)) { return [](TreeIterator auto first, TreeIterator auto second, TreeIterator auto... positions) { using iterator_type = decltype(first); if (first == second) { return lowest_common_ancestor_element(first, positions...); } if (!first.node) { return first; } if (!second.node) { return second; } auto *first_ancestor = first.node; do { if (!first_ancestor-&gt;parent) { return lowest_common_ancestor_element(iterator_type{ first_ancestor }, positions...); } auto *second_ancestor = second.node; while ((second_ancestor = second_ancestor-&gt;parent)) { if (first_ancestor == second_ancestor) { return lowest_common_ancestor_element( iterator_type{ first_ancestor }, positions...); } }; } while ((first_ancestor = first_ancestor-&gt;parent)); // Unreachable code under nominal use case. Other invalid cases may have // returned early. The result of the application of library functions to // invalid ranges is undefined per 23.3.1 // [iterator.requirements.general]/12. return iterator_type{}; }(first, positions...); } return first; } </code></pre> <p>Unclear areas:</p> <ul> <li>Is my understanding of the complexity <code>O(Ih)</code> correct? Where <code>I</code> is the number of input node and <code>h</code> the tree height, for a quadratic complexity or simplifies to linear complexity in <code>h</code> for <code>O(h)</code>? It seems to be accepted as <code>O(h)</code> for the typical case for two nodes <code>I = 2</code> but is it applicable here?</li> <li>Is this implementation actually recursive in the number of input position?</li> </ul> <p>The code is tested and updated <a href="https://github.com/FrancoisCarouge/Tree/pull/198/files" rel="nofollow noreferrer">here</a>.</p>
[]
[ { "body": "<h1>Answers to your questions</h1>\n<blockquote>\n<ul>\n<li>Is my understanding of the complexity <span class=\"math-container\">\\$O(Ih)\\$</span> correct? Where <span class=\"math-container\">\\$I\\$</span> is the number of input node and <span class=\"math-container\">\\$h\\$</span> the tree height, for a quadratic complexity or simplifies to linear complexity in <span class=\"math-container\">\\$h\\$</span> for <span class=\"math-container\">\\$O(h)\\$</span>? It seems to be accepted as <span class=\"math-container\">\\$O(h)\\$</span> for the typical case for two nodes <span class=\"math-container\">\\$I = 2\\$</span> but is it applicable here?</li>\n</ul>\n</blockquote>\n<p>It is <span class=\"math-container\">\\$O(Ih)\\$</span>. It might be easier to understand by realizing that your algorihm will always first try to find the LCA of the first two nodes, then you want to find the LCA of the result of the first LCA and the next node, and so on until you processed all the nodes. In the limit for a large number of nodes, each time you go to the next node, you need on about <span class=\"math-container\">\\$h\\$</span> steps.</p>\n<p>It is definitely not <span class=\"math-container\">\\$O(h)\\$</span> as even with a binary tree you can have <span class=\"math-container\">\\$O(2^h)\\$</span> nodes, and your algorithm potentially has to check every node; consider that it can only stop early if it reached the top; and the top of the tree might not be in the set of nodes you want to get the LCA of, or it might be the last.</p>\n<p>For the case of <span class=\"math-container\">\\$I = 2\\$</span>, the complexity is <span class=\"math-container\">\\$O(h^2)\\$</span>, as your algorithm basically becomes:</p>\n<pre><code>for (auto i: parents_of(firsts))\n for (auto j: parents_of(second))\n if (i == j)\n return i;\n</code></pre>\n<blockquote>\n<ul>\n<li>Is this implementation actually recursive in the number of input position?</li>\n</ul>\n</blockquote>\n<p>Yes. This is also easy to see; every time you recursively call <code>lowest_common_ancestor_element()</code>, it is with one less parameter.</p>\n<h1>Reduce the indentation level</h1>\n<p>Almost right at the start you increase the indentation level by two because of the <code>if constexpr</code> and lambda function. You can avoid this by just overloading <code>lowest_common_ancestor_element()</code>; one overload takes just one parameter, the other takes two or more:</p>\n<pre><code>[[nodiscard]] constexpr auto\nlowest_common_ancestor_element(TreeIterator auto first)\n{\n return first;\n}\n\n[[nodiscard]] constexpr auto\nlowest_common_ancestor_element(TreeIterator auto first,\n TreeIterator auto second,\n TreeIterator auto... positions)\n{\n using iterator_type = decltype(first);\n\n if (first == second) {\n return lowest_common_ancestor_element(first, positions...);\n }\n\n ...\n}\n</code></pre>\n<h1>Separate out the case of two nodes</h1>\n<p>You are trying to do everything in one function. As already shown above, it helps to separate out special cases. The one with only one node is easy. For three or more nodes, you basically do:</p>\n<pre><code>[[nodiscard]] constexpr auto\nlowest_common_ancestor_element(TreeIterator auto first,\n TreeIterator auto second,\n TreeIterator auto third,\n TreeIterator auto... positions)\n{\n auto LCA_of_first_and_second = lowest_common_ancestor_element(first, second);\n return lowest_common_ancestor_element(LCA_of_first_and_second, third, positions...);\n}\n</code></pre>\n<p>Then you are left with the case of two nodes, which is where you have the nested loops:</p>\n<pre><code>[[nodiscard]] constexpr auto\nlowest_common_ancestor_element(TreeIterator auto first,\n TreeIterator auto second)\n{\n if (first == second || !first.node) {\n return first;\n }\n\n if (!second.node) {\n return second;\n }\n\n using iterator_type = decltype(first);\n\n auto *first_ancestor = first.node;\n do {\n if (!first_ancestor-&gt;parent) {\n return iterator_type{ first_ancestor };\n }\n auto *second_ancestor = second.node;\n while ((second_ancestor = second_ancestor-&gt;parent)) {\n if (first_ancestor == second_ancestor) {\n return iterator_type{ first_ancestor };\n }\n };\n } while ((first_ancestor = first_ancestor-&gt;parent));\n\n return iterator_type{};\n}\n</code></pre>\n<h1>Have the iterator be able to get its parent</h1>\n<p>The casting between nodes and iterators could be avoided if a <code>TreeIterator</code> would have a function to return an iterator to the parent of the node. Alternatively, have a different iterator type that iterates over ancestors, so you could actually write loops like <code>for (auto first_ancestor: first.ancestors())</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T19:18:21.767", "Id": "534232", "Score": "0", "body": "I appreciate the feedback and criticism @g-sliepen" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T19:49:55.333", "Id": "534233", "Score": "0", "body": "I appreciate the valid feedback and criticism @g-sliepen -- edit: pressed enter too fast.\nI note the iterator ancestor opportunity to be explored further.\nThe indentation level is always a concern, especially so deep here, I was trying to retain a single point of entry of the algorithm for the user simplicity on the API but perhaps inappropriate here. I will seek alternatives to have both: no deep nesting but try to keep a single algorithm entry point. Perhaps there are other ways to make the implementation details private." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T20:13:29.987", "Id": "534235", "Score": "0", "body": "@FrançoisCarouge Technically, since it's a variadic template, there is no single entry point to begin with." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T11:38:25.750", "Id": "270489", "ParentId": "270482", "Score": "0" } } ]
{ "AcceptedAnswerId": "270489", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T03:55:13.937", "Id": "270482", "Score": "2", "Tags": [ "c++", "algorithm", "tree", "c++20" ], "Title": "A Lowest Common Ancestor (LCA) Tree Algorithm" }
270482
<h3>Predeclared class instance tracks the number of regular instances</h3> <p>In VBA, predeclared class instances can act as <a href="https://rubberduckvba.wordpress.com/2018/04/24/factories-parameterized-object-initialization/" rel="nofollow noreferrer">object factories</a>, and in general, it makes sense to keep this instance stateless. However, I needed to count non-default instances and execute reset code whenever all of them were destroyed. I came up with the following code to have the <em>predeclared</em> class instance do this job (code below includes attributes definition, factory, constructor, and instance counting):</p> <p><strong>DbManager.cls</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;DbManager&quot; '@ModuleDescription &quot;Top database API class. Abstract factory for DbConnection.&quot; '@PredeclaredId Option Explicit Private Type TDbManager Connections As Scripting.Dictionary InstanceCount As Long End Type Private this As TDbManager Public Function Create() As DbManager Dim Instance As DbManager Set Instance = New DbManager Instance.Init Set Create = Instance End Function Friend Sub Init() Set this.Connections = New Scripting.Dictionary this.Connections.CompareMode = TextCompare End Sub Private Sub Class_Initialize() If Me Is DbManager Then this.InstanceCount = 0 Else DbManager.InstanceAdd End If End Sub Private Sub Class_Terminate() DbManager.InstanceDel End Sub Public Property Get InstanceCount() As Long If Me Is DbManager Then InstanceCount = this.InstanceCount Else InstanceCount = DbManager.InstanceCount End If End Property Public Property Let InstanceCount(ByVal Value As Long) If Me Is DbManager Then this.InstanceCount = Value Else DbManager.InstanceCount = Value End If End Property Public Sub InstanceAdd() If Me Is DbManager Then this.InstanceCount = this.InstanceCount + 1 Else DbManager.InstanceCount = DbManager.InstanceCount + 1 End If End Sub Public Sub InstanceDel() If Me Is DbManager Then this.InstanceCount = this.InstanceCount - 1 If this.InstanceCount = 0 Then '''' CLEANUP WHEN ALL REGULAR INSTANCES DESTROYED End If Else DbManager.InstanceCount = DbManager.InstanceCount - 1 End If End Sub </code></pre>
[]
[ { "body": "<p>I'm guessing this is a highly redacted version of the <code>DbManager</code> class as it seems to have no 'Db' behavior and no external dependencies. As a consequence, setting the PredeclaredId = True, on the surface, seems unnecessary as there are no parameters in the <code>Create</code> function. That said, I suspect there really <em>are</em> <code>Create</code> parameters in the non-redacted version. Assuming the code works as intended and the above assumptions are also true, a few comments came to mind regarding the code.</p>\n<p><strong>Default instances</strong></p>\n<p>When the PredeclaredId attribute of a VBA ClassModule is set to <code>True</code>, the class is <em>like</em> a static Class in C# and can offer immediately callable methods. This setup provides for a clever workaround for VBA's lack of parameterized constructors. Even so, this default instance is <em>still</em> an 'instance' of the <code>DbManager</code>.</p>\n<p>In this case the goal of counting instances is complicated by the presence of a default instance. The frequent use of <code>If-Else-End If</code> constructs within the <code>DbManager</code> class to discern the Default instance versus the 'Regular' instances highlights this problem. Having the <code>PredeclaredId</code> attribute set to <code>True</code> is getting in the way.</p>\n<p>Further, it is unusual for an object to be responsible for tracking how many of 'itself' have been created/released.</p>\n<p>As it relates to the code provided, it looks as though the <code>DbManager</code> has four responsibilities:</p>\n<ol>\n<li>DbManager Db related interactions. Again, it is assumed that the post is highly redacted and <code>DbManager</code> has functionality beyond what is shown.</li>\n<li>Creating DbManager instances - currently uses the parameterize-able creation mechanism</li>\n<li>Tracking instance creation and deletion</li>\n<li>Resetting 'stuff' whenever the number of DbManager instances 'out in the wild' exceed '0' and then returns to '0'.</li>\n</ol>\n<p>It would seem that all these collateral duties (#2-#4) can be addressed by applying the Single Responsibility Principle (SRP) with a bit more rigor.</p>\n<p>So, one approach to re-organizing the responsibilities:</p>\n<ol>\n<li><code>DbManager</code>: Set the <code>PredeclaredId</code> attribute to <code>False</code>. Let this class focus just on itself. All instances (however created) are 'Regular' instances. This eliminates all the <code>If-Else-End If</code> business.</li>\n<li><code>DbManagerProvider</code>: Is the object that replaces all the previous default instance <code>DbManager.Create()</code> calls. The object provides fully initialized <code>DbManager</code> instances on demand. Setting the <code>PredeclaredId</code> attribute to <code>True</code> for this class could be appropriate. It is likely that this class should be a singleton in your application.</li>\n<li><code>InstanceCountTracker</code>: Injected into each <code>DbManager</code> instance by the <code>DbManagerProvider</code> to support the <code>InstanceDel</code> method call when <code>Class_Terminate()</code> is invoked on a <code>DbManager</code> instance.</li>\n<li><code>IDbResetter</code>: Handles reset operations when the <code>DbManager</code> instance count reaches zero.</li>\n</ol>\n<p>A bit more about <code>IDBResetter</code>: The 'Reset' responsibility is provided as an interface so that it can be swapped out for different 'Reset' implementations. It is my assumption that the <code>Reset</code> operation interacts with the same 'Db' dependencies/resources as a <code>DbManager</code>. Since the <code>DbManagerProvider</code> <em>knows</em> how to create a <code>DbManager</code>, it also <em>knows</em> about all the associated dependencies. So, the default <code>IDbResetter</code> implementation is provided by the <code>DbManagerProvider</code>.</p>\n<p><strong>Testing - Dependency Injection</strong></p>\n<p>To support testing, the <code>DbManagerProvider</code> can be injected with another <code>IDbResetter</code> implementation to provide with each new <code>DbManager</code> instance. In the context of testing, the injected implementation would provide isolation to/from the 'Db' resources and probaby does nothing when 'Reset' is called.</p>\n<p>An example of how distributing the various responsibilities <em>could</em> be implemented.</p>\n<p><strong>DbManager.cls</strong>\nThe <code>DbManager</code> class does nothing but <em>manage the Db</em> now. Without the <code>PredeclaredId</code> attribute set to <code>True</code>, all instances are 'equal'. Instance tracking is provided by the injected <code>IInstanceCountTracker</code> interface.</p>\n<pre><code>Option Explicit\n\nPrivate Type TDbManager\n Connections As Scripting.Dictionary\n InstanceTracker As IInstanceCountTracker\nEnd Type\n\nPrivate this As TDbManager\n\nPrivate Sub Class_Initialize()\n Set this.Connections = New Scripting.Dictionary\n this.Connections.CompareMode = TextCompare\nEnd Sub\n\nPrivate Sub Class_Terminate()\nOn Error Resume Next\n this.InstanceTracker.InstanceDel\nEnd Sub\n\nPublic Property Get InstanceTracker() As IInstanceCountTracker\n InstanceTracker = this.InstanceTracker\nEnd Property\nPublic Property Set InstanceTracker(ByVal RHS As IInstanceCountTracker)\n Set this.InstanceTracker = RHS\nEnd Property\n</code></pre>\n<p><strong>DbManagerProvider</strong>\nThe <code>DbManagerProvider</code> handles instance creation and initialization. It also provides the 'Reset' implementation by implementing the <code>IDbResetter</code> interface.</p>\n<pre><code>Option Explicit\n\nImplements IDbResetter\n\nPrivate Type TDbManagerProvider\n InstanceTracker As IInstanceCountTracker\nEnd Type\n\nPrivate this As TDbManagerProvider\n\nPrivate Sub Class_Initialize()\n Set this.InstanceTracker = New InstanceCountTracker\n \n 'This object provides the default 'Reset' implementation\n Set this.InstanceTracker.Resetter = Me\nEnd Sub\n\nPublic Function CreateDbManager() As DbManager\n Set CreateDbManager = New DbManager\n this.InstanceTracker.InstanceAdd\n \n Set CreateDbManager.InstanceTracker = this.InstanceTracker\nEnd Function\n\nPrivate Sub IDbResetter_Reset()\n '''' CLEANUP WHEN ALL REGULAR INSTANCES DESTROYED\nEnd Sub\n\n'Allow for injecting a Fake/Stub IDbResetter. Use to isolate/ignore necessary Db objects during testing\nPublic Sub InjectResetter(ByVal pResetter As IDbResetter)\n Set this.InstanceTracker.Resetter = pResetter\nEnd Sub\n\n</code></pre>\n<p><strong>InstanceCountTracker</strong>\n<code>InstanceCountTracker</code> encapsulates the instance counting process and the criteria/logic for invoking the 'Reset' process. Contains an <code>IDbResetter</code> reference to invoke the 'Reset' process.</p>\n<pre><code>Option Explicit\n\nImplements IInstanceCountTracker\n\nPrivate Type TInstanceCountTracker\n InstanceCount As Long\n ResetOnNextZero As Boolean\n Resetter As IDbResetter\nEnd Type\n\nPrivate this As TInstanceCountTracker\n\nPrivate Sub IInstanceCountTracker_InstanceAdd()\n this.InstanceCount = this.InstanceCount + 1\n this.ResetOnNextZero = True\nEnd Sub\n\nPrivate Sub IInstanceCountTracker_InstanceDel()\n \n If this.InstanceCount = 0 Then\n 'TODO: Handle/Raise an error\n End If\n \n this.InstanceCount = this.InstanceCount - 1\n \n If this.ResetOnNextZero And this.InstanceCount = 0 Then\n this.ResetOnNextZero = False\n \n this.Resetter.Reset\n End If\nEnd Sub\n\nPrivate Property Get IInstanceCountTracker_Resetter() As IDbResetter\n Set IInstanceCountTracker_Resetter = this.Resetter\nEnd Property\n\nPrivate Property Set IInstanceCountTracker_Resetter(ByVal RHS As IDbResetter)\n Set this.Resetter = RHS\nEnd Property\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T16:46:17.983", "Id": "534326", "Score": "0", "body": "thank you for your feedback. I indeed removed all business logic to focus on the topic. In the code, I try to follow design patterns illustrated by the RDVBA blog. I learned about this implementation of the factory pattern in VBA using predeclared instances from there. The full version of the DbManager class is a top-level API class. It takes care of the environment (by calling a class that loads a custom dll module necessary for db functionality) and generates/manages DbConnection classes. It has only one function directly involving a database - backing up the database." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T16:46:25.983", "Id": "534327", "Score": "0", "body": "The fact that VBA does not have class objects (only instances) does make certain things more complicated. I use the factory pattern (VBA style), and DbManagerProvider implements the abstract factory pattern. Both of them have pros and cons, and I use both. Regular instances are responsible for #1, and in languages supporting class objects, such as Python, classes perform function #2, but in VBA, #2 must be implemented explicitly, and the code goes in the same class module when the factory pattern is used (a bit of a hack), which is what I aim at with DbManager." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T16:46:35.190", "Id": "534328", "Score": "0", "body": "Instance counting is another hack, which I came up with to address a few other VBA limitations (this topic is a part of a separate CR question). I agree that DbManager has multiple responsibilities, and proposed refactoring has certain advantages. On the other hand, these responsibilities have a common theme, focused on the preparation of the environment for database interaction and clean-up at the exit. Except for the backup routine, other DB-related functions are implemented in underlying classes." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T15:28:35.877", "Id": "270539", "ParentId": "270483", "Score": "1" } } ]
{ "AcceptedAnswerId": "270539", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T06:36:03.450", "Id": "270483", "Score": "1", "Tags": [ "object-oriented", "vba" ], "Title": "Predeclared class instance tracks the number of regular instances" }
270483
<p>When you run a jar file by double-clicking on it, you don't get console so all your input/output have to be on GUI. This program solves this problem and gives users/programmers a console which can be used for input/output as done on console by command line programs. So, in effect this program gives a console for JAR programs.</p> <p>Can someone please do the code review. The code is below:</p> <hr /> <h2>Console_For_Java_JAR_Programs.java</h2> <pre><code> import java.io.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class Console_For_Java_JAR_Programs implements KeyListener, ActionListener { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; String title = null; String text = null; JFrame jf = null; JTextArea jta = null; JScrollPane jsp = null; JMenuBar jmb = null; JMenu jm = null; JMenuItem jmi = null; // key codes int BACKSPACE = 8; int ENTER = 10; int PG_UP = 33; // do nothing for this key pressed int PG_DN = 34; // do nothing for this key pressed int END = 35; int HOME = 36; int LEFT_ARROW = 37; int UP_ARROW = 38; // do nothing for this key pressed //int RIGHT_ARROW = 39; // handled by JTextArea int DOWN_ARROW = 40; // do nothing for this key pressed int CTRL = 128; int A = 65; // disable ctrl-a int H = 72; // handle ctrl-h //int DELETE = 127; // handled by JTextArea int initialCaretPosition = 0; int endOfInputCaretPosition = 0; Object lock1 = new Object(); Object lock2 = new Object(); boolean inputAvailable = false; byte[] b = null; int len = -1; int indexIntoByteArray = -1; boolean newLineSent = false; byte endOfInput = -1; byte newLine = 10; boolean enterAlreadyPressedEarlier = false; long Id_keyPressed = 0; long Id_getNextByteFromJTextArea = 0; long Id_outputToJTextArea = 0; public void actionPerformed(ActionEvent ae) { int cCurrPos = jta.getCaretPosition(); jta.selectAll(); jta.copy(); jta.select(cCurrPos, cCurrPos); } // end of actionPerformed public void keyTyped(KeyEvent ke) { } // end of keyTyped public void keyReleased(KeyEvent ke) { } // end of keyReleased public void keyPressed(KeyEvent ke) { Id_keyPressed = Thread.currentThread().getId(); int keyCode = ke.getKeyCode(); if ((keyCode == PG_UP) || (keyCode == PG_DN) || (keyCode == UP_ARROW) || (keyCode == DOWN_ARROW) || ((keyCode == A) &amp;&amp; (ke.getModifiersEx() == CTRL))) { ke.consume(); } else if ((keyCode == LEFT_ARROW) || (keyCode == BACKSPACE) || ((keyCode == H) &amp;&amp; (ke.getModifiersEx() == CTRL))) { synchronized(lock1) { if (jta.getCaretPosition() &lt;= initialCaretPosition) { ke.consume(); } } // end of synchronized block } else if (keyCode == HOME) { synchronized(lock1) { jta.setCaretPosition(initialCaretPosition); ke.consume(); } // end of synchronized block } else if (keyCode == END) { synchronized(lock1) { jta.setCaretPosition(jta.getDocument().getLength()); ke.consume(); } // end of synchronized block } else if (keyCode == ENTER) { // this if block should not exit until all the input has been // processed. synchronized(lock1) { inputAvailable = true; endOfInputCaretPosition = jta.getDocument().getLength(); //if ((endOfInputCaretPosition - initialCaretPosition) == 1) { // only newline was entered, so increment initialCaretPosition if ((enterAlreadyPressedEarlier == true) &amp;&amp; (endOfInputCaretPosition - initialCaretPosition) &gt; 0) { // need to increment initialCaretPosition by 1 to account for last enter pressed initialCaretPosition++; } jta.setCaretPosition(jta.getDocument().getLength()); enterAlreadyPressedEarlier = true; lock1.notifyAll(); } // wait until all input has been processed synchronized(lock2) { //if (Thread.holdsLock(lock2) == true) { System.out.println(&quot;Thread id: &quot; + Thread.currentThread().getId() + &quot;, lock2 is held&quot;); } else { System.out.println(&quot;Thread id: &quot; + Thread.currentThread().getId() + &quot;, lock2 is _not_ held&quot;); } try { lock2.wait(); } catch (Exception e) { //System.out.println(&quot;Exception (debug:1): &quot; + e.getMessage()); } } } // end of if else if } // end of keyPressed byte getNextByteFromJTextArea() { String s = &quot;&quot;; Id_getNextByteFromJTextArea = Thread.currentThread().getId(); synchronized(lock1) { //if (Thread.holdsLock(lock1) == true) { System.out.println(&quot;Thread id: &quot; + Thread.currentThread().getId() + &quot;, lock1 is held&quot;); } else { System.out.println(&quot;Thread id: &quot; + Thread.currentThread().getId() + &quot;, lock1 is _not_ held&quot;); } if (inputAvailable == false) { try { lock1.wait(); } catch (Exception e) { //System.out.println(&quot;Excpetion (debug:2): &quot; + e.getMessage()); //System.exit(1); } // end of try catch } // end of if inputAvailable if (newLineSent == true) { // send endOfInput now, all input has been prcocessed, anyone // waiting on lock2 should be woken up and some variables // should be re-initialized newLineSent = false; b = null; len = -1; indexIntoByteArray = -1; inputAvailable = false; initialCaretPosition = jta.getDocument().getLength(); endOfInputCaretPosition = jta.getDocument().getLength(); synchronized(lock2) { //if (Thread.holdsLock(lock2) == true) { // System.out.println(&quot;lock2 is held..2..Thread id = &quot; + Thread.currentThread().getId()); //} else { // System.out.println(&quot;lock2 is ___not___ held..2..Thread id = &quot; + Thread.currentThread().getId()); //} lock2.notifyAll(); return endOfInput; } } // end of if newLineSent if (len == -1) { // read input len = endOfInputCaretPosition - initialCaretPosition; try { s = jta.getText(initialCaretPosition, len); b = s.getBytes(); // enter is still getting processed, the text area // hasn't been updated with the enter, so send a // newline once all bytes have been sent. } catch (Exception e) { //System.out.println(&quot;Exception (debug:3): &quot; + e.getMessage()); if (b != null) { Arrays.fill(b, (byte)(-1)); } } // end of try catch } // end of if len == -1 // if control reaches here then it means that we have to send a byte indexIntoByteArray++; if (indexIntoByteArray == len) { // send newLine as all input have been sent already newLineSent = true; return newLine; } if (b[indexIntoByteArray] == newLine) { newLineSent = true; } return b[indexIntoByteArray]; } // end of synchronized block } // end of getNextByteFromJTextArea void outputToJTextArea(byte b) { Id_outputToJTextArea = Thread.currentThread().getId(); synchronized(lock1) { char ch = (char)(b); String text = Character.toString(ch); jta.append(text); jta.setCaretPosition(jta.getDocument().getLength()); initialCaretPosition = jta.getCaretPosition(); enterAlreadyPressedEarlier = false; } } // end of outputToJTextArea void configureJTextAreaForInputOutput() { jta.addKeyListener(this); // remove all mouse listeners for (MouseListener listener : jta.getMouseListeners()) { //outputToJTextArea(jta, &quot;\nRemoving mouse listener\n&quot;); jta.removeMouseListener(listener); } // remove all mouse motion listeners for (MouseMotionListener listener : jta.getMouseMotionListeners()) { //outputToJTextArea(jta, &quot;\nRemoving mouse motion listener\n&quot;); jta.removeMouseMotionListener(listener); } // remove all mouse wheel listeners for (MouseWheelListener listener : jta.getMouseWheelListeners()) { //outputToJTextArea(jta, &quot;\nRemoving mouse wheel listener\n&quot;); jta.removeMouseWheelListener(listener); } System.setIn(new InputStream() { @Override public int read() { // we need to sleep here because of some threading issues //try { // Thread.sleep(1); //} catch (Exception e) { //System.out.println(&quot;Exception (debug:4): &quot; + e.getMessage()); //} byte b = getNextByteFromJTextArea(); return ((int)(b)); } }); System.setOut(new PrintStream(new OutputStream() { @Override public void write(int b) { outputToJTextArea((byte)(b)); } })); System.setErr(new PrintStream(new OutputStream() { @Override public void write(int b) { outputToJTextArea((byte)(b)); } })); } // end of configureJTextAreaForInputOutput void createAndShowConsole() { title = &quot;Console&quot;; jf = InitComponents.setupJFrameAndGet(title, (3*screenWidth)/4, (3*screenHeight)/4); jta = InitComponents.setupJTextAreaAndGet(&quot;&quot;, 5000, 100, true, true, true, false, 0, 0, 0, 0); //jta.setBackground(Color.BLACK); //jta.setForeground(Color.LIGHT_GRAY); //jta.setCaretColor(Color.LIGHT_GRAY); jta.setFont(jta.getFont().deriveFont(13.5f)); configureJTextAreaForInputOutput(); jsp = InitComponents.setupScrollableJTextAreaAndGet(jta, 10, 10, (3*screenWidth)/4 - 33, (3*screenHeight)/4 - 79); jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jf.add(jsp); jmb = InitComponents.setupJMenuBarAndGet(); jm = InitComponents.setupJMenuAndGet(&quot;Copy All to Clipboard&quot;); jm.setBorder(BorderFactory.createLineBorder(Color.green, 2)); jmi = InitComponents.setupJMenuItemAndGet(&quot;Copy All to Clipboard&quot;); jm.add(jmi); jmb.add(jm); jmi.addActionListener(this); jf.setJMenuBar(jmb); jf.setLocationRelativeTo(null); jf.setVisible(true); } // end of createAndShowConsole public static void main(String[] args) { Console_For_Java_JAR_Programs cfjjp = new Console_For_Java_JAR_Programs(); cfjjp.createAndShowConsole(); while (true) { try { BufferedReader br = null; String input = &quot;&quot;; System.out.println(); System.out.print(&quot;Enter some input (BufferedReader Example) (press enter after inputting): &quot;); br = new BufferedReader(new InputStreamReader(System.in)); input = br.readLine(); System.out.print(&quot;User input was: &quot; + input + &quot;\n\n&quot;); //System.err.println(&quot;Is this getting printed?\n\n&quot;); System.out.print(&quot;Enter an int, then float, then a string (Scanner Example): &quot;); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); float f = sc.nextFloat(); String s = sc.nextLine(); System.out.println(&quot;Number: &quot; + num); System.out.println(&quot;Float: &quot; + f); System.out.println(&quot;String: &quot; + s); } catch (Exception e) { //System.out.println(&quot;Exception (debug:5): &quot; + e.getMessage()); } } // end of while true } // end of main } // end of Console_For_Java_JAR_Programs class InitComponents { public static JFrame setupJFrameAndGet(String title, int width, int height) { JFrame tmpJF = new JFrame(title); tmpJF.setSize(width, height); tmpJF.setLocationRelativeTo(null); tmpJF.setLayout(null); tmpJF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); return tmpJF; } // end of setupJFrameAndGet public static JTextArea setupJTextAreaAndGet(String text, int rows, int columns, boolean setEditableFlag, boolean setLineWrapFlag, boolean setWrapStyleWordFlag, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JTextArea tmpJTA = new JTextArea(text, rows, columns); tmpJTA.setEditable(setEditableFlag); tmpJTA.setLineWrap(setLineWrapFlag); tmpJTA.setWrapStyleWord(setWrapStyleWordFlag); if (setBoundsFlag == true) { tmpJTA.setBounds(xpos, ypos, width, height); } return tmpJTA; } // end of setupJTextAreaAndGet public static JScrollPane setupScrollableJTextAreaAndGet(JTextArea jta, int xpos, int ypos, int width, int height) { JScrollPane tmpJSP = new JScrollPane(jta); tmpJSP.setBounds(xpos, ypos, width, height); return tmpJSP; } // end of setupScrollableJTextAreaAndGet public static JMenuBar setupJMenuBarAndGet() { JMenuBar tmpJMB = new JMenuBar(); return tmpJMB; } // end of setupJMenuBarAndGet public static JMenu setupJMenuAndGet(String text) { JMenu tmpJM = new JMenu(text); return tmpJM; } // end of setupJMenuAndGet public static JMenuItem setupJMenuItemAndGet(String text) { JMenuItem tmpJMI = new JMenuItem(text); return tmpJMI; } // end of setupJMenuItemAndGet }// end of InitComponents </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T22:52:26.507", "Id": "534354", "Score": "0", "body": "Are your sure it compiles? In method `keyPressed(KeyEvent ke)` you have some illegal syntax `Id_keyPressed = Thread.currentThread().getId();`. Please read [ask]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T06:35:47.357", "Id": "534501", "Score": "0", "body": "Yes, the code compiles and runs. I have posted this code after testing it. I copied the code again from this question and compiled it and ran it. Did you try compiling? Also why do you think that `Id_keyPressed = Thread.currentThread().getId();` has illegal syntax? Can you please explain." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T08:49:23.027", "Id": "270487", "Score": "-1", "Tags": [ "java", "swing", "gui" ], "Title": "Console for Java JAR programs" }
270487
<p>The code below will generate an HTML select tag and options using a text file having list of countries. If the file doesn't exist or contains only empty / white space lines then generate an input box instead of select tag.</p> <hr /> <h2>generate_select_tag_and option_from_list_of_countries.php</h2> <pre><code>&lt;?php $file = &quot;countries.txt&quot;; $file_handle = @fopen($file, &quot;r&quot;); $line = &quot;&quot;; $valid_line_found = false; $label_input_html = '&lt;label style=&quot;position:absolute;right:70%;color:black;&quot;&gt;** Select Country: &lt;/label&gt;' . &quot;\n&quot;; $label_input_html = $label_input_html . '&lt;input style=&quot;position:absolute;left:31%;&quot; type=&quot;text&quot; name=&quot;country&quot; id=&quot;country&quot; maxlength=&quot;40&quot; size=&quot;40&quot;&gt;&lt;br&gt;&lt;br&gt;' . &quot;\n&quot;; $label_input_html = $label_input_html . &quot;\n&quot;; if ($file_handle == false) { echo $label_input_html; goto END; } while(!feof($file_handle)) { $line = fgets($file_handle); $line = trim($line); if (empty($line)) { continue; } else { $valid_line_found = true; break; } } // end of while loop if ($valid_line_found == false) { echo $label_input_html; fclose($file_handle); goto END; } echo '&lt;label for=&quot;country&quot; style=&quot;position:absolute;right:70%;color:black;&quot;&gt;** Select Country: &lt;/label&gt;' . &quot;\n&quot;; echo '&lt;select name=&quot;country&quot; id=&quot;country&quot; size=&quot;1&quot; style=&quot;position:absolute;left:31%;&quot; maxlength=&quot;40&quot; size=&quot;40&quot;&gt;' . &quot;\n&quot;; echo &quot;\t&quot;. '&lt;option value=&quot;&quot;&gt;&lt;/option&gt;' . &quot;\n&quot;; echo &quot;\t&quot;. '&lt;option value=&quot;' . $line . '&quot;&gt;' . $line . '&lt;/option&gt;' . &quot;\n&quot;; while(!feof($file_handle)) { $line = fgets($file_handle); $line = trim($line); if (empty($line)) { continue; } echo &quot;\t&quot;. '&lt;option value=&quot;' . $line . '&quot;&gt;' . $line . '&lt;/option&gt;' . &quot;\n&quot;; } // end of while loop echo '&lt;/select&gt;&lt;br&gt;&lt;br&gt;' . &quot;\n&quot;; echo &quot;\n&quot;; fclose($file_handle); END: ?&gt; </code></pre> <p>The file having list of countries is below:</p> <hr /> <h2>countries.txt</h2> <pre><code> Afghanistan Albania Algeria Andorra Angola Antigua and Barbuda Argentina Armenia Australia Austria Azerbaijan Bahamas Bahrain Bangladesh Barbados Belarus Belgium Belize Benin Bhutan Bolivia Bosnia and Herzegovina Botswana Brazil Brunei Bulgaria Burkina Faso Burundi Cambodia Cameroon Canada Cape Verde Central African Republic Chad Chile China Colombia Comoros Congo Costa Rica Croatia Cuba Cyprus Czech Republic DR Congo Denmark Djibouti Dominica Dominican Republic East Timor Ecuador Egypt El Salvador Equatorial Guinea Eritrea Estonia Eswatini Ethiopia Fiji Finland France Gabon Gambia Georgia Germany Ghana Greece Grenada Guatemala Guinea Guinea-Bissau Guyana Haiti Honduras Hungary Iceland India Indonesia Iran Iraq Ireland Israel Italy Ivory Coast Jamaica Japan Jordan Kazakhstan Kenya Kiribati Kuwait Kyrgyzstan Laos Latvia Lebanon Lesotho Liberia Libya Liechtenstein Lithuania Luxembourg Madagascar Malawi Malaysia Maldives Mali Malta Marshall Islands Mauritania Mauritius Mexico Micronesia Moldova Monaco Mongolia Montenegro Morocco Mozambique Myanmar Namibia Nauru Nepal Netherlands New Zealand Nicaragua Niger Nigeria North Korea North Macedonia Norway Oman Pakistan Palau Palestine Panama Papua New Guinea Paraguay Peru Philippines Poland Portugal Qatar Romania Russia Rwanda Saint Kitts and Nevis Saint Lucia Saint Vincent and the Grenadines Samoa San Marino Saudi Arabia Senegal Serbia Seychelles Sierra Leone Singapore Slovakia Slovenia Solomon Islands Somalia South Africa South Korea South Sudan Spain Sri Lanka Sudan Suriname Sweden Switzerland Syria São Tomé and Príncipe Tajikistan Tanzania Thailand Togo Tonga Trinidad and Tobago Tunisia Turkey Turkmenistan Tuvalu Uganda Ukraine United Arab Emirates United Kingdom United States Uruguay Uzbekistan Vanuatu Vatican City Venezuela Vietnam Yemen Zambia Zimbabwe </code></pre>
[]
[ { "body": "<p>Consider using concatenation:</p>\n<ul>\n<li>rather than <code>$label_input_html = $label_input_html . ...</code></li>\n<li>use <code>$label_input_html .= ...</code></li>\n</ul>\n<p>You're outputting HTML, so end $label_input_html with <code>&lt;br&gt;</code>, not <code>\\n</code>.</p>\n<p>Also see the &quot;\\t&quot;, so if are you doing all that for display purposes, like to show your work, that's fine.</p>\n<p>I don't understand the <code>END:</code>. AFAIA that's completely unnecessary.</p>\n<p>For an optimization, I'd put it all in one loop and test as you go for if you've found a valid line and if you're putting options or select.\nAdditionally, rather than opening and reading line by line:</p>\n<p><code>$lines = file($filename, FILE_IGNORE_NEW_LINES);</code></p>\n<p>.. will return an array or FALSE.</p>\n<p>Then you can loop through the array same way as the file, but without keeping a file open.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T21:11:26.537", "Id": "534244", "Score": "1", "body": "The `END:` is a label used with the [`goto`](https://www.php.net/manual/en/control-structures.goto.php) operator... not really used often in PHP but since PHP is a c-based language it supports it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T22:56:44.957", "Id": "534355", "Score": "0", "body": "Kinda thought that might be it, but at the same time, hoping not, lol. (\"Who put goto's in my PHP?!?\")" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T15:35:37.160", "Id": "270496", "ParentId": "270491", "Score": "3" } }, { "body": "<p>Unless it is preferable to use <code>fopen()</code>, <code>fgets()</code>, <code>fclose()</code>, etc. - e.g. for the sake of performance, it could be simpler to use <a href=\"https://php.net/file_get_contents\" rel=\"nofollow noreferrer\"><code>file_get_contents()</code></a> to read all of the lines into memory and loop over the lines.</p>\n<hr />\n<p>It is extremely rare to see <code>goto</code> within PHP code. Idiomatic PHP code would simply use conditional blocks. Even the <a href=\"https://www.php.net/manual/en/control-structures.goto.php\" rel=\"nofollow noreferrer\">PHP documentation for <code>goto</code> contains the XKCD about the keyword</a>, also mentioned in <a href=\"https://stackoverflow.com/a/46789/1575353\">this SO answer</a> about when that keyword should be used.</p>\n<p><a href=\"https://www.php.net/manual/en/images/0baa1b9fae6aec55bbb73037f3016001-xkcd-goto.png\" rel=\"nofollow noreferrer\"><img src=\"https://www.php.net/manual/en/images/0baa1b9fae6aec55bbb73037f3016001-xkcd-goto.png\" alt=\"1\" /></a></p>\n<hr />\n<p>Some comparisons use loose-equality operators - e.g.</p>\n<blockquote>\n<pre><code>if ($file_handle == false) {\n</code></pre>\n</blockquote>\n<p><a href=\"https://softwareengineering.stackexchange.com/q/126585/244085\">It is a good habit to use strict equality operators</a> whenever possible - especially given <a href=\"https://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting\" rel=\"nofollow noreferrer\">the values that are juggled to be equal to <code>false</code></a>.</p>\n<hr />\n<p>At the end of the PHP file there is a closing PHP tag followed by another blank line</p>\n<blockquote>\n<pre><code>?&gt;\n</code></pre>\n</blockquote>\n<p>Per <a href=\"https://www.php.net/manual/en/language.basic-syntax.phptags.php\" rel=\"nofollow noreferrer\">the PHP documentation</a>:</p>\n<blockquote>\n<p>If a file contains only PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.\n<sup><a href=\"https://www.php.net/manual/en/language.basic-syntax.phptags.php\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T21:52:20.497", "Id": "270511", "ParentId": "270491", "Score": "2" } }, { "body": "<p>The way I see it, your whole process can be boiled down to this:</p>\n<pre><code>&lt;label for=&quot;country&quot;&gt;** Select Country: &lt;/label&gt;\n&lt;?php\n$countries = file('countries.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);\nif (!$countries) {\n echo '&lt;input type=&quot;text&quot; name=&quot;country&quot; id=&quot;country&quot; maxlength=&quot;40&quot; size=&quot;40&quot;&gt;';\n} else {\n array_unshift($countries, '');\n printf(\n '&lt;select name=&quot;country&quot; id=&quot;country&quot;&gt;&lt;option&gt;' . &quot;\\n\\t%s&lt;/option&gt;\\n&lt;/select&gt;&quot;,\n implode(&quot;&lt;/option&gt;\\n\\t&lt;option&gt;&quot;, $countries)\n );\n}\n</code></pre>\n<p>Advice:</p>\n<ol>\n<li><p>Trimming your data should be done at write time (once), so that you never again need to trim your data ever again.</p>\n</li>\n<li><p><code>file()</code> will split your file's data line-by-line -- you can use flags to prevent newlines and empty lines (but those empty lines shouldn't be in your file to begin with).</p>\n</li>\n<li><p>Move all styling to an external style sheet or at the very least out of your html markup -- it just makes your code harder to read with inline styling.</p>\n</li>\n<li><p>Typically, <code>&lt;label&gt;</code> tags include a <code>for</code> attribute to connect with a field's <code>id</code> attribute. This is your choice to make.</p>\n</li>\n<li><p>Don't repeat the same label. More generally, don't repeat yourself.</p>\n</li>\n<li><p>I recommend not declaring single-use variables. If you are concatenating just to print anyhow, then just print as you go.</p>\n</li>\n<li><p>I think you will have a very hard time finding <code>goto</code> in any modern professional applications. I recommend that you skip learning about this technique because when used, it gives a code an outdated smell. Other similar opinions: <a href=\"https://softwareengineering.stackexchange.com/a/329339\">What is so bad with goto when it's used for these obvious and relevant cases?</a>, <a href=\"https://stackoverflow.com/a/1900049/2943403\">Is GOTO in PHP evil?</a>, <a href=\"https://stackoverflow.com/q/7557372/2943403\">Is GOTO a good practice?</a></p>\n</li>\n<li><p><code>maxlength=&quot;40&quot; size=&quot;40&quot;</code> is of no use in a <code>&lt;select&gt;</code> -- just omit these attributes.</p>\n</li>\n<li><p>There is no benefit in repeating an <code>&lt;option&gt;</code>'s text value as its <code>value</code> attribute -- just omit that markup bloat.</p>\n</li>\n<li><p>Because you just need to feed your country names to option tags, you can just <code>implode()</code> instead of using a <code>foreach()</code>. It's up to you if you prefer this technique.</p>\n</li>\n<li><p>I am using <code>array_unshift()</code> to prepend an empty value to the array, this will provide the first empty <code>&lt;option&gt;</code>.</p>\n</li>\n<li><p>Try to avoid relying on <code>&lt;br&gt;</code> for creating vertical space within your HTML document. Using fewer and better chosen html elements to craft your document will make it cleaner and easier to manage through styling.</p>\n</li>\n<li><p>It's no longer in my recommended script, but I do not advise the use of <code>empty()</code> unless your script actually needs to 1. check if the variable is declared and 2. check if the variable has a falsey value. In your script, you called <code>trim()</code> before calling <code>!empty()</code>; it could have been:</p>\n<pre><code>while (!feof($file_handle)) {\n $line = trim(fgets($file_handle));\n if ($line) { // function-less truthy check is the same\n // ...\n }\n}\n</code></pre>\n<p>Looking closer, I don't like that you are accessing/iterating the file contents twice. This is even more reason that I will urge you to adopt my refactored snippet. <code>continue</code> is certainly a useful tool, but in your code, it can be refactored away.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:42:09.557", "Id": "270515", "ParentId": "270491", "Score": "2" } }, { "body": "<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n// It might be good to write functions to describe at least what is happening by their name\n\n $file = &quot;countries.txt&quot;; // fopen is only safe when using this constant, don't accept user input as an argument\n $file_handle = @fopen($file, &quot;r&quot;); // don't use @ to suppres errors, it will make debugging so much harder https://stackoverflow.com/questions/136899/suppress-error-with-operator-in-php \n // file_get_contents() might be better for your situation\n $line = &quot;&quot;;\n $valid_line_found = false;\n\n $label_input_html = '&lt;label style=&quot;position:absolute;right:70%;color:black;&quot;&gt;** Select Country: &lt;/label&gt;' . &quot;\\n&quot;; // inline css can be improved to be written in it's own section / file, then you can reuse the styling.\n $label_input_html = $label_input_html . '&lt;input style=&quot;position:absolute;left:31%;&quot; type=&quot;text&quot; name=&quot;country&quot; id=&quot;country&quot; maxlength=&quot;40&quot; size=&quot;40&quot;&gt;&lt;br&gt;&lt;br&gt;' . &quot;\\n&quot;; // also it's prettier to just generate html outside php tags and not in a variable, even if it's just for syntax highlighting\n $label_input_html = $label_input_html . &quot;\\n&quot;;\n\n if ($file_handle == false) { // comparison should always be done with === unless you have a good reason not to\n echo $label_input_html;\n goto END; // please don't use GOTO https://xkcd.com/292/\n }\n\n while(!feof($file_handle)) { // if you use file_get_contents() you can just loop with a foreach instead\n\n $line = fgets($file_handle);\n $line = trim($line);\n if (empty($line)) {\n continue;\n } else {\n $valid_line_found = true;\n break;\n }\n\n } // end of while loop\n // no need to comment end of loops normally\n\n if ($valid_line_found == false) {\n echo $label_input_html;\n fclose($file_handle);\n goto END;\n }\n\n echo '&lt;label for=&quot;country&quot; style=&quot;position:absolute;right:70%;color:black;&quot;&gt;** Select Country: &lt;/label&gt;' . &quot;\\n&quot;;\n echo '&lt;select name=&quot;country&quot; id=&quot;country&quot; size=&quot;1&quot; style=&quot;position:absolute;left:31%;&quot; maxlength=&quot;40&quot; size=&quot;40&quot;&gt;' . &quot;\\n&quot;;\n echo &quot;\\t&quot;. '&lt;option value=&quot;&quot;&gt;&lt;/option&gt;' . &quot;\\n&quot;;\n echo &quot;\\t&quot;. '&lt;option value=&quot;' . $line . '&quot;&gt;' . $line . '&lt;/option&gt;' . &quot;\\n&quot;;\n\n while(!feof($file_handle)) { // you write a second loop but is not needed, you could combine them\n\n $line = fgets($file_handle);\n $line = trim($line);\n if (empty($line)) {\n continue;\n }\n echo &quot;\\t&quot;. '&lt;option value=&quot;' . $line . '&quot;&gt;' . $line . '&lt;/option&gt;' . &quot;\\n&quot;;\n\n } // end of while loop\n\n echo '&lt;/select&gt;&lt;br&gt;&lt;br&gt;' . &quot;\\n&quot;;\n echo &quot;\\n&quot;;\n\n fclose($file_handle);\n\n END:\n\n?&gt; // don't close php only files to prevent whitespace being send\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T11:39:24.440", "Id": "534296", "Score": "0", "body": "It's generally better to write your observations as prose, rather than hiding them in comments of what appears to be a code-only answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T12:02:59.467", "Id": "534298", "Score": "0", "body": "@TobySpeight Good advice!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T09:25:38.360", "Id": "270528", "ParentId": "270491", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T12:59:28.527", "Id": "270491", "Score": "3", "Tags": [ "php", "html", "io" ], "Title": "Generate HTML select tag and options using a text file having list of countries" }
270491
<p>I am working on a Python package for converting baking recipes. Ideally, the recipe is simply stored as a CSV file read in by the package. Given the recipe can be imperial or metric units of measurement, I am trying to internally convert any set of measurement units to metric for simplicity.</p> <p>The main question I am trying to solve is a light-weight way to store a lot of conversions and ratios given a variety of names that a measurement unit can be.</p> <p>For example, if a recipe has <code>&quot;tsp&quot;</code>, I would want to classify it in the teaspoon family which would consist of <code>['tsp', 'tsps', 'teaspoon', 'teaspoons']</code> and have them all use the <code>TSP_TO_METRIC</code> conversion ratio.</p> <p>Initially, I started as a list of lists but I feel like there may be a more elegant way to store and access these items. I was thinking a dictionary or some sort of JSON file to read in but unsure where the line is between needing an external file versus a long file of constants? I will continue to expand conversions as different ingredients are added so I am also looking for an easy way to scale.</p> <p>Here is an example of the data conversions I am attempting to store. Then I use a series of <code>if-else</code> coupled with <code>any(unit in sublist for sublist in VOLUME_NAMES):</code> to check the lists of lists.</p> <pre><code>TSP_TO_METRIC = 5 TBSP_TO_METRIC = 15 OZ_TO_METRIC = 28.35 CUP_TO_METRIC = 8 * OZ_TO_METRIC PINT_TO_METRIC = 2 * CUP_TO_METRIC QUART_TO_METRIC = 4 * CUP_TO_METRIC GALLON_TO_METRIC = 16 * CUP_TO_METRIC LB_TO_METRIC = 16 * OZ_TO_METRIC STICK_TO_METRIC = 8 * TBSP_TO_METRIC TSP_NAMES = ['TSP', 'TSPS', 'TEASPOON', 'TEASPOONS'] TBSP_NAMES = ['TBSP', 'TBSPS', 'TABLESPOON', 'TABLESPOONS'] CUP_NAMES = ['CUP', 'CUPS'] LB_NAMES = ['LB', 'LBS', 'POUND', 'POUNDS'] OZ_NAMES = ['OZ', 'OUNCE', 'OUNCES'] BUTTER_NAMES = ['STICK', 'STICKS'] EGG_NAMES = ['CT', 'COUNT'] GALLON_NAMES = ['GAL', 'GALLON', 'GALLONS'] VOLUME_NAMES = [TSP_NAMES, TBSP_NAMES, CUP_NAMES, GALLON_NAMES] WEIGHT_NAMES = [LB_NAMES, OZ_NAMES] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T14:49:05.613", "Id": "534217", "Score": "2", "body": "Welcome to Code Review. Please post the full code if possible to give more context to reviewers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T15:25:15.697", "Id": "534222", "Score": "2", "body": "Welcome to the Code Review Community. We only review code that is working as expected, there are other sites that will help you debug your code. None of the sites on [Stack Exchange](https://stackexchange.com/) will write code for you. Please read [Where can I get help?](https://meta.stackexchange.com/questions/129598/which-computer-science-programming-stack-exchange-sites-do-i-post-on) and [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T11:16:47.793", "Id": "534295", "Score": "0", "body": "Is it possible to *recommend a data structure* without knowing the demands on the data?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T13:57:53.877", "Id": "270493", "Score": "-1", "Tags": [ "python" ], "Title": "What would be a recommended data structure for a set of baking conversions?" }
270493
<p>Please, tell me, why this code doesn't work without &quot;-'0'&quot; in this string:&quot;result = 10* result + (str[i++] - '0');&quot;? Объясните, пожалуйста, люди добрые, почему код не работает без &quot;-'0'&quot; в этой строке кода: &quot;result = 10* result + (str[i++] - '0');&quot;?</p> <pre><code> ``` #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;limits.h&gt; int prosoft_atoi(const char *str){ /*инициализируем: sign - знак числа (как положительное), result - результат, i - индекс первого.*/ int sign = 1, result = 0, i = 0; // если встречаем пробел - игнорируем. while (str[i] == ' ') { ++i; } // определим знак результата: if (str[i] == '-' ) { sign = -1; i++; } // преобразуем входные данные в тип int, соблюдая условия: while (str[i] &gt;= '0' &amp;&amp; str[i] &lt;= '9') { result = 10* result + (str[i++] - '0'); } return result * sign; } int main() { printf(&quot;Test1: %d\n&quot;, prosoft_atoi(&quot;1&quot;)); // 1 printf(&quot;Test2: %d\n&quot;, prosoft_atoi(&quot;-1&quot;)); // -1 printf(&quot;Test3: %d\n&quot;, prosoft_atoi(&quot;1234567890&quot;));// 1234567890 printf(&quot;Test4: %d\n&quot;, prosoft_atoi(&quot;&quot;)); // 0 printf(&quot;Test5: %d\n&quot;, prosoft_atoi(&quot;test&quot;)); // 0 printf(&quot;Test6: %d\n&quot;, prosoft_atoi(&quot;22test&quot;)); // 22 printf(&quot;Test7: %d\n&quot;, prosoft_atoi(&quot; 537&quot;)); // 537 printf(&quot;Test8: %d\n&quot;, prosoft_atoi(&quot;xx123&quot;)); // 0 printf(&quot;Test9: %d\n&quot;, prosoft_atoi(NULL)); // 0 printf(&quot;TestA: %d\n&quot;, prosoft_atoi(&quot;123-4&quot;)); // 123 printf(&quot;TestB: %d\n&quot;, prosoft_atoi(&quot;!123&quot;)); // 0 return 0; } ``` </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T16:22:34.740", "Id": "534225", "Score": "1", "body": "You may want to post this question on [so] or [ru.so]. It is off-topic on Code Review. If you decide to post it on Stack Overflow, then \"doesn't work\" is not a sufficient problem description. It would be better to specify exactly the intended output and actual output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T08:51:17.660", "Id": "534274", "Score": "0", "body": "max555, Review `str[i] == ' '` and Test9." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T14:22:13.383", "Id": "270494", "Score": "-2", "Tags": [ "c", "helper" ], "Title": "C, atoi. Своя функция atoi на C" }
270494
<p>This program takes x numbers and displays the mean, median and mode.</p> <p>My goal here was to use classes and class properties the best i could to make the code shorter (honestly i may have just made it longer), so i would like to get some feedback on that.</p> <pre><code>import tkinter as tk from typing import Callable, List from statistics import mean, median, mode &quot;&quot;&quot;MainFunctions = initialization creates 2 starting input boxes and the 3 outputs&quot;&quot;&quot; &quot;&quot;&quot;Input = initialization creates an entry and stringvar for input&quot;&quot;&quot; &quot;&quot;&quot;Output = initialization creates a label for the name of the average and another for the output&quot;&quot;&quot; class Input: def __init__(self, parent: tk.Tk, index: int, callback: Callable[[], None]) -&gt; None: self.value_var = tk.StringVar(parent) self.value_var.trace_add(mode=&quot;write&quot;, callback=callback) self.value_entry = tk.Entry( parent, textvariable=self.value_var ) self.value_entry.grid(row=index, column=1) def delete_entry(self) -&gt; None: self.value_entry.destroy() @property def value(self) -&gt; str: if self.value_var.get(): return self.value_var.get() else: return None @property def row(self) -&gt; int: grid_info = self.value_entry.grid_info() return grid_info['row'] class Output: def __init__(self, parent: tk.Tk, index: int, name: str) -&gt; None: self.name = name self.name_label = tk.Label(parent, text=f&quot;{name}:&quot;) self.name_label.grid(row=index, column=0) self.output_label = tk.Label(parent, text=0) self.output_label.grid(row=index, column=1) def grid(self, row) -&gt; None: self.name_label.grid(row=row, column=0) self.output_label.grid(row=row, column=1) def set_output(self, values) -&gt; None: try: match self.name: case &quot;Mean&quot;: self.output_label.configure(text=mean(values)) case &quot;Median&quot;: self.output_label.configure(text=median(values)) case &quot;Mode&quot;: self.output_label.configure(text=mode(values)) except: self.output_label.configure(text=0) class MainFunctions: def __init__(self, parent: tk.Tk) -&gt; None: self.parent = parent self.inputs = [ Input(self.parent, 0, self.input_callback), Input(self.parent, 1, self.input_callback) ] self.outputs = [ Output( self.parent, 2, &quot;Mean&quot; ), Output( self.parent, 3, &quot;Median&quot; ), Output( self.parent, 4, &quot;Mode&quot; ) ] def create_destroy_input(self) -&gt; None: &quot;&quot;&quot;Counts the number of empty stringvars&quot;&quot;&quot; empty_stringvars = 0 for input in self.inputs[::-1]: if input.value == None: empty_stringvars += 1 &quot;&quot;&quot;Deletes all empty entries and stringvars except for 1, then creates another&quot;&quot;&quot; for input in self.inputs[::-1]: if empty_stringvars &lt;= 1: self.inputs += [ Input( self.parent, len(self.inputs), self.input_callback ) ] return if input.value == None: input.delete_entry() self.inputs.remove(input) empty_stringvars -= 1 def grid_output(self) -&gt; None: &quot;&quot;&quot;To grid the output according to the how many entries there are&quot;&quot;&quot; row = 1 for output in self.outputs: output.grid(row + len(self.inputs)) row += 1 def get_values(self) -&gt; List: &quot;&quot;&quot;Gets all values in entries&quot;&quot;&quot; values = [] for input in self.inputs: try: value = input.value.replace(&quot;,&quot;, &quot;.&quot;) values.append(float(value)) except: pass return values def set_output(self, values) -&gt; None: &quot;&quot;&quot;Calls function for setting output 3 times for each output label&quot;&quot;&quot; for output in self.outputs: output.set_output(values) def input_callback(self, name: str, mode: str, index: str) -&gt; None: &quot;&quot;&quot;Every stringvar calls back to this&quot;&quot;&quot; self.create_destroy_input() self.grid_output() self.set_output(self.get_values()) def main() -&gt; None: root = tk.Tk() root.title(&quot;Mean, median and mode calculator&quot;) root.resizable(width=False, height=False) MainFunctions(root) root.mainloop() if __name__ == &quot;__main__&quot;: main() <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T16:17:18.913", "Id": "270497", "Score": "1", "Tags": [ "python", "calculator", "statistics", "tkinter" ], "Title": "Mean, median and mode GUI" }
270497
<p><em>Terminology usage</em>: I will use chunk, page, partition, or subrange interchangeably.</p> <p>I frequently use and promote using the <code>System.Collections.Concurrent.Partitioner</code> class (<a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent.partitioner.create?view=net-6.0#System_Collections_Concurrent_Partitioner_Create_System_Int32_System_Int32_System_Int32_" rel="nofollow noreferrer">see link</a>). For my particular usage, I always use it for a full indexed collection, i.e. <code>IList&lt;T&gt;</code>. Sometimes I may use it for single-threaded processing lists with fixed range size per chunk, or I may process in parallel threads where I care more about the number of chunks rather than a specific range size.</p> <p>Recently I posted an answer using <code>Partitioner</code> to this <a href="https://codereview.stackexchange.com/questions/270338/sum-of-2-arrays-using-multi-threading/270355#270355">CR question</a>. However, it caused me to think of ways I could enhance a partitioner customized more to my needs and preferred usage.</p> <p>For starters, I wish the boring tuple property names of <code>Item1</code> and <code>Item2</code> had more descriptive names such as <code>FromInclusive</code> and <code>ToExclusive</code>.</p> <p>For logging purposes, it would be nice sometimes to know what chunk number I am currently processing. There could be some other nice things to know such as how many total chunks there are or perhaps whether I am on the last chunk.</p> <p>I almost always work with an item count, meaning the overall range is from 0 to <code>item count – 1</code>. But the manner in how those chunks are formed and how many chunks there will be depends upon whether I pass in a range size, or a desired chunk count. With <code>Partitioner</code>, if I want a specific chunk count, I must first use my desired chunk count to determine the applicable range size, which is what <code>Partitioner</code> is expecting.</p> <p><strong>CLASS PartitionedIndexRange</strong></p> <p>I am most interested in feedback or a review of this class.</p> <pre><code>public class PartitonedIndexRange { private PartitonedIndexRange(int fromInclusive, int toExclusive, int partitionIndex, int partitionsCount) { this.FromInclusive = fromInclusive; this.ToExclusive = toExclusive; this.PartitionIndex = partitionIndex; this.PartitionsCount = partitionsCount; } public int FromInclusive { get; } public int ToExclusive { get; } = -1; public int PartitionIndex { get; } = -1; public int PartitionsCount { get; } public int LastPartitionIndex =&gt; PartitionsCount - 1; public bool IsFirstPartition =&gt; PartitionIndex == 0; public bool IsLastPartition =&gt; PartitionIndex == LastPartitionIndex; public int Size =&gt; ToExclusive - FromInclusive; public static void CheckCannotBeNegative(string name, int value) { if (value &lt; 0) { throw new ArgumentOutOfRangeException(name, $&quot;{name} cannot be negative.&quot;); } } public static void CheckMustBePositive(string name, int value) { if (value &lt;= 0) { throw new ArgumentOutOfRangeException(name, $&quot;{name} must be greater than 0.&quot;); } } public static void Check2CannotBeLessThan1(string name1, int value1, string name2, int value2) { if (value2 &lt; value1) { throw new ArgumentOutOfRangeException(name2, $&quot;{name2} cannot be less than {name1}.&quot;); } } public static IEnumerable&lt;PartitonedIndexRange&gt; GetPartitionsByRangeSize(int itemCount, int rangeSize) { CheckCannotBeNegative(nameof(itemCount), itemCount); CheckMustBePositive(nameof(rangeSize), rangeSize); if (itemCount == 0) { yield break; } int partitionCount = GetChunkSize(itemCount, rangeSize); foreach (var partition in GetPartitions(0, itemCount, partitionCount, rangeSize)) { yield return partition; } } public static IEnumerable&lt;PartitonedIndexRange&gt; GetPartitionsByRangeSize(int fromInclusive, int toExclusive, int rangeSize) { CheckCannotBeNegative(nameof(fromInclusive), fromInclusive); Check2CannotBeLessThan1(nameof(fromInclusive), fromInclusive, nameof(toExclusive), toExclusive); CheckMustBePositive(nameof(rangeSize), rangeSize); if (toExclusive == fromInclusive) { yield break; } int partitionCount = GetChunkSize(toExclusive - fromInclusive, rangeSize); foreach (var partition in GetPartitions(fromInclusive, toExclusive, partitionCount, rangeSize)) { yield return partition; } } public static IEnumerable&lt;PartitonedIndexRange&gt; GetPartitionsByPartitionCount(int itemCount, int partitionCount) { CheckCannotBeNegative(nameof(itemCount), itemCount); CheckMustBePositive(nameof(partitionCount), partitionCount); if (itemCount == 0) { yield break; } int rangeSize = GetChunkSize(itemCount, partitionCount); foreach (var partition in GetPartitions(0, itemCount, partitionCount, rangeSize)) { yield return partition; } } public static IEnumerable&lt;PartitonedIndexRange&gt; GetPartitionsByPartitionCount(int fromInclusive, int toExclusive, int partitionCount) { CheckCannotBeNegative(nameof(fromInclusive), fromInclusive); Check2CannotBeLessThan1(nameof(fromInclusive), fromInclusive, nameof(toExclusive), toExclusive); CheckMustBePositive(nameof(partitionCount), partitionCount); if (toExclusive == fromInclusive) { yield break; } int rangeSize = GetChunkSize(toExclusive - fromInclusive, partitionCount); foreach (var partition in GetPartitions(fromInclusive, toExclusive, partitionCount, rangeSize)) { yield return partition; } } private static IEnumerable&lt;PartitonedIndexRange&gt; GetPartitions(int fromInclusive, int toExclusive, int partitionCount, int rangeSize) { int inclusiveStart = fromInclusive; for (int partitionIndex = 0; partitionIndex &lt; partitionCount; partitionIndex++) { bool isLast = (partitionIndex + 1) == partitionCount; int exclusiveEnd = isLast ? toExclusive : inclusiveStart + rangeSize; var partition = new PartitonedIndexRange(inclusiveStart, exclusiveEnd, partitionIndex, partitionCount); yield return partition; inclusiveStart = exclusiveEnd; } } private static int GetChunkSize(int itemCount, int inputSize) { // &lt;quote&gt;Context means everything.&lt;/quote&gt; // If inputSize is a Range Size, then outputSize is the Partition Count // If inputSize is a Partition Count, then outputSize is the Range Size int outputSize = itemCount / inputSize; return (itemCount % inputSize == 0) ? outputSize : 1 + outputSize; } public override string ToString() { return $&quot;Partition[{PartitionIndex}] Range [{FromInclusive} - {ToExclusive}) Size {Size}&quot;; } } </code></pre> <p>I intentionally made the constructor private restricting usage to the static create methods: <code> GetPartitionsByRangeSize</code> and <code> GetPartitionsByPartitionCount</code>.</p> <p><strong>STATIC CLASS UsageExample</strong></p> <p>Note I am not interested in any feedback or review on the <code>UsageExample</code> class.</p> <pre><code>internal static class UsageExample { private static Random _random { get; } = new Random(); public static void RunSimple() { // Simple example does not need an actual collection. // All we really need is to know the size of a collection. Console.WriteLine(); Console.WriteLine(&quot;SIMPLE EXAMPLE using itemCount&quot;); var itemCount = _random.Next(60_000, 200_000); var rangeSize = 12_500; var partitionsByRangeSize = PartitonedIndexRange.GetPartitionsByRangeSize(itemCount, rangeSize); Console.WriteLine(); Console.WriteLine($&quot;BY RANGE SIZE. ItemCount={itemCount} RangeSize={rangeSize}&quot;); foreach (var partition in partitionsByRangeSize) { Console.WriteLine(partition); } var partitionCount = 9; var partitionsByPartitionCount = PartitonedIndexRange.GetPartitionsByPartitionCount(itemCount, partitionCount); Console.WriteLine(); Console.WriteLine($&quot;BY PARTITION COUNT. ItemCount={itemCount} PartitionCount={partitionCount}&quot;); foreach (var partition in partitionsByPartitionCount) { Console.WriteLine(partition); } } public static void RunSimple2() { Console.WriteLine(); Console.WriteLine(&quot;SIMPLE EXAMPLE using toInclusive &amp; fromExclusive&quot;); var fromInclusive = 1_000; var toExclusive = 12_500; var rangeSize = 1_000; var partitionsByRangeSize = PartitonedIndexRange.GetPartitionsByRangeSize(fromInclusive, toExclusive, rangeSize); Console.WriteLine(); Console.WriteLine($&quot;BY RANGE SIZE. FromInclusive={fromInclusive} ToExclusive={toExclusive} RangeSize={rangeSize}&quot;); foreach (var partition in partitionsByRangeSize) { Console.WriteLine(partition); } var partitionCount = 10; var partitionsByPartitionCount = PartitonedIndexRange.GetPartitionsByPartitionCount(fromInclusive, toExclusive, partitionCount); Console.WriteLine(); Console.WriteLine($&quot;BY PARTITION COUNT. FromInclusive={fromInclusive} ToExclusive={toExclusive} PartitionCount={partitionCount}&quot;); foreach (var partition in partitionsByPartitionCount) { Console.WriteLine(partition); } } public static void RunParallel() { Console.WriteLine(); Console.WriteLine(&quot;PARALLEL EXAMPLE&quot;); var arraySize = _random.Next(88_888, 111_111); var maxDegreeOfParallelism = Environment.ProcessorCount + 1; var example = SumArray.Create(arraySize, maxDegreeOfParallelism); Console.WriteLine(); Console.WriteLine($&quot;Running multi-threaded for ArraySize={arraySize} MaxDegreeOfParallelism={maxDegreeOfParallelism}&quot;); Console.WriteLine(&quot;Custom partitioner with guaranteed order will be called.&quot;); Console.WriteLine(&quot;Parallel.ForEach order is NOT guaranteed.&quot;); var elapsed = example.RunMultiThreaded(); Console.WriteLine($&quot; Elapsed = {elapsed}&quot;); } private class SumArray { // Modified my answer from this original Code Review post: // https://codereview.stackexchange.com/questions/270338/sum-of-2-arrays-using-multi-threading/270355#270355 public int[] ArrayA { get; private set; } = new int[0]; public int[] ArrayB { get; private set; } = new int[0]; public int[] ArrayC { get; private set; } = new int[0]; public int MaxDegreeOfParallelism { get; private set; } = 1; public int ArraySize { get; private set; } = 0; private SumArray(int size, int maxDegreeOfParallelism) { // There are probably more checks that could be done but here are the minimum. if (size &lt;= 0) { throw new ArgumentOutOfRangeException(nameof(size), &quot;Array size must be greater than 0&quot;); } if (maxDegreeOfParallelism &lt;= 0) { throw new ArgumentOutOfRangeException(nameof(maxDegreeOfParallelism), &quot;MaxDegreeOfParallelism must be greater than 0&quot;); } // While I could call Initialize() here, my philosophy is that a constructor // should do the BARE MINIMUM, which is only to set some properties and // then return as quickly as possible. // To that end, I mark the constructor as private, and require accessing // it via the public Create(). this.ArraySize = size; this.MaxDegreeOfParallelism = maxDegreeOfParallelism; } public static SumArray Create(int size, int maxDegreeOfParallelism) { var instance = new SumArray(size, maxDegreeOfParallelism); // Initialize is intentionally run after construction. instance.Initialize(); return instance; } private void Initialize() { ArrayA = new int[ArraySize]; ArrayB = new int[ArraySize]; ArrayC = new int[ArraySize]; // Magic number replacements. // https://en.wikipedia.org/wiki/Magic_number_(programming) // Consider increasing with bigger arrays. // Consider making parameters or properties rather than constants. const int minA = 1; const int maxA = 9999; const int minB = 100_000; const int maxB = 900_000; for (int i = 0; i &lt; ArraySize; i++) { // Consider increasing the magic num ArrayA[i] = _random.Next(minA, maxA); ArrayB[i] = _random.Next(minB, maxB); } } public TimeSpan RunSingleThreaded() { var watch = Stopwatch.StartNew(); for (int i = 0; i &lt; ArraySize; i++) { ArrayC[i] = ArrayA[i] + ArrayB[i]; } watch.Stop(); return watch.Elapsed; } public TimeSpan RunMultiThreaded() { var watch = Stopwatch.StartNew(); var options = new ParallelOptions() { MaxDegreeOfParallelism = MaxDegreeOfParallelism }; // CUSTOM PARTITIONER CALL HERE var partitions = PartitonedIndexRange.GetPartitionsByPartitionCount(ArraySize, MaxDegreeOfParallelism); // While the partitioner sends the partitions in order, // the task scheduler is not guaranteed to process them in the same order. Parallel.ForEach(partitions, options, partition =&gt; { LockedWriteLine($&quot; START {partition}&quot;); for (var i = partition.FromInclusive; i &lt; partition.ToExclusive; i++) { ArrayC[i] = ArrayA[i] + ArrayB[i]; } LockedWriteLine($&quot; END Partition[{partition.PartitionIndex}]&quot;); }); watch.Stop(); return watch.Elapsed; } private object _lockObject = new object(); private void LockedWriteLine(string text) { // I know Console.WriteLine is supposed to be thread safe, // but I am being extra cautious here to remove any doubt. lock (_lockObject) { Console.WriteLine(text); } } } } </code></pre> <p>This requires <code>using System.Diagnostics ;</code> for the <code>Stopwatch</code>. There is a subclass named <code>SumArray</code>, which is a modified example of the answer I provided to this POST. The <code>RunMultiThreaded</code> method uses the custom partitioner. I included some <code>Console.WriteLine</code> to illustrate when a thread starts and ends, which can produce some very interesting results regarding ordering.</p> <p><strong>SAMPLE CONSOLE OUTPUT</strong></p> <pre><code>SIMPLE EXAMPLE BY RANGE SIZE. ItemCount=77032 RangeSize=12500 Partition[0] Range [0 - 12500) Size 12500 Partition[1] Range [12500 - 25000) Size 12500 Partition[2] Range [25000 - 37500) Size 12500 Partition[3] Range [37500 - 50000) Size 12500 Partition[4] Range [50000 - 62500) Size 12500 Partition[5] Range [62500 - 75000) Size 12500 Partition[6] Range [75000 - 77032) Size 2032 BY PARTITION COUNT. Item Count=77032 PartitionCount=9 Partition[0] Range [0 - 8560) Size 8560 Partition[1] Range [8560 - 17120) Size 8560 Partition[2] Range [17120 - 25680) Size 8560 Partition[3] Range [25680 - 34240) Size 8560 Partition[4] Range [34240 - 42800) Size 8560 Partition[5] Range [42800 - 51360) Size 8560 Partition[6] Range [51360 - 59920) Size 8560 Partition[7] Range [59920 - 68480) Size 8560 Partition[8] Range [68480 - 77032) Size 8552 PARALLEL EXAMPLE Running multi-threaded for ArraySize=103493 MaxDegreeOfParallelism=7 Custom partitioner with guaranteed order will be called. Parallel.ForEach order is NOT guaranteed. START Partition[0] Range [0 - 14785) Size 14785 END Partition[0] START Partition[1] Range [14785 - 29570) Size 14785 START Partition[4] Range [59140 - 73925) Size 14785 END Partition[4] START Partition[2] Range [29570 - 44355) Size 14785 END Partition[1] START Partition[6] Range [88710 - 103493) Size 14783 END Partition[6] START Partition[3] Range [44355 - 59140) Size 14785 END Partition[3] START Partition[5] Range [73925 - 88710) Size 14785 END Partition[5] END Partition[2] Elapsed = 00:00:00.0364611 </code></pre> <p>Simple Observations: notice the size of the last partition in the Simple example, chunking by Partition Count produces more balanced chunks than by Range Size.</p> <p>Parallel Observations: although the custom partitioner creates the partitions in a very ordered, sequential manner, the <code>Parallel.ForEach</code> does not guarantee the order of processing. Note that # 2 starts after # 4 but before # 6, 3 and 5, and that # 2 also is the last to complete. Note as well that # 0 started and ended before the others began.</p> <p>Granted that’s just from one sample run. I encourage you to run it several times since the results change. Here is output from another run.</p> <pre><code>SIMPLE EXAMPLE BY RANGE SIZE. ItemCount=130810 RangeSize=12500 Partition[0] Range [0 - 12500) Size 12500 Partition[1] Range [12500 - 25000) Size 12500 Partition[2] Range [25000 - 37500) Size 12500 Partition[3] Range [37500 - 50000) Size 12500 Partition[4] Range [50000 - 62500) Size 12500 Partition[5] Range [62500 - 75000) Size 12500 Partition[6] Range [75000 - 87500) Size 12500 Partition[7] Range [87500 - 100000) Size 12500 Partition[8] Range [100000 - 112500) Size 12500 Partition[9] Range [112500 - 125000) Size 12500 Partition[10] Range [125000 - 130810) Size 5810 BY PARTITION COUNT. ItemCount=130810 PartitionCount=9 Partition[0] Range [0 - 14535) Size 14535 Partition[1] Range [14535 - 29070) Size 14535 Partition[2] Range [29070 - 43605) Size 14535 Partition[3] Range [43605 - 58140) Size 14535 Partition[4] Range [58140 - 72675) Size 14535 Partition[5] Range [72675 - 87210) Size 14535 Partition[6] Range [87210 - 101745) Size 14535 Partition[7] Range [101745 - 116280) Size 14535 Partition[8] Range [116280 - 130810) Size 14530 PARALLEL EXAMPLE Running multi-threaded for ArraySize=98424 MaxDegreeOfParallelism=7 Custom partitioner with guaranteed order will be called. Parallel.ForEach order is NOT guaranteed. START Partition[1] Range [14061 - 28122) Size 14061 START Partition[0] Range [0 - 14061) Size 14061 START Partition[3] Range [42183 - 56244) Size 14061 END Partition[1] START Partition[2] Range [28122 - 42183) Size 14061 END Partition[3] START Partition[4] Range [56244 - 70305) Size 14061 END Partition[0] START Partition[6] Range [84366 - 98424) Size 14058 END Partition[2] END Partition[4] END Partition[6] START Partition[5] Range [70305 - 84366) Size 14061 END Partition[5] Elapsed = 00:00:00.0644807 </code></pre> <p>Here is another example of parallel usage where the <em><strong>last partition starts before the first one!</strong></em></p> <pre><code>PARALLEL EXAMPLE Running multi-threaded for ArraySize=93916 MaxDegreeOfParallelism=7 Custom partitioner with guaranteed order will be called. Parallel.ForEach order is NOT guaranteed. START Partition[1] Range [13417 - 26834) Size 13417 START Partition[6] Range [80502 - 93916) Size 13414 START Partition[3] Range [40251 - 53668) Size 13417 START Partition[2] Range [26834 - 40251) Size 13417 START Partition[5] Range [67085 - 80502) Size 13417 START Partition[4] Range [53668 - 67085) Size 13417 START Partition[0] Range [0 - 13417) Size 13417 END Partition[1] END Partition[6] END Partition[3] END Partition[2] END Partition[5] END Partition[0] END Partition[4] Elapsed = 00:00:00.0346445 </code></pre> <p><strong>CONCERNS</strong></p> <p>While I like <code>UsageExample</code> as a nice way of demonstrating the unpredictable order of parallel tasks, I have little concern about a review of its code. My primary concern is a review of the <code>PartitionedIndexRange</code> class. So far, I like it enough to have it find a welcome on my developer’s toolkit. Having meta data about the partition is nice from a logging perspective in my many applications, most of which are Console apps running unattended via Windows Task Scheduler.</p> <p>I chose to use longer descriptive names for the meta data to clarify the context of the indices. There are the pair of <code>FromInclusive</code> and <code>ToExclusive</code>, which do not contain the word “Index” and save for the capitalization match the old partitioner names. For the meta properties, I could have gone with “Id” or “Index” but chose the longer “PartitionIndex” to be clear. Ditto for “PartitionCount” instead of “Count”.</p>
[]
[ { "body": "<p>I think your approach is simple and straight forward. The overall naming convention is good. Many parts of the class have descriptive naming, and that makes things much easier to understand the class.</p>\n<p>The validations methods such as <code>CheckCannotBeNegative</code>, <code>CheckMustBePositive</code> ..etc. since the actual purpose is to test a value against condition and throw an exception if true, it would be more sensible to include <code>Throw</code> in the method's name, such as <code>ThrowIfNegative</code> as it would tell what to expect from this method. <code>CheckMustBePositive</code> can be also <code>ThrowIfZeroOrNegative</code>.</p>\n<p>for the actual methods <code>GetPartitionsByRangeSize</code> and <code>GetPartitionsByPartitionCount</code> they have similar logic, the only difference I see are three values <code>fromInclusive</code> , <code>partitionCount</code> and <code>rangeSize</code>.</p>\n<p>So basically, you have two strategies, one using a starting and ending indexes, and the second would be to use a chunk size (which is the <code>ItemCount</code>). So, instead of replicating 4 methods, we can do one private method, and recall it with the arguments needed from the public methods instead. This would mean extending <code>GetChunkSize</code> with a way to calculate the <code>partitionCount</code> and <code>rangeSize</code> based on the passed arguments that we did in the public methods.</p>\n<p>My theory is to reduce code redundancy and add more maintainability and readibility, which would results with something like this :</p>\n<pre><code>public static IEnumerable&lt;PartitonedIndexRange&gt; GetPartitionsByPartitionCount(int itemCount, int partitionCount)\n{\n return GetPartitionsByPartitionCount(0, itemCount, partitionCount);\n}\n\npublic static IEnumerable&lt;PartitonedIndexRange&gt; GetPartitionsByPartitionCount(int fromInclusive, int toExclusive, int partitionCount)\n{\n return InternalCreatePartitions(fromInclusive, toExclusive, partitionCount, 0);\n}\n\npublic static IEnumerable&lt;PartitonedIndexRange&gt; GetPartitionsByRangeSize(int itemCount, int rangeSize)\n{\n return GetPartitionsByRangeSize(0, itemCount, rangeSize);\n}\n\npublic static IEnumerable&lt;PartitonedIndexRange&gt; GetPartitionsByRangeSize(int fromInclusive, int toExclusive, int rangeSize)\n{\n return InternalCreatePartitions(fromInclusive, toExclusive, 0, rangeSize);\n}\n\n\nprivate static IEnumerable&lt;PartitonedIndexRange&gt; InternalCreatePartitions(int fromInclusive, int toExclusive, int partitionCount, int rangeSize)\n{\n // here we will put the combined logic of the GetPartitionsByRangeSize &amp;&amp; GetPartitionsByPartitionCount\n}\n</code></pre>\n<p>if you see that we passes <code>0</code> to some arguments, as a way to determine which part of the arguments should be calculated (or ignored) internally. For instance, if we pass a zero to <code>rangeSize</code> then it means we need to calculate the chunk size based on the <code>partitionCount</code>, thus, we will have the <code>rangeSize</code> calculated. While if we pass zero to the <code>fromInclusive</code> this would give us the <code>ItemCount</code> since <code>itemCount = toExclusive</code>.</p>\n<p>based on that, the <code>GetChunkSize</code> would be extended to something like this :</p>\n<pre><code>private static (int PartitionCount, int RangeSize) InternalGetCalculatedChunkSize(int fromInclusive, int toExclusive, int partitionCount, int rangeSize)\n{ \n int calculatedRangeSize = rangeSize;\n\n int calculatedPartitionSize = partitionCount;\n\n // if it's a Partition Count then the fromInclusive would be zero.\n int itemCount = toExclusive - fromInclusive;\n\n // since we passes a zero to one of the operhands (partitionCount OR rangeSize)\n // this shall determines which non-zero part should be used as input size\n int inputSize = Math.Max(calculatedPartitionSize, calculatedRangeSize);\n \n int outputSize = itemCount / (inputSize == 0 ? 1 : inputSize); // extra insurance to prevent from DivideByZeroException\n\n int chunkSize = (itemCount % inputSize == 0) ? outputSize : 1 + outputSize;\n\n if (partitionCount == 0)\n {\n\n calculatedPartitionSize = chunkSize;\n }\n else\n {\n calculatedRangeSize = chunkSize; \n }\n\n // if for some reason the calculation resulted a zero or negative\n ThrowIfZeroOrNegative(nameof(calculatedPartitionSize), calculatedPartitionSize);\n\n ThrowIfZeroOrNegative(nameof(calculatedRangeSize), calculatedRangeSize);\n\n return (PartitionCount: calculatedPartitionSize, RangeSize: calculatedRangeSize);\n}\n</code></pre>\n<p>Now, we can do this :</p>\n<pre><code>private static IEnumerable&lt;PartitonedIndexRangev2&gt; InternalCreatePartitions(int fromInclusive, int toExclusive, int partitionCount, int rangeSize)\n{\n ThrowIfNegative(nameof(fromInclusive), fromInclusive);\n \n ThrowIfNegative(nameof(toExclusive), toExclusive);\n \n ThrowIfNegative(nameof(partitionCount), partitionCount);\n \n ThrowIfNegative(nameof(rangeSize), rangeSize);\n\n if (toExclusive &lt; fromInclusive)\n {\n throw new ArgumentOutOfRangeException(nameof(toExclusive), $&quot;{nameof(toExclusive)} cannot be less than {nameof(fromInclusive)}.&quot;);\n }\n\n // (fromInclusive + toExclusive) == 0 is equivalent to ItemCount == 0 since we passes a zero to fromInclusive.\n if (fromInclusive == toExclusive || (fromInclusive + toExclusive) == 0) \n { \n yield break; \n }\n\n var chunkSize = InternalGetCalculatedChunkSize(fromInclusive, toExclusive, partitionCount, rangeSize);\n \n foreach (var partition in InternalGetPartitionsIterator(fromInclusive, toExclusive, chunkSize.PartitionCount, chunkSize.RangeSize))\n {\n yield return partition;\n }\n}\n\nprivate static IEnumerable&lt;PartitonedIndexRange&gt; InternalGetPartitionsIterator(int fromInclusive, int toExclusive, int partitionCount, int rangeSize)\n{\n int inclusiveStart = fromInclusive;\n\n for (int partitionIndex = 0; partitionIndex &lt; partitionCount; partitionIndex++)\n {\n bool isLast = (partitionIndex + 1) == partitionCount;\n\n int exclusiveEnd = isLast ? toExclusive : inclusiveStart + rangeSize;\n\n var partition = new PartitonedIndexRange(inclusiveStart, exclusiveEnd, partitionIndex, partitionCount);\n\n yield return partition;\n\n inclusiveStart = exclusiveEnd;\n }\n}\n</code></pre>\n<p>With that, the initial theory should work as expected.</p>\n<p>The last thing to add, is using <code>uint</code> instead of <code>int</code> if possible. This would reduce the need of checking for negative integers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T16:01:03.513", "Id": "534318", "Score": "0", "body": "Thank you for the review. I like the idea of using `Throw` in the check method names. The reason I did not use `GetPartitionsByPartitionCount(0, itemCount, partitionCount);` is because the error message should be about `itemCount` and not `fromExclusive`, which is how it would be with yours. Someone who passed in `itemCount` could be confused as to why the exception is mentioning `fromExclusive`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T17:13:50.103", "Id": "534329", "Score": "0", "body": "@RickDavin I see now, well, you could add validations at each method, just to verify the values before it's passed to the main method, that should be fine too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T15:40:02.813", "Id": "270540", "ParentId": "270502", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T18:04:29.190", "Id": "270502", "Score": "2", "Tags": [ "c#" ], "Title": "A Custom Range Partitioner" }
270502
<p>I've built this complex form or at least what I would consider a complex form and it feels really dirty. It felt dirty while I was programming it but I wanted to get it working and then go back and refactor it. The form consists of the days of the week and for each day there are three options (breakfast, lunch, dinner) and for each one of these a user can upload an image and a description. At the very end of the form is a special occasion which doesn't include a breakfast, lunch, or dinner option. Here is what the form looks like:</p> <p><a href="https://i.stack.imgur.com/9GbBK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9GbBK.png" alt="Form build with laravel livewire" /></a></p> <p>The way I got this to is by turning what they checked so for instance Monday and Breakfast into a key which I store in the database as monday_breakfast and this is how I reference it in the code. Below I've included the code for this. Let me know your thoughts, I know there is a better way to accomplish this. Thanks!</p> <p>Create.php</p> <pre class="lang-php prettyprint-override"><code>&lt;?php namespace App\Http\Livewire\Specials\Modals; use App\Http\Livewire\Locations\Show; use Exception; use App\Models\Location; use Illuminate\Http\Request; use Illuminate\Support\Str; use Livewire\WithFileUploads; use LivewireUI\Modal\ModalComponent; class Create extends ModalComponent { use WithFileUploads; public $location; public array $days = []; public array $times = []; public array $dow = []; public array $tod = []; public $photos = []; public $descriptions = []; public function mount(Request $request, Location $location) { $this-&gt;location = $location; $this-&gt;daysOfTheWeek(); $this-&gt;timesOfTheDay(); $this-&gt;setupSpecials(); } public function setupSpecials() { $this-&gt;location-&gt;specials()-&gt;each(function ($value, $key) { if ($value['key'] === 'special_occasion') { array_push($this-&gt;dow, 'special_occasion'); } else { $key = explode('_', $value['key']); array_push($this-&gt;dow, $key[0]); array_push($this-&gt;tod, $value['key']); } if ($value['image']) { $this-&gt;photos[$value['key']] = env('AWS_URL') . $value['image']; } $this-&gt;descriptions[$value['key']] = $value['description']; }); } public function render() { return view('livewire.specials.modals.create'); } public function chosenDay($day) { if (in_array($day, $this-&gt;dow)) { $key = array_search($day, $this-&gt;dow); array_splice($this-&gt;dow, $key); } else { array_push($this-&gt;dow, $day); } } public function chosenTime($time) { if (in_array($time, $this-&gt;tod)) { $key = array_search($time, $this-&gt;tod); array_splice($this-&gt;tod, $key); } else { array_push($this-&gt;tod, $time); } } public function timesOfTheDay() { $this-&gt;times = [ 'breakfast', 'lunch', 'dinner', ]; } public function daysOfTheWeek() { $this-&gt;days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'special_occasion' ]; } public function submit() { $arr3 = []; foreach ($this-&gt;descriptions as $key =&gt; $description) { // if the special exists, update the image and description. if ($special = $this-&gt;location-&gt;specials()-&gt;where('key', $key)-&gt;first()) { $photo = array_key_exists($key, $this-&gt;photos) ? $this-&gt;photos[$key] : null; if ($photo &amp;&amp; !is_string($photo)) { $special-&gt;deleteImageFromS3(); $path = $photo-&gt;storePubliclyAs(request()-&gt;user()-&gt;awsSpecialsDirectory(), Str::random(6), 's3'); $special-&gt;update([ 'image' =&gt; $path, 'description' =&gt; $description, ]); } $special-&gt;update([ 'description' =&gt; $description, ]); } // if the special doesn't exist we're going to create one. if (!$this-&gt;location-&gt;specials()-&gt;where('key', $key)-&gt;count()) { $photo = array_key_exists($key, $this-&gt;photos) ? $this-&gt;photos[$key] : null; if ($photo) { $path = $photo-&gt;storePubliclyAs(request()-&gt;user()-&gt;awsSpecialsDirectory(), Str::random(6), 's3'); } $arr3[$key] = [ 'key' =&gt; $key, 'image' =&gt; $photo ? $path : null, 'description' =&gt; $description, 'day_of_week' =&gt; $key === 'special_occasion' ? 8 : $this-&gt;getIntegerForDayOfWeek(explode('_', $key)[0]), 'meal_of_day' =&gt; $key === 'special_occasion' ? 0 : $this-&gt;getIntegerForMealOfDay(explode('_', $key)[1]), ]; } } $this-&gt;location-&gt;specials()-&gt;createMany($arr3); $this-&gt;closeModalWithEvents([ Show::getName() =&gt; ['locationUpdated', [$this-&gt;location]] ]); } /** * Returns the key for the searched value. * @param $dow * @return false|int|string */ private function getIntegerForDayOfWeek($dow) { return array_search($dow, $this-&gt;days); } /** * Returns the key for the searched value. * @param $mod * @return false|int|string */ private function getIntegerForMealOfDay($mod) { return array_search($mod, $this-&gt;times); } } </code></pre> <p>create.blade.php</p> <pre class="lang-html prettyprint-override"><code>&lt;div&gt; &lt;form class=&quot;space-y-6&quot; wire:submit.prevent=&quot;submit&quot;&gt; &lt;div class=&quot;flex py-3 px-4 bg-gray-100&quot;&gt; &lt;p&gt;Create Special&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;px-4&quot;&gt; @if (session()-&gt;has('success')) &lt;div class=&quot;&quot;&gt; {{ session('message') }} &lt;/div&gt; @endif &lt;div class=&quot;mt-3 grid grid-cols-1 gap-3&quot;&gt; @foreach($days as $key =&gt; $day) &lt;div class=&quot;bg-gray-100 p-2 rounded-md&quot;&gt; &lt;div class=&quot;flex items-center py-2&quot;&gt; &lt;input id=&quot;{{$day}}&quot; wire:click=&quot;chosenDay('{{$day}}')&quot; type=&quot;checkbox&quot; {{ in_array($day, $dow) ? 'checked' : '' }} class=&quot;h-4 w-4 text-cyan-600 focus:ring-cyan-500 border-gray-300 rounded&quot;&gt; &lt;label for=&quot;{{$day}}&quot; class=&quot;ml-2 block text-md font-bold text-gray-900&quot;&gt; {{ $day === 'special_occasion' ? 'Special Occasion' : ucwords($day) }} &lt;/label&gt; &lt;/div&gt; @if(in_array($day, $dow)) @if ($day !== 'special_occasion') @foreach($times as $time) &lt;div class=&quot;py-2 ml-6&quot;&gt; &lt;div class=&quot;flex items-center&quot;&gt; &lt;input id=&quot;{{$day . '_' . $time}}&quot; wire:click=&quot;chosenTime('{{$day . '_' . $time}}')&quot; type=&quot;checkbox&quot; {{ in_array($day . '_' . $time, $tod) ? 'checked' : '' }} class=&quot;h-4 w-4 text-cyan-600 focus:ring-cyan-500 border-gray-300 rounded&quot;&gt; &lt;div class=&quot;flex justify-between items-center w-full&quot;&gt; &lt;label for=&quot;{{$day . '_' . $time}}&quot; class=&quot;ml-2 block text-md font-bold text-gray-900&quot;&gt; {{ ucwords($time) }} &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; @if(in_array($day . '_' . $time, $tod)) &lt;div class=&quot;flex mt-2&quot;&gt; &lt;label for=&quot;{{ 'image_' . $day . '_' . $time }}&quot; class=&quot;flex-none cursor-pointer mr-3 flex items-center justify-center bg-white shadow rounded-md h-14 w-14 text-xs hover:bg-gray-50 hover:border hover:border-gray-300&quot;&gt; @if(array_key_exists($day . '_' . $time, $photos)) &lt;img src=&quot;{{ is_string($photos[$day . '_' . $time]) ? $photos[$day . '_' . $time] : $photos[$day . '_' . $time]-&gt;temporaryUrl() }}&quot; class=&quot;object-cover w-full h-14&quot;&gt; @else Image @endif &lt;input class=&quot;sr-only&quot; id=&quot;{{ 'image_' . $day . '_' . $time }}&quot; wire:model.defer=&quot;photos.{{ $day . '_' . $time }}&quot; accept=&quot;image/*&quot; type=file /&gt; &lt;/label&gt; &lt;div class=&quot;flex-grow&quot;&gt; &lt;textarea type=&quot;text&quot; placeholder=&quot;Enter short description&quot; wire:model.defer=&quot;descriptions.{{ $day . '_' . $time }}&quot; class=&quot;appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm&quot;&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; @endif &lt;/div&gt; @endforeach @else &lt;div class=&quot;flex mt-2&quot;&gt; &lt;label for=&quot;{{ 'image_' . $day }}&quot; class=&quot;flex-none cursor-pointer mr-3 flex items-center justify-center bg-white shadow rounded-md h-14 w-14 text-xs hover:bg-gray-50 hover:border hover:border-gray-300&quot;&gt; @if(array_key_exists($day, $photos)) &lt;img src=&quot;{{ is_string($photos[$day]) ? $photos[$day] : $photos[$day]-&gt;temporaryUrl() }}&quot; class=&quot;object-cover w-full h-14&quot;&gt; @else Image @endif &lt;input class=&quot;sr-only&quot; id=&quot;{{ 'image_' . $day }}&quot; wire:model=&quot;photos.{{ $day }}&quot; accept=&quot;image/*&quot; type=file /&gt; &lt;/label&gt; &lt;div class=&quot;flex-grow&quot;&gt; &lt;textarea type=&quot;text&quot; placeholder=&quot;Enter short description&quot; wire:model=&quot;descriptions.{{ $day }}&quot; class=&quot;appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm&quot;&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/div&gt; @endif @endif &lt;/div&gt; @endforeach &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;flex justify-end py-3 px-4 bg-gray-100&quot;&gt; &lt;button wire:click=&quot;$emit('closeModal')&quot; type=&quot;button&quot; class=&quot;mr-2 inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-gray-600 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-cyan-500&quot;&gt; Cancel &lt;/button&gt; &lt;button type=&quot;submit&quot; class=&quot;inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-cyan-600 hover:bg-cyan-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-cyan-500&quot;&gt; Submit &lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T18:44:35.887", "Id": "270503", "Score": "0", "Tags": [ "php", "laravel" ], "Title": "Choose meals for a week" }
270503
<p>The method is given NxN matrix always powers of 2 and a number,it will return true if the num is found example for 4x4 size: <a href="https://i.stack.imgur.com/HBw2L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HBw2L.png" alt="example" /></a></p> <pre><code> public class Search{ public static boolean search1 (int [][] matrix, int key) { int value = matrix.length / 2; int first_quarter_pivot = matrix[value-1][0]; // represents highest number in first quarter int second_quarter_pivot = matrix[value-1][value]; // represents highest number in second quarter int third_quarter_pivot = matrix[matrix.length-1][value]; // represents highest number in third quarter int fourth_quarter_pivot = matrix[matrix.length-1][0]; // represents highest number in fourth quarter boolean isBoolean = false; int i=0; int j; // if the key is not in the range of biggest smallest number it means he can`t be there. if(!(key &gt;= first_quarter_pivot) &amp;&amp; (key &lt;= fourth_quarter_pivot)) { return false; } // if key is one of the pivots return true; if((key == first_quarter_pivot || (key ==second_quarter_pivot)) || (key == third_quarter_pivot) || (key == fourth_quarter_pivot )) return true; // if key is smaller than first pivot it means key is the first quarter,we limit the search to first quarter. // if not smaller move to the next quarter pivot if(key &lt; first_quarter_pivot){{ j =0; do if(matrix[i][j] == key) { isBoolean = true; break; } else if((j == value)) { j = 0; i++; } else if(matrix[i][j] != key){ j++; } while(isBoolean != true) ; } return isBoolean; } // if key is smaller than second pivot it means key is the second quarter,we limit the search to second quarter. // if not smaller move to the next quarter pivot if(key &lt; second_quarter_pivot){{ j = value;// start (0,value) j++ till j=value do if(matrix[i][j] == key) { isBoolean = true; break; } else if((j == matrix.length-1)) { j = value; i++; } else if(matrix[i][j] != key){ j++; } while(isBoolean != true) ; } return isBoolean; } // if key is smaller than third pivot it means key is the third quarter,we limit the search to third quarter. // if not smaller move to the next quarter pivot if(key &lt; third_quarter_pivot){{ i = value; j = value;// start (0,value) j++ till j=value do if(matrix[i][j] == key) { isBoolean = true; break; } else if((j == matrix.length-1)) { j = value; i++; } else if(matrix[i][j] != key){ j++; } while(isBoolean != true) ; } return isBoolean; } // if key is smaller than fourth pivot it means key is the fourth quarter,we limit the search to fourth quarter. // number must be here because we verfied his existence in the start. if(key &lt; fourth_quarter_pivot){ i = value; j = 0;// start (0,value) j++ till j=value do if(matrix[i][j] == key) { isBoolean = true; break; } else if((j == value)) { j = 0; i++; } else if(matrix[i][j] != key){ j++; } while(isBoolean != true) ; } return isBoolean; } } </code></pre> <p>Is this code any good? from run time efficiency is it still O(n^2)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T08:09:05.247", "Id": "534267", "Score": "0", "body": "This looks unfinished. Have you actually tested it?" } ]
[ { "body": "<p>No, the code doesn't do what it should.</p>\n<ul>\n<li>The method should be recursive (calling itself) or looping, currently it only executes once.</li>\n<li>The complexity is constant O(1) because you dont use recursion or loops.</li>\n</ul>\n<p>Binary-Search Implementation in O(2n):</p>\n<pre><code>static boolean search(int[][] matrix, int key) {\n int n = matrix.length;\n int col = n - 1;\n int row = 0;\n\n while (row &lt; n &amp;&amp; col &gt;= 0) {\n if (key == matrix[row][col]) {\n return true;\n } else if (key &gt; matrix[row][col]) {\n row++;\n } else {\n col--;\n }\n }\n return false;\n}\n</code></pre>\n<p>Maybe also look at <a href=\"https://medium.com/swlh/search-sorted-matrix-in-linear-time-c999234d39a\" rel=\"nofollow noreferrer\">https://medium.com/swlh/search-sorted-matrix-in-linear-time-c999234d39a</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T08:17:29.073", "Id": "534268", "Score": "1", "body": "Some good observations here, though I'm not sure how much help is given by showing code for a matrix sorted by row and column, rather than by quadrant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T08:28:01.013", "Id": "534272", "Score": "0", "body": "thanks for the help but it didn`t post the full code,iv`e edited with the new code,thanks!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T20:30:30.360", "Id": "270507", "ParentId": "270505", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T18:54:48.433", "Id": "270505", "Score": "-1", "Tags": [ "java", "performance" ], "Title": "Search in circular sorted martix" }
270505
<p>I'm currently learning python with an udemy course. I wrote this code, which is meant to be a higher lower game, where the second answer always stays. As far as i tested it my code is working fine, but i feel like many solutions are bad. Its just felt weird coding some of the solutions, but i cant come up with better stuff. I would really aprecciate if someone would oversee my code and give some example for bad writing of myself with a better solution.</p> <p>Heres my code:</p> <pre><code>from art import logo, vs import random from game_data import data from replit import clear def game(): score = 0 print(logo) lost = False options = [&quot;spaceholder&quot;, random.choice(data)] options = print_options(options[1]) while not lost: return_values = compare(options[0], options[1], score) score = return_values[1] lost = return_values[0] if not lost: options = print_options(options[1]) # print both persons def print_options(a): char1 = a new_list = data new_list.remove(char1) char2 = random.choice(data) new_list.append(char1) print(f&quot;Compare A: {char1['name']}, a {char1['description']}, from {char1['country']} &quot;) print(vs) print (f&quot;Against B: {char2['name']}, a {char2['description']}, from {char2['country']} &quot;) return char1, char2 # get input and compare both persons def compare(adict, bdict, score): guess=input(&quot;&quot;&quot;Who has more followers? Type 'A' or 'B': &quot;&quot;&quot;) a = adict[&quot;follower_count&quot;] b = bdict[&quot;follower_count&quot;] if guess == &quot;A&quot; and a &gt; b: clear() print(logo) print(f&quot;Youre right! Current score: {score + 1}&quot;) return False, score +1 elif guess == &quot;B&quot; and b &gt; a: clear() print(logo) print(f&quot;Youre right! Current score: {score + 1}&quot;) return False, score + 1 else: clear() print(logo) print(f&quot;Sorry, thats wrong. Final score: {score}&quot;) return True, score game() </code></pre> <p>Edit: imports: clear is just clearing the console art:</p> <pre><code>logo = &quot;&quot;&quot; __ ___ __ / / / (_)___ _/ /_ ___ _____ / /_/ / / __ `/ __ \/ _ \/ ___/ / __ / / /_/ / / / / __/ / /_/ ///_/\__, /_/ /_/\___/_/ / / /____/_ _____ _____ / / / __ \ | /| / / _ \/ ___/ / /___/ /_/ / |/ |/ / __/ / /_____/\____/|__/|__/\___/_/ &quot;&quot;&quot; vs = &quot;&quot;&quot; _ __ | | / /____ | | / / ___/ | |/ (__ ) |___/____(_) &quot;&quot;&quot; </code></pre> <p>game data:</p> <pre><code>data = [ { 'name': 'Instagram', 'follower_count': 346, 'description': 'Social media platform', 'country': 'United States' }, { 'name': 'Cristiano Ronaldo', 'follower_count': 215, 'description': 'Footballer', 'country': 'Portugal' }, { 'name': 'Ariana Grande', 'follower_count': 183, 'description': 'Musician and actress', 'country': 'United States' }, { 'name': 'Dwayne Johnson', 'follower_count': 181, 'description': 'Actor and professional wrestler', 'country': 'United States' }, { 'name': 'Selena Gomez', 'follower_count': 174, 'description': 'Musician and actress', 'country': 'United States' }, { 'name': 'Kylie Jenner', 'follower_count': 172, 'description': 'Reality TV personality and businesswoman and Self-Made Billionaire', 'country': 'United States' }, { 'name': 'Kim Kardashian', 'follower_count': 167, 'description': 'Reality TV personality and businesswoman', 'country': 'United States' }, { 'name': 'Lionel Messi', 'follower_count': 149, 'description': 'Footballer', 'country': 'Argentina' }, { 'name': 'Beyoncé', 'follower_count': 145, 'description': 'Musician', 'country': 'United States' }, { 'name': 'Neymar', 'follower_count': 138, 'description': 'Footballer', 'country': 'Brasil' }, { 'name': 'National Geographic', 'follower_count': 135, 'description': 'Magazine', 'country': 'United States' }, { 'name': 'Justin Bieber', 'follower_count': 133, 'description': 'Musician', 'country': 'Canada' }, { 'name': 'Taylor Swift', 'follower_count': 131, 'description': 'Musician', 'country': 'United States' }, { 'name': 'Kendall Jenner', 'follower_count': 127, 'description': 'Reality TV personality and Model', 'country': 'United States' }, { 'name': 'Jennifer Lopez', 'follower_count': 119, 'description': 'Musician and actress', 'country': 'United States' }, { 'name': 'Nicki Minaj', 'follower_count': 113, 'description': 'Musician', 'country': 'Trinidad and Tobago' }, { 'name': 'Nike', 'follower_count': 109, 'description': 'Sportswear multinational', 'country': 'United States' }, { 'name': 'Khloé Kardashian', 'follower_count': 108, 'description': 'Reality TV personality and businesswoman', 'country': 'United States' }, { 'name': 'Miley Cyrus', 'follower_count': 107, 'description': 'Musician and actress', 'country': 'United States' }, { 'name': 'Katy Perry', 'follower_count': 94, 'description': 'Musician', 'country': 'United States' }, { 'name': 'Kourtney Kardashian', 'follower_count': 90, 'description': 'Reality TV personality', 'country': 'United States' }, { 'name': 'Kevin Hart', 'follower_count': 89, 'description': 'Comedian and actor', 'country': 'United States' }, { 'name': 'Ellen DeGeneres', 'follower_count': 87, 'description': 'Comedian', 'country': 'United States' }, { 'name': 'Real Madrid CF', 'follower_count': 86, 'description': 'Football club', 'country': 'Spain' }, { 'name': 'FC Barcelona', 'follower_count': 85, 'description': 'Football club', 'country': 'Spain' }, { 'name': 'Rihanna', 'follower_count': 81, 'description': 'Musician and businesswoman', 'country': 'Barbados' }, { 'name': 'Demi Lovato', 'follower_count': 80, 'description': 'Musician and actress', 'country': 'United States' }, { 'name': &quot;Victoria's Secret&quot;, 'follower_count': 69, 'description': 'Lingerie brand', 'country': 'United States' }, { 'name': 'Zendaya', 'follower_count': 68, 'description': 'Actress and musician', 'country': 'United States' }, { 'name': 'Shakira', 'follower_count': 66, 'description': 'Musician', 'country': 'Colombia' }, { 'name': 'Drake', 'follower_count': 65, 'description': 'Musician', 'country': 'Canada' }, { 'name': 'Chris Brown', 'follower_count': 64, 'description': 'Musician', 'country': 'United States' }, { 'name': 'LeBron James', 'follower_count': 63, 'description': 'Basketball player', 'country': 'United States' }, { 'name': 'Vin Diesel', 'follower_count': 62, 'description': 'Actor', 'country': 'United States' }, { 'name': 'Cardi B', 'follower_count': 67, 'description': 'Musician', 'country': 'United States' }, { 'name': 'David Beckham', 'follower_count': 82, 'description': 'Footballer', 'country': 'United Kingdom' }, { 'name': 'Billie Eilish', 'follower_count': 61, 'description': 'Musician', 'country': 'United States' }, { 'name': 'Justin Timberlake', 'follower_count': 59, 'description': 'Musician and actor', 'country': 'United States' }, { 'name': 'UEFA Champions League', 'follower_count': 58, 'description': 'Club football competition', 'country': 'Europe' }, { 'name': 'NASA', 'follower_count': 56, 'description': 'Space agency', 'country': 'United States' }, { 'name': 'Emma Watson', 'follower_count': 56, 'description': 'Actress', 'country': 'United Kingdom' }, { 'name': 'Shawn Mendes', 'follower_count': 57, 'description': 'Musician', 'country': 'Canada' }, { 'name': 'Virat Kohli', 'follower_count': 55, 'description': 'Cricketer', 'country': 'India' }, { 'name': 'Gigi Hadid', 'follower_count': 54, 'description': 'Model', 'country': 'United States' }, { 'name': 'Priyanka Chopra Jonas', 'follower_count': 53, 'description': 'Actress and musician', 'country': 'India' }, { 'name': '9GAG', 'follower_count': 52, 'description': 'Social media platform', 'country': 'China' }, { 'name': 'Ronaldinho', 'follower_count': 51, 'description': 'Footballer', 'country': 'Brasil' }, { 'name': 'Maluma', 'follower_count': 50, 'description': 'Musician', 'country': 'Colombia' }, { 'name': 'Camila Cabello', 'follower_count': 49, 'description': 'Musician', 'country': 'Cuba' }, { 'name': 'NBA', 'follower_count': 47, 'description': 'Club Basketball Competition', 'country': 'United States' } ] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T20:43:14.657", "Id": "534237", "Score": "1", "body": "Welcome to Code Review! Could you tell us about the imports, or better yet, show us that code too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T20:53:10.220", "Id": "534242", "Score": "3", "body": "@200_success I added it. I hope thats what you meant \nAnd thanks for welcoming me here. Im very new to python btw" } ]
[ { "body": "<p>I'm not going to go too heavily into refactoring the whole thing.</p>\n<p>Some basic readability things:</p>\n<pre><code>return_values = compare(options[0], options[1], score)\nscore = return_values[1]\nlost = return_values[0]\n</code></pre>\n<p>It would be much clearer if you did:</p>\n<pre><code>lost, score = compare(options[0], options[1], score)\n</code></pre>\n<p>You have indented things with two spaces, which is odd, normally we use 4 spaces for indenting each level!</p>\n<p>In terms of best practice:</p>\n<p><code>print_options</code> does a couple of things, both selecting another contestant AND printing them out. each function should only do one thing e.g.:</p>\n<pre><code>options = print_options(options[1])\n</code></pre>\n<p>could be: (I made some notes too..)</p>\n<pre><code>def get_options(char1): #a-&gt;char1\n #char1 = a #removed\n new_list = data\n new_list.remove(char1)\n char2 = random.choice(data) # Should be random.choice(new_list)?\n #new_list.append(char1) #This does nothing? \n return char1, char2\n\ndef print_options(options):\n\n print(f&quot;Compare A: {char1['name']}, a {char1['description']}, from {char1['country']} &quot;)\n print(vs)\n print (f&quot;Against B: {char2['name']}, a {char2['description']}, from {char2['country']} &quot;\n\n[...] \n options = get_options(options[1])\n print_options(options)\n</code></pre>\n<p>The following is the same code copied and pasted, this is a good clue you could refactor it.</p>\n<pre><code>if guess == &quot;A&quot; and a &gt; b:\n clear()\n print(logo)\n print(f&quot;Youre right! Current score: {score + 1}&quot;)\n return False, score +1\nelif guess == &quot;B&quot; and b &gt; a:\n clear()\n print(logo)\n print(f&quot;Youre right! Current score: {score + 1}&quot;)\n return False, score + 1\n</code></pre>\n<p>something along the lines of</p>\n<pre><code>if a&gt;b and guess == &quot;A&quot; or a&lt;b and guess == &quot;B&quot;:\n clear()\n print(logo)\n print(f&quot;Youre right! Current score: {score + 1}&quot;)\n return False, score + 1\n</code></pre>\n<p>Also, <code>compare</code> does at least three different things too (Get input, compare, and print) It might be good to split this into two or three functions (<code>get_guess()</code> <code>check_guess(options, guess)</code> and <code>print_result(lost,score)</code> might be a good idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T19:58:15.700", "Id": "534339", "Score": "1", "body": "Pssst, to make your answer _even_ better (It is already great!), maybe mention something about the formatting of the code? 2 indents is really uncommon! ^^" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T20:03:33.763", "Id": "534341", "Score": "2", "body": "I hadn't noticed that, I wondered why I ended up with 6 spaces in mine..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:59:08.147", "Id": "534396", "Score": "0", "body": "Thanks a lot for you answer!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T19:47:06.223", "Id": "270549", "ParentId": "270508", "Score": "3" } }, { "body": "<p>Great tips from the other answer, here are just some more bits and bobs.</p>\n<h3>Use the library capabilities to their fullest</h3>\n<pre><code> char1 = a\n new_list = data\n new_list.remove(char1)\n char2 = random.choice(data)\n new_list.append(char1)\n</code></pre>\n<p>This, in addition to the uncommon indentation sticks out to me. Why are we removing, why are we adding, why are we redefining? Consider</p>\n<pre><code>char1, char2 = random.sample(data, 2)\n</code></pre>\n<h3>Excplicit over implisitt</h3>\n<p>Try to make your code as clear as possible. We are not collecting data, we are collecting <em>twitter data</em>. Similarly we are not returning <em>char1</em> and <em>char2</em> but we are returning <em>celebrities</em> (or really <em>accounts</em>, but too lazy to change my code now)</p>\n<pre><code>def compare(adict, bdict, score):\n guess=input(&quot;&quot;&quot;Who has more followers? Type 'A' or 'B': &quot;&quot;&quot;)\n a = adict[&quot;follower_count&quot;]\n b = bdict[&quot;follower_count&quot;]\n</code></pre>\n<p>This also seems strange, why not just make <code>compare</code> take in <code>a</code> and <code>b</code>. Remember the thing about explicit? Yeah, those should probably not be called <code>adict</code> and <code>bdict</code>.</p>\n<h3>Tricks</h3>\n<p>What would you do if you needed to compare 3 or 4 twitter accounts? You would quickly run into issues. The quick and dirty solution is as follows:</p>\n<p>We sort the accounts in decending order of number of followers</p>\n<pre><code>twitter_account_0, twitter_account_1\n</code></pre>\n<p>Then we label them with letters</p>\n<pre><code>twitter_account_0, twitter_account_1\n A B\n</code></pre>\n<p>The trick now is that we shuffle the <em>labels</em> instead of the actual accounts</p>\n<pre><code>twitter_account_0, twitter_account_1\n B A\n</code></pre>\n<p>So <code>twitter_account_0</code> is really the biggest one. But we print them by label so it looks like</p>\n<pre><code>A, twitter_account_1\nB, twitter_account_0\n</code></pre>\n<p>So when you type B, we just need to check that this corresponds to the account with index 0. Slightly quicker to do this with a lookup table. One <em>very</em> rough implementation looks like the following</p>\n<pre><code>import string\n\nfrom art import logo, vs\nimport random\nfrom game_data import twitter_data\n\nTOTAL_CELEBRITIES = 3\n\n\ndef celebrity_info(celebrities_by_label, info):\n for label, celebrity in celebrities_by_label.items():\n print(label, end=&quot;, &quot;)\n for key in info[:-1]:\n print(celebrity[key], end=&quot;, &quot;)\n print(celebrity[info[-1]], end=&quot;\\n\\n&quot;)\n\n\ndef get_celebritites(twitter, total=TOTAL_CELEBRITIES, sort_key=&quot;follower_count&quot;):\n\n indexes = random.sample(range(0, total), total)\n index_2_label = [string.ascii_uppercase[i] for i in indexes]\n label_2_index = {label: index for index, label in enumerate(index_2_label)}\n\n labels = list(string.ascii_uppercase[0:TOTAL_CELEBRITIES])\n\n celebrities = random.sample(twitter, total)\n celebrities.sort(key=lambda d: d[sort_key], reverse=True)\n celebrities_by_label = {\n label: celebrities[label_2_index[label]] for label in labels\n }\n return (\n celebrities_by_label,\n label_2_index,\n labels,\n )\n\n\n# get input and compare both persons\ndef round(celebrities_by_label, label_2_index, labels):\n celebrity_info(celebrities_by_label, [&quot;name&quot;, &quot;description&quot;])\n\n answer = input(f&quot;Who has more followers? Type one of {labels}: &quot;).upper()\n # The celebrity with index 0 always has the highest count\n return label_2_index.get(answer, None) == 0\n\n\ndef game():\n print(logo)\n celebrities_by_label, label_2_index, labels = get_celebritites(\n twitter_data, TOTAL_CELEBRITIES\n )\n\n points = 0\n while round(celebrities_by_label, label_2_index, labels):\n points += 1\n print(f&quot;Youre right! Current score: {points}&quot;)\n celebrities_by_label, label_2_index, labels = get_celebritites(\n twitter_data, TOTAL_CELEBRITIES\n )\n print(f&quot;Sorry, thats wrong. Final score: {points}\\n&quot;)\n\n celebrity_info(celebrities_by_label, [&quot;name&quot;, &quot;description&quot;, &quot;follower_count&quot;])\n\n\nif __name__ == &quot;__main__&quot;:\n\n game()\n</code></pre>\n<h3>The proper way</h3>\n<p>The proper way is to make a <code>class</code> that is a <code>datastructure</code> and let each twitter account be an instance of this class. I will leave it to you to give this a chance. It is a great opportunity to get introduced to object oriented programming!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:58:45.347", "Id": "534395", "Score": "0", "body": "Thanks for the Answer!\nIt helped a lot and i am going to look into OOP today." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T22:17:36.137", "Id": "270555", "ParentId": "270508", "Score": "0" } } ]
{ "AcceptedAnswerId": "270549", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T20:35:38.467", "Id": "270508", "Score": "4", "Tags": [ "python", "beginner", "number-guessing-game" ], "Title": "Higher lower game" }
270508
<p>I want to use shell scripts to consume kafka messages and return to status. I found that my script wasn't efficient enough.</p> <p>Can I write this script better?</p> <p>I want to output kafka-console-consumer.sh execution time, how do I write it?</p> <p>The input result can be kafka_Check|consumer:0|consumer_time:0.3s</p> <pre><code>#!/bin/bash result=&quot;&quot; vesrion=`ps -ef|grep -v grep|grep -o &quot;kafka.\{,20\}[0-9]-sources.jar&quot;|awk -F '-' '{print $2}'|cut -d . -f 1,-3|tr -d .` OUT_FLAG() { local check_value=$1 local result_value=$2 if [ &quot;${check_value}&quot; -eq 0 ];then result=&quot;$result|${result_value}:0&quot; else result=&quot;$result|${result_value}:1&quot; fi } get_kafka_home(){ local kafka_home_count=`ps -ef|grep kafka-tool|grep -v grep| wc -l` if [ $kafka_home_count -ge 1 ];then kafka_home=`ps -ef|grep kafka\.kafka|grep -v grep | awk -F '/bin/../libs' '{print $2}'|awk -F ':' '{print $2}'` else echo &quot;could not found kafka_home.&quot; exit 1 fi } consumer(){ local consumer_mes=0 TOPIC=`$kafka_home/bin/kafka-topics.sh --zookeeper localhost:2181 --list|grep -v &quot;__consumer_offsets&quot;|grep -m 1 &quot;[a-zA-Z]&quot;` if [ ${vesrion} -gt 0102 ]; then timeout -k 3s 3s $kafka_home/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic $TOPIC --from-beginning --max-messages 1 &amp;&gt;/dev/null consumer_mes=$? OUT_FLAG ${consumer_mes} &quot;consumer_flag&quot; else timeout -k 3s 3s $kafka_home/bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic $TOPIC --from-beginning --new-consumer --max-messages 1 &amp;&gt;/dev/null consumer_mes=$? OUT_FLAG ${consumer_mes} &quot;consumer_flag&quot; fi } main(){ get_kafka_home config_file=&quot;$kafka_home/config/server.properties&quot; if [[ $(ss -ntupl|grep -w '9092' &amp;&gt;/dev/null) -ne 0 ]]&amp;&amp;[[ $(ss -ntupl|grep -w '2181' &amp;&gt;/dev/null) -ne 0 ]] then exit 1 else consumer fi echo &quot;Kafka_Check$result&quot; } main </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T08:18:44.047", "Id": "534269", "Score": "2", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>I'm not good enough with shell programming to really dig into your code, but I have some suggestions nonetheless!</p>\n<ul>\n<li>Make sure you know <em>where</em> the inefficiency is.<br />\nThere's no bennefit from optimizing stuff that isn't the bottleneck. For example, if most of the time that your script takes to run is spent running the stuff from <code>$kafka_home/bin/</code>, then optimizing your own code won't speed things up.</li>\n<li>Avoid redundancy.<br />\nYou're calling <code>ps -ef</code> three times. Can't you just call <code>ps -ef|grep -v grep</code> once and save it to a variable for use in subsequent commands?</li>\n<li>Consider swapping in more modern tools.<br />\nI don't understand what you're doing well enough to question your choice to use bash, but <code>grep</code> looks like low hanging fruit. <a href=\"https://beyondgrep.com/feature-comparison/\" rel=\"nofollow noreferrer\">Several alternatives exist</a>; I've heard <a href=\"https://blog.burntsushi.net/ripgrep/#bonus-benchmarks\" rel=\"nofollow noreferrer\">ripgrep is the best</a>.</li>\n<li><a href=\"https://stackoverflow.com/a/4708569/10135377\">Consider using <code>$()</code> instead of <code>``</code>.</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T03:35:00.737", "Id": "270519", "ParentId": "270513", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:10:12.483", "Id": "270513", "Score": "0", "Tags": [ "bash", "shell" ], "Title": "Bash script to process Kafka messages" }
270513
<p>I have the following piece of code.</p> <pre><code>someFunction = async () =&gt; { let boolean = await this.someFetchFunction(); if (!boolean) boolean = this.someOtherFunction(); return boolean; } </code></pre> <p>I was wondering what would be a cleaner/better solution to this code. Was thinking in a more ES6 way and to avoid reassigning variables</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:31:57.347", "Id": "534246", "Score": "1", "body": "You could do this: `return await this.someFetchFunction() || await this.someOtherFunction();`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:33:15.177", "Id": "534247", "Score": "1", "body": "FYI, I'm not sure this question meets the guidelines here because this is not your real, working code, but rather a made up example. Conceptual coding questions probably belong in stackoverflow. Questions about improving actual working code can be posted here. See the Step 1: box on the right side of [this page](https://codereview.stackexchange.com/questions/ask) for posting guidelines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:34:16.963", "Id": "534248", "Score": "0", "body": "@jfriend00 its a real example, just changed the variable names so that its not distracting or anything like that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:36:56.870", "Id": "534250", "Score": "1", "body": "Oftentimes attempts to simplify the code obscure actual relevant details and that's why both here and stackoverflow want you to post your actual, real code. It's for your own benefit and people often simplify things out of the code they post that turn out to be relevant because they think they're only asking about issue A, but issue B is equally relevant and left out of the question. And, real variable names are NOT distracting at all. In fact, they should help people better understand what the code is doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T23:18:03.550", "Id": "534256", "Score": "1", "body": "Welcome to Code Review! Unfortunately this question does not match what this site is about. Please re-read the Help center page [_What topics can I ask about here?_](https://codereview.stackexchange.com/help/on-topic) - specifically the third question. It would really help reviewers to know what the purpose of the code is. For more information, see [this meta post](https://codereview.meta.stackexchange.com/a/1710/120114)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T22:26:59.567", "Id": "270514", "Score": "1", "Tags": [ "javascript", "ecmascript-6" ], "Title": "avoid reassigning variables in javascript" }
270514
<pre><code>public class Diff { public static int findMinDiff1 (int[] a, int x, int y) { // runtime efficenecy: linear o(n),depends on a.length // memory efficenecy: 1+1+1.. n int temp_x = -1; int temp_y = -1; int min = Integer.MAX_VALUE; for(int i = 0 ; i &lt; a.length ; i++) { if(a[i] == x) temp_x = i; if(a[i] == y) temp_y = i; if(temp_x != -1 &amp;&amp; temp_y != -1) min = Math.abs(temp_x - temp_y); if(min == 0) return 1; } return min; } } </code></pre> <p>do you see any problems here? and whats the memory efficenecy? i hope i got the term right,each time a[i] goes in the loop it<span class="math-container">`</span>s counted as taking memory?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T03:13:38.270", "Id": "534261", "Score": "0", "body": "What tests have you run?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T03:19:14.303", "Id": "534262", "Score": "0", "body": "I just run this on the main System.out.println(Diff.findMinDiff1(myIntArray,1,2)); // 1\n System.out.println(Diff.findMinDiff1(myIntArray,1,3)); // 2\n System.out.println(Diff.findMinDiff1(myIntArray,1,4)); // 3\n System.out.println(Diff.findMinDiff1(myIntArray,1,5)); // 4\n System.out.println(Diff.findMinDiff1(myIntArray,1,6));\n System.out.println(Diff.findMinDiff1(myIntArray,1,7));\n System.out.println(Diff.findMinDiff1(myIntArray,1,8));\n System.out.println(Diff.findMinDiff1(myIntArray,1,9));\n System.out.println(Part2.findMinDiff1(myIntArray,10,10));" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T00:01:25.347", "Id": "270517", "Score": "0", "Tags": [ "java", "performance", "array" ], "Title": "Given Array and 2 ints return the smallest distance between based on index" }
270517
<p>I'm trying to take a raw byte array of audio and trim it.</p> <p>The user selects a start and end value using a range slider.</p> <pre><code>// args are doubles from 0.0 - 1.0 // audio is uncompressed, 16-bit, 44,100hz, MONO public static byte[] trimBytes(byte[] fullLength, double from, double to) { int startingByteIndex = (int) ((double) fullLength.length * from); // samples/frames are two bytes long, so... // we make sure we don't include half a sample (corrupt audio) if (startingByteIndex %2 != 0) { startingByteIndex ++; // use plus, because minus could overflow } int endingByteIndex = (int) ((double) fullLength.length * to); int finalByteArrayLength = endingByteIndex - startingByteIndex; // make sure we don't include half a sample (corrupt audio) if (finalByteArrayLength %2 != 0) { finalByteArrayLength --; // use minus because plus could overflow } byte[] result = new byte[finalByteArrayLength]; for (int i=0; i&lt;finalByteArrayLength; i++) { int indexToCopy = startingByteIndex + i; result[i] = fullLength[indexToCopy]; } return result; } </code></pre> <p>Is this going to crash for any reason or is there a better way to do this?</p> <p>Note: I cannot use Java.nio.</p>
[]
[ { "body": "<blockquote>\n<p>0.0 - 1.0, Is this going to crash for any reason?</p>\n</blockquote>\n<p>As you don't check, there's an <code>ArrayIndexOutOfBoundsException</code> that could be turned into an <code>IllegalArgumentException</code>.</p>\n<blockquote>\n<p>is there a better way to do this?</p>\n</blockquote>\n<ul>\n<li>Avoid copying altogether:<br />\nUse <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/ByteBuffer.html#slice()\" rel=\"nofollow noreferrer\">java.nio.ByteBuffer.slice()</a></li>\n<li>Don't open code what the JRE provides:<br />\nUse <a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#copyOfRange(byte%5B%5D,int,int)\" rel=\"nofollow noreferrer\">java.util.Arrays.copyOfRange(byte[] original, int from, int to)</a>\n<pre><code>final double halfLength = fullLength.length / 2.0;\nArrays.copyOfRange(fullLength,\n (int)Math.ceil(halfLength * from) * 2,\n (int)Math.floor(halfLength * to) * 2);\n</code></pre>\n</li>\n<li>Don't write, never commit/publish uncommented/undocumented code, minimal:\n<pre><code>/** Returns a new Byte[] containing samples from fullLength\n* starting at from (rounded up), ending at to (rounded down). */\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T18:47:31.540", "Id": "534334", "Score": "0", "body": "Thanks! Unfortunately I can't use java.nio due to min Android API requirement of 23. But I will use the remainder of your advice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T05:31:53.967", "Id": "270523", "ParentId": "270518", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T01:24:03.277", "Id": "270518", "Score": "0", "Tags": [ "java", "algorithm", "android", "audio", "byte" ], "Title": "Safely and Quickly Trim a Byte Array of Audio in Java" }
270518
<p>I just had a realization about Mergesort possibly being unstable depending on how it is implemented while reading <a href="https://www.quora.com/Is-merge-sort-a-stable-sorting-algorithm" rel="nofollow noreferrer">this post</a>.</p> <p>Would the merge method below lead to an unstable algorithm?</p> <pre class="lang-java prettyprint-override"><code>private static void merge (Comparable[] arr, Comparable[] aux, int lo, int mid, int hi){ //assert, both subarrays arr[lo:mid] and arr[mid+1:hi] should be sorted // i points to beginning of subarray, arr[lo:mid] int i = lo; // j points to beginning of subarray, arr[mid+1:hi] int j = mid + 1; // copy array elements over to empty aux, arr will be the array used to build up sorted array, aux, will hold elements to be copied over in sorted order. // in other words, aux will hold the two subarrays. one from aux[lo:mid], inclusive on lo and mid, and the other subarray from aux[mid+1:hi] for (int k = lo; k &lt;= hi; k++){ aux[k] = arr[k]; } // k marks where each element should be inserted. int k = lo; // while we have not consumed either sub array 1, aux[lo:mid] or subarray2, aux[mid+1:hi] while (i &lt;= mid &amp;&amp; j &lt;= hi){ // Would logic below lead to unstable mergesort? I think else logic would need to move the element from the first subarray to achieve stability if (isLessThan(aux[i], aux[j])) { arr[k] = aux[i]; i++; } else{ arr[k] = aux[j]; j++; } k++; } // // will only execute if we have not consumed all elements in subarray whose pointer is i for (; i &lt;= mid; i ++){ arr[k] = aux[i]; k++; } // //will only execute if we have not consumed all elements in subarray whose pointer is j for (; j &lt;= hi; j ++){ arr[k] = aux[j]; k++; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T04:50:49.133", "Id": "534264", "Score": "2", "body": "Depends on how `isLessThan` is implemented. If it returns `false` on equal elements, then yes, it is unstable. That said, there is not enough to review, VTC." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T11:43:01.437", "Id": "534297", "Score": "2", "body": "I’m voting to close this question because I don't think a code review would be appreciated by the participant asking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T13:28:51.377", "Id": "534306", "Score": "0", "body": "What do you mean @greybeard" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T13:42:35.043", "Id": "534307", "Score": "1", "body": "I don't think you'd appreciate [open ended feedback on any and all aspects of the code](https://codereview.stackexchange.com/help/on-topic) near as much as an answer to your explicit question about order stability." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T03:59:20.507", "Id": "270521", "Score": "-1", "Tags": [ "java", "mergesort" ], "Title": "Mergesort unstable as Implemented?" }
270521
<p>I'm trying to write a Java function that will take a byte array (of PCM audio recorded on Android) and return an array of data of floats that is intended to be used to create a visual representation of the audio wave -- a standard (quick and dirty) volume over time wave similar to the appearance of what Soundcloud uses.</p> <p>The array returned by this function is not used to produce audio -- it is only for visual use.</p> <p>The visual wave doesn't need to be super high resolution, so the number of elements in the returned array does not need to be as high as the number of elements in the actual audio byte array that is passed in.</p> <p>Anyway, I'm just making sure that I'm not introducing any unforeseen bugs or that I'm not approaching the problem the wrong way... or if there might be a simpler way.</p> <pre><code> // audio is uncompressed, 16-bit, 44,100hz, MONO // which is two bytes per sample public static float[] getVisualWaveData(byte[] fromBytes) { // decide the minimum resolution of the resulting audio wave final int MINIMUM_TARGET_RESOLUTION_IN_SAMPLES = 300; int targetResolutionInSamples = fromBytes.length / 2; boolean resolutionStillTooHigh = true; // divide original byte array length by 2 until threshold is crossed // then step back above threshold int exponent = 1; while (resolutionStillTooHigh) { targetResolutionInSamples = targetResolutionInSamples / 2; exponent++; if (targetResolutionInSamples &lt; MINIMUM_TARGET_RESOLUTION_IN_SAMPLES) { resolutionStillTooHigh = false; targetResolutionInSamples = targetResolutionInSamples * 2; exponent--; } } // create resulting array of floats // by stepping through original byte array in steps of (2*Math.pow(2,exponent)) // and adding the adjacent bytes and dividing that value by the max float[] result = new float[targetResolutionInSamples]; int counter = 0; for (int i = 0; i&lt;fromBytes.length; i=i + (int) (2*Math.pow(2,exponent))) { // Effectively &quot;add&quot; two adjacent bytes to get the original short. // Android audio is little endian short byte1 = (short) (fromBytes[i] * Math.pow(2,8)); // correct (increase) weight of first byte short byte2 = (short) fromBytes[i+1]; // convert one sample (presumably a short that is comprised of two adjacent bytes) float resultingFloat = (float) (byte1 + byte2)/(float) Short.MAX_VALUE; // &lt;----------- !!!!!!! DANGER DANGER result[counter] = resultingFloat; counter++; } return result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T05:44:54.183", "Id": "534266", "Score": "2", "body": "`array of [values] intended to be used to create a visual representation` of what? Volume over time? Over frequency? Note that several hundred samples of *samples* will most likely be noise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T10:25:41.487", "Id": "534293", "Score": "2", "body": "As `16-bit…per sample` spells two bytes *with different weight*, I don't see how revision 1 could work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T18:41:44.863", "Id": "534333", "Score": "0", "body": "I've revised it a bit. thx" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T19:00:26.867", "Id": "534338", "Score": "0", "body": "I see, but the ratio of weights is 2 to the power of `Byte.SIZE` - in \"base conversion\", you don't raise \"digit values\" to powers according to their position: You multiply by the *base* raised to such a power (Possibly implicitly: Horner)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T21:19:44.620", "Id": "534349", "Score": "0", "body": "Corrected! (I think)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T22:17:05.200", "Id": "534352", "Score": "0", "body": "Scaling now looks promising. There is the unresolved issue of what interpretation the result values are to allow. Aaand…yet another catch in converting from byte to numerical sample: bytes are signed. To open code conversion of a non-most-significant `byte` to \"just an 8 bit natural number\", please refer the JLS (5.1.2-6 Primitive Conversions)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T05:18:15.577", "Id": "270522", "Score": "0", "Tags": [ "java", "algorithm", "android", "audio", "byte" ], "Title": "Converting Audio Bytes to Array of Floats for Visual Representation" }
270522
<p><code>strcat_new()</code> function, not present in standard C library.</p> <p>Syntax: <code>char *strcat_new(char *delim, long num_args, ...);</code></p> <p>The code is below. Can someone please do the code review?</p> <hr /> <h2>strcat_new.c</h2> <pre><code> #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdarg.h&gt; #include &quot;strcat_new.h&quot; /* * strcat_new: * * Parameters: * num_args: number of variable arguments that are passed to this function * excluding the 'delim' string. * ...: Variable number of pointers to character arrays. * * Description: * strcat_new concatenates all the strings/character arrays passed to it. If * 'delim' is not NULL then after every string, the 'delim' string is concatenated. * It allocates a new character array whose size is equal to the sum of the * lengths of all strings passed to it plus 1 (extra 1 for terminating null byte). * It then concatenates all the strings passed to it separated by 'delim' string * into the newly allocated character array and then returns the pointer to * the newly allocated character array. If memory allocation fails then NULL is returned. * * It is the responsibility of the caller to free the allocated memory. */ char *strcat_new(char *delim, long num_args, ...) { va_list valist; long i = 0; long j = 0; long iica = 0; // iica - index into character array long len = 0; long delim_len = 0; long total_len = 0; char *new_char_array = NULL; char *temp = NULL; if (num_args &lt;= 0) return NULL; if (delim) { delim_len = strlen(delim); } va_start(valist, num_args); for (i = 0; i &lt; num_args; i++) { temp = va_arg(valist, char *); if (!temp) continue; total_len = total_len + strlen(temp) + delim_len; } va_end(valist); total_len = total_len - delim_len; // remove the last delimiter total_len = total_len + 1; // 1 extra for terminating null byte new_char_array = malloc(total_len); if (!new_char_array) return NULL; va_start(valist, num_args); for (i = 0; i &lt; num_args; i++) { temp = va_arg(valist, char *); if (!temp) continue; len = strlen(temp); for (j = 0; j &lt; len; j++) { new_char_array[iica] = temp[j]; iica++; } if (i &lt; (num_args - 1)) { for (j = 0; j &lt; delim_len; j++) { new_char_array[iica] = delim[j]; iica++; } } } va_end(valist); new_char_array[iica] = 0; return new_char_array; } // end of strcat_new </code></pre> <hr /> <h2>strcat_new.h</h2> <pre><code> #ifndef _STRCAT_NEW_H_ #define _STRCAT_NEW_H_ /* * strcat_new: * * Parameters: * num_args: number of variable arguments that are passed to this function * excluding the 'delim' string. * ...: Variable number of pointers to character arrays. * * Description: * strcat_new concatenates all the strings/character arrays passed to it. If * 'delim' is not NULL then after every string, the 'delim' string is concatenated. * It allocates a new character array whose size is equal to the sum of the * lengths of all strings passed to it plus 1 (extra 1 for terminating null byte). * It then concatenates all the strings passed to it separated by 'delim' string * into the newly allocated character array and then returns the pointer to * the newly allocated character array. If memory allocation fails then NULL is returned. * * It is the responsibility of the caller to free the allocated memory. */ char *strcat_new(char *delim, long num_args, ...); #endif </code></pre> <hr /> <h2>test_strcat_new.c</h2> <pre><code> #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &quot;strcat_new.h&quot; int main(void) { char *a = strcat_new(&quot;;:?&quot;, 4, &quot;abc&quot;, &quot;123&quot;, &quot;xyz&quot;, &quot;455&quot;); printf(&quot;\n&quot;); printf(&quot;a = %s, strlen(a) = %lu\n&quot;, a, strlen(a)); free(a); a = strcat_new(NULL, 3, &quot;123&quot;, &quot;xyz&quot;, &quot;455&quot;); printf(&quot;\n&quot;); printf(&quot;a = %s, strlen(a) = %lu\n&quot;, a, strlen(a)); free(a); a = strcat_new(NULL, 0, &quot;123&quot;, &quot;xyz&quot;, &quot;455&quot;); printf(&quot;\n&quot;); printf(&quot;a = %s, strlen(a) = %lu\n&quot;, a, a?strlen(a):0); free(a); a = strcat_new(NULL, -1, &quot;123&quot;, &quot;xyz&quot;, &quot;455&quot;); printf(&quot;\n&quot;); printf(&quot;a = %s, strlen(a) = %lu\n&quot;, a, a?strlen(a):0); free(a); a = strcat_new(&quot;=&quot;, 4, &quot;abc&quot;, &quot;123&quot;, &quot;xyz&quot;, &quot;455&quot;); printf(&quot;\n&quot;); printf(&quot;a = %s, strlen(a) = %lu\n&quot;, a, strlen(a)); free(a); a = strcat_new(&quot;{(=%$^%^&amp;&amp;(&amp;)}&quot;, 4, &quot;abc&quot;, &quot;123&quot;, &quot;xyz&quot;, &quot;455&quot;); printf(&quot;\n&quot;); printf(&quot;a = %s, strlen(a) = %lu\n&quot;, a, strlen(a)); free(a); printf(&quot;\n&quot;); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T13:26:31.797", "Id": "534305", "Score": "0", "body": "Please do not edit the question, especially the code, after an answer has been posted. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T15:18:06.707", "Id": "534316", "Score": "15", "body": "By analogy with similar functions in many other languages, consider calling it `strjoin` rather than `strcat_new`, which makes one think it's similar to `strcat`, when it's really very different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T05:57:58.897", "Id": "534493", "Score": "0", "body": "@pacmaninbw, the existing code had a bug. I fixed that bug and updated the code. Please tell me how should I post the code that doesn't have the bug. Shall I post a new question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:05:29.020", "Id": "534518", "Score": "0", "body": "Also, even though varargs is practical for \"manual\" inputs, this is way more likely to be called with variable inputs decided at runtime (e.g. results of a database or API query). Providing an interface which takes an array rather than varargs is probably necessary. That one would be `strjoin`, and a varargs-based interface would be called `vstrjoin` (by analogy with `sprintf`/`vsprintf` etc.). Evidently, one should just call the other after conversion of the arguments. We'll leave it as an exercise to determine which one calls which :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T15:57:27.940", "Id": "534558", "Score": "0", "body": "To post any corrections to the code the best thing would be to ask a follow up question. A follow up question will have a link back to this question. You also might want to accept one of the three answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:44:34.200", "Id": "534571", "Score": "0", "body": "An alternative design for this would be `char *strcat_new(const char *delim, const char *str1, ...)` without the count and with a null pointer marking the end of the list. Another alternative interface would be `char *strcat_new(const char *delim, size_t numstr, char **str)` (probably with a const or two added to the last argument). This would take an array of strings. You could have a null-terminated list of strings and do without the `numstr` argument too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:49:39.620", "Id": "534573", "Score": "0", "body": "I have a variant `char *vstrcpy(char *dst, size_t n, ...)` which copies to the given `dst` string and returns a pointer to the null byte at the end of the concatenated string. It doesn't currently have the size of the destination variable (original version 1988), and it doesn't have a delimiter — it isn't the same function. Clearly, because the caller of `vstrcpy()` knows where the data is stored, it can return the pointer to the end of the string and hence the length. The `strcat_new()` function returns the allocated string and can't also return the end/length without a change of interface." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T17:14:42.610", "Id": "534576", "Score": "0", "body": "Incidentally, the file `strcat_new.c` should not include `<stdio.h>` — it does not use anything defined (solely) in that header. (`NULL` is defined in other headers too — `<stddef.h>`, `<string.h>` and `<stdlib.h>` — as well as `<stdio.h>`.)" } ]
[ { "body": "<p><strong>Neat and well formatted</strong></p>\n<p><strong>Design</strong></p>\n<p>Rather than &quot;then after every string, the 'delim' string is concatenated.&quot; (that sounds like <code>n</code> delimiters), I would expect <em>between</em> every string. <em>between</em>, or the like, matches code (<code>n - 1</code> delimiters).</p>\n<p><strong>Design: <code>num_args == 0</code></strong></p>\n<p>Consider allowing this corner case.</p>\n<pre><code>// if (num_args &lt;= 0) return NULL;\nif (num_args &lt; 0) return NULL; // Do not error on 0\n</code></pre>\n<p>Other code may need to change too.</p>\n<p><strong>Use <code>const</code></strong></p>\n<p>Allow <code>const</code> string pointer as <code>delim</code>.</p>\n<pre><code>// char *strcat_new(char *delim, long num_args, ...)\nchar *strcat_new(const char *delim, long num_args, ...)\n</code></pre>\n<p><strong>Why <code>long</code>?</strong></p>\n<p><code>size_t num_args</code> (Goldilocks type for array sizing and indexing) or <code>int num_args</code> (the most common type) would make more sense.</p>\n<p>For pedantic code, could use <code>uintmax_t len</code> to sum the length needs and make sure it is not more than <code>SIZE_MAX</code>.</p>\n<p><strong>&quot;strcat_new.h&quot; first</strong></p>\n<p>In strcat_new.c, (not other *.c), put <code>#include &quot;strcat_new.h&quot;</code> first, before <code>&lt;&gt;</code> includes, to insure &quot;strcat_new.h&quot; compiles on its own without <code>&lt;&gt;</code> includes in the .c files.</p>\n<p><strong>Redundant description</strong></p>\n<p>Reduce maintenance. In *.c use</p>\n<pre><code>/* \n * strcat_new:\n *\n * See strcat_new.h\n */\n</code></pre>\n<p><strong>Define and assign</strong></p>\n<p>Define when needed.</p>\n<pre><code>// char *new_char_array = NULL;\n...\n// new_char_array = malloc(total_len);\n\n...\nchar *new_char_array = malloc(total_len);\n</code></pre>\n<p><strong><code>memcpy()</code> vs. user code</strong></p>\n<p>Rather than user loops, consider <code>memcpy()</code>, <code>strcpy()</code>.</p>\n<pre><code> for (j = 0; j &lt; len; j++) {\n new_char_array[iica] = temp[j];\n iica++;\n }\n\n // vs\n\n memcpy(new_char_array + iica, temp, len);\n iica += len; \n</code></pre>\n<p>For long strings, likely faster.</p>\n<p><strong>Enable all warnings</strong></p>\n<p><code>long delim_len = 0; delim_len = strlen(delim);</code> implies all warnings not enabled as that is a change of sign-ness with no cast.</p>\n<p><strong>1 <code>strlen()</code> per arg</strong></p>\n<p>[See code far below for alternate idea.]</p>\n<p>I would consider saving the <code>strlen(temp)</code> rather than calling twice.</p>\n<p>It is more fuss for short concatenations, but a savings for long ones. It is for long cases that such micro-optimizations are useful.</p>\n<p><strong>Minor: Name</strong></p>\n<p>Perhaps <code>alloc_strcat()</code> rather than <code>strcat_new()</code>. More C like than C++?</p>\n<p><code>str...()</code> may collide with future library. &quot;Function names that begin with str, mem, or wcs and a lowercase letter may be added to the declarations in the &lt;string.h&gt; header.&quot;</p>\n<p><strong>Bug</strong></p>\n<p>As is, when <code>temp == NULL</code>, the code skips to print the <em>next</em> delimiter. It should print delimiters selectively. Consider <code>strcat_new(NULL, 3, &quot;123&quot;, &quot;xyz&quot;, (char*)0);</code> would print a delimiter at the end.</p>\n<p>A better delim print would be</p>\n<pre><code>// Pseudo code\ndelim_printing_needed = false;\nfor each arg\n if (delim_printing_needed) print_delim\n if (arg is not null) {\n print arg\n delim_printing_needed = true;\n }\n}\n</code></pre>\n<p><strong>Pedantic: Consider <code>restrict</code></strong></p>\n<p>Let compiler know <code>delim</code> is not changed by access in other strange ways. Allows for some optimizations.</p>\n<pre><code>char *strcat_new(const char * restrict delim, long num_args, ...)\n</code></pre>\n<p><strong><code>strlen()</code> returns <code>size_t</code></strong></p>\n<pre><code>// printf(&quot;a = %s, strlen(a) = %lu\\n&quot;, a, strlen(a));\nprintf(&quot;a = %s, strlen(a) = %zu\\n&quot;, a, strlen(a));\n// ^\n</code></pre>\n<p><strong>Consider sentinels</strong></p>\n<p>Easier to see white-space troubles.</p>\n<pre><code>// printf(&quot;a = %s, strlen(a) = %zu\\n&quot;, a, strlen(a));\nprintf(&quot;a = \\&quot;%s\\&quot;, strlen(a) = %zu\\n&quot;, a, strlen(a));\n// ^ ^\n</code></pre>\n<p><strong>Hidden problem - null pointer vs <code>NULL</code></strong></p>\n<p>Code has <code>if (!temp) continue;</code> implying a <em>null pointer</em> may be passed as one of the ... arguments. Test code does not test this.</p>\n<p>Using <code>NULL</code>, a <em>null pointer constant</em>, as a <code>...</code> argument is problematic as the <em>type</em> of <code>NULL</code> may differ in size from a <em>null pointer</em> - strange as that sounds.</p>\n<p>What is needed is a <em>null pointer</em>, like <code>((void *) NULL)</code>. Here is may be useful to form a <em>null pointer</em> to be used in skipping like <code>#define NULL_CHAR_POINTER ((char *) 0)</code>.</p>\n<p>Using <code>NULL</code> as the <code>delim</code> argument is not a problem as it is converted to a <code>char *</code>.</p>\n<hr />\n<p>[Edit]</p>\n<p>Looked fun to try to incorporate these ideas.</p>\n<p>Saving the <code>arg</code> lengths not really needed to maintain only 2 passes through each <code>arg</code> (vs. OP's 3 passes: 2x <code>strlen()</code> and <code>for</code> loop).</p>\n<pre><code>#include &quot;alloc_concat.h&quot;\n#include &lt;stdbool.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdarg.h&gt;\n\n// Copy string and return string end\n// If stpcpy available, use it, else ...\nstatic char *my_stpcpy(char *restrict dest, const char *restrict src) {\n while ((*dest = *src) != '\\0') {\n dest++;\n src++;\n }\n return dest;\n}\n\n\n/*\n * Since it is so important to free the returned pointed,\n * I like the function name to echo that.\n */\nchar *concat_alloc(const char *delim, size_t num_args, ...) {\n uintmax_t total_sz = 1;\n const size_t delim_len = delim ? strlen(delim) : 0;\n\n // Walk args, summing space needs.\n va_list valist;\n va_start(valist, num_args);\n bool delim_needed = false;\n for (size_t i = 0; i &lt; num_args; i++) {\n char *arg = va_arg(valist, char *);\n if (arg) {\n if (delim_needed) {\n total_sz += delim_len;\n }\n total_sz += strlen(arg);\n delim_needed = true;\n }\n }\n va_end(valist);\n\n char *concat = total_sz &gt; SIZE_MAX ? NULL : malloc((size_t) total_sz);\n if (concat == NULL) {\n return NULL;\n }\n char *s = concat;\n\n // Walk args, appending delim and arg.\n va_start(valist, num_args);\n delim_needed = false;\n for (size_t i = 0; i &lt; num_args; i++) {\n char *arg = va_arg(valist, char *);\n if (arg) {\n if (delim_needed) {\n s = my_stpcpy(s, delim);\n }\n s = my_stpcpy(s, arg);\n delim_needed = true;\n }\n }\n va_end(valist);\n *s = '\\0'; // In case my_stpcpy() never called.\n\n return concat;\n}\n</code></pre>\n<p>Some tests. (Not very extensive)</p>\n<pre><code>#include&lt;stdio.h&gt;\n\nint main() {\n char *s;\n s = concat_alloc(&quot;, &quot;, 3, &quot;1&quot;, &quot;2&quot;, &quot;3&quot;); printf(&quot;&lt;%s&gt;\\n&quot;, s); free(s);\n s = concat_alloc(&quot;, &quot;, 3, (char*)0, &quot;2&quot;, &quot;3&quot;); printf(&quot;&lt;%s&gt;\\n&quot;, s); free(s);\n s = concat_alloc(&quot;, &quot;, 3, &quot;1&quot;, (char*)0, &quot;3&quot;); printf(&quot;&lt;%s&gt;\\n&quot;, s); free(s);\n s = concat_alloc(&quot;, &quot;, 3, (char*)0, &quot;2&quot;, &quot;3&quot;); printf(&quot;&lt;%s&gt;\\n&quot;, s); free(s);\n s = concat_alloc(&quot;, &quot;, 3, (char*)0, (char*)0, (char*)0); printf(&quot;&lt;%s&gt;\\n&quot;, s); free(s);\n s = concat_alloc(&quot;, &quot;, 0); printf(&quot;&lt;%s&gt;\\n&quot;, s); free(s);\n}\n</code></pre>\n<p>Output</p>\n<pre><code>&lt;1, 2, 3&gt;\n&lt;2, 3&gt;\n&lt;1, 3&gt;\n&lt;2, 3&gt;\n&lt;&gt;\n&lt;&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T02:51:21.673", "Id": "534487", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/131970/discussion-on-answer-by-chux-reinstate-monica-strcat-new-function-not-prese)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T09:23:59.150", "Id": "534514", "Score": "0", "body": "re: naming: `strcatdup` or `strdupcat` occur to me; `strdup` mallocs a copy of a string; `strcat` concatenates. Or jcaron's suggestion of `strjoin` is appealing, especially given the `delim` arg." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:10:41.370", "Id": "534521", "Score": "2", "body": "@Peter, all those names are in the \"reserved for library expansion\" set. User code should not define external identifiers beginning with `str` (or any identifier of that form when `<stdlib.h>` or `<string.h>` are included), unless the next character is something other than a lower-case letter. Perhaps `str_join`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:14:31.653", "Id": "534522", "Score": "0", "body": "@TobySpeight: Indeed; I wrote that comment before seeing your answer. Hmm, that even rules out `string_join` because that still starts with `str`. Maybe `join_strings`? It's pretty unlikely you'd actually run into a name conflict, but it's good to be fully guaranteed safe." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:19:01.910", "Id": "534523", "Score": "0", "body": "Yes, indeed. There's a few gotchas in the \"reserved for library expension\" set (e.g. lots of English words begin with `to`). As you say, a clash is unlikely, but it could be catastrophic and hard to diagnose if the wrong function is linked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:05:22.553", "Id": "534559", "Score": "0", "body": "Can you elaborate on `In strcat_new.c, (not other *.c), put #include \"strcat_new.h\" first, before <> includes, to insure \"strcat_new.h\" compiles on its own without <> includes in the .c files.`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:09:03.823", "Id": "534560", "Score": "0", "body": "Do you mean that it ensures that the header file is self-contained?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:09:27.097", "Id": "534561", "Score": "2", "body": "@marco-a Yes - self contained. An `#include \"xxx.h\"` should work without requiring a prior _include_. To test that, the `xxx.c` should first `#include \"xxx.h\"` without previous `#include`s." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:59:35.450", "Id": "534574", "Score": "1", "body": "See [Should I use `#include` in headers?](https://stackoverflow.com/q/1804486/15168) on SO for a discussion of header guards and 'idempotence', 'self-containment', and 'minimalism'." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T09:58:34.920", "Id": "270531", "ParentId": "270524", "Score": "17" } }, { "body": "<h2>Reserved identifiers</h2>\n<p>The include-guard <code>_STRCAT_NEW_H_</code> is one of the names reserved for the implementation, as it begins with underscore and an upper-case letter.</p>\n<p>As a general guide, never begin names with underscore.</p>\n<p>The function name beginning with <code>str</code> is reserved for standard library extension, so choose a different name there, too.</p>\n<h2>Interface</h2>\n<p>Consider using null pointer to mark the last argument, rather than requiring the programmer to keep the count argument up to date. Provide a constant for that purpose (as the <code>NULL</code> macro doesn't necessarily expand to the right type in varargs).</p>\n<h2>Implementation</h2>\n<p>As <a href=\"/a/270531/75307\">chux's review</a> says, make sure you have warnings enabled for conversions between signed and unsigned types. There are plenty of problems you can find and fix that way, before asking humans to review the code.</p>\n<p>I don't think this function requires any signed values at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T14:11:01.347", "Id": "534312", "Score": "1", "body": "I did really mean what I wrote, but having re-read 7.1.3, I discover my memory is faulty!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T15:23:56.587", "Id": "534317", "Score": "0", "body": "\"Provide a constant for that purpose\" No, really not. `(char*)0` is so much more obvious and better to remember." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T17:26:48.323", "Id": "534331", "Score": "0", "body": "I take it you've never seen `typedef int size_t;` in standard headers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T20:18:21.503", "Id": "534345", "Score": "3", "body": "@Joshua Maybe in crazy pre-standard headers? And anyway, `size_t` is a semantic type seeing ubiquitous use, not a one-off name to hide the standard sentinel." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T20:19:55.400", "Id": "534346", "Score": "1", "body": "@Deduplicator: Well if you did compile on a platform with an `int size_t` your comparison between signed and unsigned warnings would trigger." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T08:12:09.533", "Id": "534380", "Score": "1", "body": "I concur with the suggestion to terminate the argument list, instead of passing a counter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:32:36.037", "Id": "534409", "Score": "1", "body": "@Peter-ReinstateMonica passing a counter allows, at run time, a change in how much is appended - of course when count is low, same high number of augments are still passed. Using a list terminator fixes the count at compiler time and need to watch out for the `NULL` issue discussed elsewhere. Also OP's code selectively skips concatenating with a null pointer arg, so to implement OP's goal and a terminated list involves something special other than a _null pointer_. FWIW I agree with your preference, yet OP's goal is an acceptable as is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T14:04:25.463", "Id": "534416", "Score": "0", "body": "@chux True, if nullptr is a legitimate argument it is not available as terminator. But the other argument about compile time vs. run time is not relevant for the terminator vs. count argument -- if you always pass n resp. n+1 arguments (the necessarily fixed compile time side) you can pass a counter x <= n or terminate at arg x+1 equally well, at run time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T09:30:35.067", "Id": "534515", "Score": "1", "body": "@Joshua: ISO C guarantees that `size_t` is an unsigned type (at least that's what https://en.cppreference.com/w/c/types/size_t says; I didn't check the actual standard). I see little point in taking pains to account for broken implementations, especially when there aren't any modern mainstream implementations with that bug. (Are there?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T10:51:22.330", "Id": "534516", "Score": "2", "body": "@Peter, (almost) Standard reference: ISO/IEC 9899:201x committee draft section 7.19.2: \"`size_t`\nwhich is the unsigned integer type of the result of the `sizeof` operator;\"" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T11:12:25.287", "Id": "270534", "ParentId": "270524", "Score": "8" } }, { "body": "<p>Using C99 Variable Length Arrays to save calculated string-lengths, and fixing all the other problems chux identified, your code can be made far more efficient:</p>\n<pre><code>char* astrcat(const char* restrict delim, size_t num_args, ...) {\n if (!num_args)\n return calloc(1, 1);\n\n size_t lengths[num_args];\n const size_t ndelim = delim ? strlen(delim) : 0;\n size_t total = (num_args - 1) * ndelim;\n\n va_list args;\n va_start(args, num_args);\n for (size_t i = 0; i &lt; num_args; ++i) {\n lengths[i] = strlen(va_arg(args, const char*));\n total += lengths[i];\n }\n va_end(args);\n\n char* const r = malloc(total + 1);\n if (!r)\n return r;\n\n char* p = r;\n va_start(args, num_args);\n for (size_t i = 0;; ++i) {\n memcpy(p, va_arg(args, const char*), lengths[i]);\n p += lengths[i];\n if (i == num_args)\n break;\n memcpy(p, delim, ndelim);\n p += ndelim;\n }\n *p = 0;\n va_end(args);\n\n return r;\n}\n</code></pre>\n<p>If you don't want (or can't) use VLA, you can use simple recursion (this version also changed to use a sentinel instead of a manual count, using sentinel above or count below left as an exercise for the reader):</p>\n<pre><code>static char* vastrcat_impl(const char* restrict delim, size_t ndelim,\n size_t prefix, va_list args) {\n const char* p = va_arg(args, const char*);\n if (!p) {\n char* r = malloc(prefix + 1);\n if (r)\n *(r += prefix) = 0;\n return r;\n }\n size_t n = strlen(p);\n char* r = vastrcat_impl(delim, ndelim, prefix + n + ndelim, args);\n if (!r)\n return r;\n memcpy(r -= n, p, n);\n memcpy(r -= ndelim, delim, ndelim);\n return r;\n}\n\nchar* vastrcat(const char* restrict delim, va_list args) {\n const char* p = va_arg(args, const char*);\n if (!p)\n return calloc(1, 1);\n size_t n = strlen(p);\n size_t ndelim = delim ? strlen(delim) : 0;\n char* r = vastrcat_impl(delim, ndelim, n, args);\n memcpy(r -= n, p, n);\n return r;\n}\n\nchar* astrcat(const char* restrict delim, ...) {\n va_list args;\n va_start(args, delim);\n char* r = vastrcat(delim, args);\n va_end(args);\n return r;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T16:25:50.097", "Id": "270542", "ParentId": "270524", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T07:03:13.710", "Id": "270524", "Score": "9", "Tags": [ "c", "library" ], "Title": "strcat_new() function, not present in standard C library" }
270524
<p>I know this question could be the new variant of other 1million questions but before you say that, let me explain what I'm trying to achieve.</p> <p>I have a lot of APIs and want to create an SDK. There is an API for each function (Statistics, ApplicationLogs, Transactions and so on). To use those services, the API authentication is required.</p> <p>So, the application has to pass <code>apiScope</code>, <code>clientId</code> and <code>clientSecret</code>. Based on those parameters, the Identity Server releases a token that every call from the SDK has to use.</p> <p>In the SDK each API has a service and that implement the interface</p> <pre><code>public interface IBaseService&lt;T&gt; where T : class { Task&lt;T&gt; Get(); Task&lt;T&gt; Get(string query); Task&lt;List&lt;T&gt;&gt; Gets(); Task&lt;List&lt;T&gt;&gt; Gets(string query); Task&lt;T&gt; Patch(string query, string payload); Task&lt;T&gt; Post(string query, string payload); Task&lt;QueryResult&lt;T&gt;&gt; Search(QueryObjectParams queryParams); Task&lt;QueryResult&lt;T&gt;&gt; Search(string query, QueryObjectParams queryParams); } </code></pre> <p>Then, for example, the interface for the ApplicationLog is defined like</p> <pre><code>public interface IApplicationLogService : IBaseService&lt;ApplicationLog&gt; { Task&lt;ApplicationLog&gt; PatchLog(string payload); Task&lt;ApplicationLog&gt; PostLog(string payload); } </code></pre> <p>After that, there is the concrete implementation of this interface based on a base class</p> <pre><code>public class BaseService&lt;T&gt; : IBaseService&lt;T&gt; where T : class { public BaseService(string apiUrl, string baseUrl, AuthorizationServerAnswer authorizationServerToken) { _apiUrl = apiUrl; _baseUrl = baseUrl; _authorizationServerToken = authorizationServerToken; _service = new ApiService&lt;T&gt;(_apiUrl, _authorizationServerToken); } } </code></pre> <p>In this base class I pass the token to make the calls. Also, in the constructor of the <code>BaseService</code> I create a <code>_service</code> from <code>ApiService</code> where I have all HTTP calls (GET, POST, PUT, DELETE...). The concrete implementation is something like</p> <pre><code>public class ApplicationLogService : BaseService&lt;ApplicationLog&gt;, IApplicationLogService { public ApplicationLogService(string apiUrl, AuthorizationServerAnswer authorizationServerToken) : base(apiUrl, baseQuery, authorizationServerToken) { } } </code></pre> <p>The final part is the <code>UnitOfWork</code>. I create a class that collect all the services in one easy class. The initialization of the class calls a function to get the token from Identity Server. So, it is easy to see all the services</p> <pre><code>public class SDKClient { public string _baseUrl = &quot;&quot;; public AuthorizationServerAnswer AuthorizationToken { get; set; } public ApplicationLogService ApplicationLogService { get; private set; } // more code public async Task SetIdentityToken() { // create or renew the token await RenewToken(); // pass the token to the function (via the api base url) ApplicationLogService = new ApplicationLogService(_baseUrl, AuthorizationToken); } public async Task RenewToken() { if (_idService == null) _idService = new IdentityService(_baseIdentityUrl, _apiScope, _clientId, _clientSecret); if (AuthorizationToken == null || AuthorizationToken.ExpiresDateTime &gt; DateTime.Now) AuthorizationToken = await _idService.RequestTokenToAuthorizationServer(); } } </code></pre> <p>This last part, the <code>UnitOfWork</code>, may be it is not good in the dependency point of view. How can I implement it in a better, more elegant and efficient way the main class?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T09:29:45.713", "Id": "534288", "Score": "0", "body": "`Gets` isn't a good name. Should be GetList or GetAll or something like that. And `public string _baseUrl = \"\";` is really bad: it's `public` yet it has the naming of a `private`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T13:56:07.647", "Id": "534309", "Score": "0", "body": "@BCdotWEB Good start to a good answer." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T08:32:06.780", "Id": "270525", "Score": "0", "Tags": [ "c#", "dependency-injection" ], "Title": "ASP.NET Core dependency injection in class library with params" }
270525
<p>Write a function: <strong>class Solution { public int solution(int N); }</strong> that, given an integer N, returns the smallest integer greater than N, the sum of whose digits is twice as big as the sum of digits of N. Examples: 1. Given N = 14, the function should return 19. The sum of digits of 19 (1 +9 = 10) is twice as big as sum of digits of 14 (1 + 4 = 5). 2. Given N = 10, the function should return 11. 3. Given N = 99, the function should return 9999.</p> <pre><code>class G{ static int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } static void smallestNumber(int N){ int i=getSum(N); int d=i*2; int k=N; while (k&lt;100000){ if(getSum(k)==d){ System.out.println(k); return; } k++; } } public static void main(String[] args) { int N = 99; smallestNumber(N); } } </code></pre>
[]
[ { "body": "<p>Here is what i can recommend on what you've written:</p>\n<ul>\n<li>You should name your variables properly: names such as <code>i</code> should be only used as indexes.</li>\n<li>Why do you stop at <code>k</code> = 100000? Why not go further? What if <code>N</code> is bigger than that?</li>\n<li>If you plan to use a <code>while</code>, I would recommend creating a method\nreturning a boolean that checks if the condition is met and only stop then.</li>\n<li>A class named <code>G</code> could have a more explicit name.</li>\n</ul>\n<p>This being said, your approach is a bit simple, and you could go for a better solution that would allow you to aim for a better solve time, and complexity.</p>\n<p>To do so, you usually look for a pattern by going through different values or the first of the iteration. It usually involves a bit of mathematics and head scratching.</p>\n<p>You can find a more detailed explanation <a href=\"https://www.geeksforgeeks.org/find-the-smallest-number-whose-sum-of-digits-is-n/\" rel=\"nofollow noreferrer\">here</a> for your example.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T09:48:48.657", "Id": "270529", "ParentId": "270527", "Score": "4" } }, { "body": "<p>Youri's answer is correct in terms of general code review.</p>\n<p>What I want to address here is that you can rework your algorithm to skip some unnecessary steps. You're taking the brute force approach, but there's a more clever way to think about this.</p>\n<p>I'm going to take the long way to explain this, because I think it's important for you to see how I came to this solution; rather than just seeing the end result. The purpose here is to learn how to analyze how numbers behave.</p>\n<blockquote>\n<p><strong>NOTE</strong><br />\nFor the entirety of this answer, I'm counting digits beginning from the right. The &quot;first&quot; digit is the rightmost digit (10<sup>0</sup>), the &quot;second&quot; digit is the second-rightmost digit (10<sup>1</sup>), the &quot;third&quot; digit is the third-rightmost digit (10<sup>2</sup>), and so on.</p>\n</blockquote>\n<p>First of all, try to think of each digit like a container that can be filled up to 9. Since you're only interested in the <em>sum</em> of the digits, it doesn't matter (in regards to the sum) <em>which</em> containers you increase.</p>\n<p>However, you are trying increment the original number. Counting up means that you increase the rightmost number first. Therefore, when looking for your result, you increase the first digit, up to 9. Let's assume you haven't found it by now. You would then roll over to the second digit.</p>\n<p>But when you roll over to the second digit, the first digit goes back to 0. You gain <code>+1</code> from the second digit, but you lose <code>-9</code> from the first digit. It makes no sense to even try and check this number, because if the previous number was not high enough, this one <em>definitely</em> won't be.</p>\n<p>Even if you only brought the first digit down to an 8, you end up gaining <code>+1</code> from the second digit, but you still lose <code>-1</code> from the first digit, which is a zero sum game.</p>\n<p>The conclusion here is that <strong>decreasing the digits when rolling over negatively impacts the total sum of the digits</strong>, and therefore doesn't make sense. When a digit reaches 9, you can keep it at 9, and just start increasing the next digit.</p>\n<p>Let's use 765 as an example. The target sum is (7+6+5)*2 = 36. Let's start checking:</p>\n<pre><code>766 = 19 \n767 = 20\n768 = 21\n769 = 22 &lt;---------- First number reaches 9\n770 = 14\n771 = 15\n772 = 16\n773 = 17\n774 = 18\n775 = 19\n776 = 20\n777 = 21\n778 = 22\n779 = 23 &lt;---------- First sum to be higher than the 22 I point out earlier\n</code></pre>\n<p>Notice how numbers 770 to 778 were irrelevant, because their sum was lower than what we had already found. There was no reason to check any of them.</p>\n<p><strong>You only need to check numbers with a higher sum than you already found</strong>.</p>\n<p>Here's a list of numbers, starting from 766, which are actually a higher total sum than you've ever seen before</p>\n<pre><code> 766 = 19\n 767 = 20\n 768 = 21\n 769 = 22\n 779 = 23\n 789 = 24\n 799 = 25\n 899 = 26\n 999 = 27\n1999 = 28\n2999 = 29\n3999 = 30\n4999 = 31\n5999 = 32\n6999 = 33\n7999 = 34\n8999 = 35\n9999 = 36 &lt;------ FOUND IT\n</code></pre>\n<p>There are interesting things to notice about the sequence:</p>\n<ol>\n<li>The first digit increased up to 9 and then stayed there forever.</li>\n<li>The second digit increased up to 9 and then stayed there forever.</li>\n<li>The third digit increased up to 9 and then stayed there forever.</li>\n<li>...</li>\n</ol>\n<p>You can use this to your advantage, because now you know how you can find the next number in the sequence:</p>\n<ul>\n<li>Find the rightmost digit that is not already 9 and increment it.</li>\n<li>If all digits are 9, prepend a 1.</li>\n</ul>\n<p>Or, in code (I am a C# dev, the syntax should mostly match):</p>\n<pre><code>private int GetNextRecordBreakingNumber(int number)\n{\n // Split the number into an array of its digits\n int[] digits = number.ToString().Select(c =&gt; c - '0').ToArray();\n\n // Count indices from right to left\n for(int i = digits.Length - 1; i &gt;= 0; i--)\n {\n if(digits[i] != 9)\n {\n // Increment the non-9 digit\n digits[i] = digits[i] + 1;\n \n //Put the number back together and return it\n int result = 0;\n for(int j = 0; j &lt; digits.Length; j++)\n {\n result = result * 10 + digits[j];\n }\n return result;\n }\n }\n \n // If we get here, all digits were 9, so just add 10^X (where X = amount of digits in old number) \n return number + (int)Math.Pow(10, digits.Length);\n}\n</code></pre>\n<p><em>I opted for the string-based approach to separate a number into its digits, as it is much easier to read than the mathematical approach, and the performance should not form any problem, as I will discuss below the break.</em></p>\n<p>This will sequentially generate the list I showed you before:</p>\n<pre><code>int current = 765;\n \nfor(int i = 0; i &lt; 18; i++)\n{\n current = GetNextRecordBreakingNumber(current);\n Console.WriteLine(current);\n}\n</code></pre>\n<p><a href=\"https://dotnetfiddle.net/IAc2tq\" rel=\"nofollow noreferrer\">link to fiddle</a>.</p>\n<hr />\n<p>If you use this method to find the next number, instead of doing <code>k++;</code>, this will cost you significantly less iterations.</p>\n<p>Your <code>10 =&gt; 11</code> and <code>99 =&gt; 9999</code> examples prove that your code will iterate at least once, and up to <code>n</code> orders of magnitude (where <code>n</code> is the number of digits of your starting value) higher than where you started. That is <strong>massive</strong> when dealing with non-trivial numbers.</p>\n<p>Using my suggested method, you cut down the maximum iterations to <code>n*9</code>. (Edit: I think this is even lower, closer to <code>n*5</code> on average, but I'm fuzzy on the math here)</p>\n<p>Case in point: <code>99 =&gt; 9999</code>. Your logic would perform 9900 iterations. My logic would perform 18.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T20:05:39.847", "Id": "534343", "Score": "3", "body": "Nice solution, but you can do better. The digit sum must increase by `18`. The first digit is a `5`, so it can increase by `min(9-5,18)=4`. Remaining increase is `18-4=14`. Next digit is a `6` so it can increase by `min(9-6,14)=3`. Remaining increase is `14-3=11`. Next digit is a `7`, so it can increase by `min(9-7,11)=2`. Remaining increase is `11-2=9`. Next digit is an implied `0`, and can increase by `min(9-0,9)=9`. Remaining increase is `9-9=0`, signifying we're done. Only 4 iterations were required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T08:50:47.337", "Id": "534384", "Score": "1", "body": "@AJNeufeld: Yeah I noticed that near the end as well but I just didn't have the time to rewrite it :) Well explained!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T09:35:53.140", "Id": "534386", "Score": "0", "body": "Nice answer, and kudos for taking the time to explain the logic on how to figure out the algorithmic improvement." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T16:21:20.657", "Id": "270541", "ParentId": "270527", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T09:16:22.527", "Id": "270527", "Score": "1", "Tags": [ "java", "algorithm" ], "Title": "Given an integer N, returns the smallest integer greater than N, the sum of whose digits is twice as big as the sum of digits of N" }
270527
<p>I have written a Python3 program that looks for matching strings and removes them from files.</p> <pre><code>import os path = os.getcwd() ignore_files = [&quot;remove-lines.py&quot;, &quot;to-remove&quot;] with open(&quot;to-remove&quot;, &quot;r&quot;, newline=&quot;&quot;) as pattern_file: remove_patterns = [l for l in (line.strip() for line in pattern_file) if l] for root, directories, files in os.walk(path, topdown=False): for name in files: out = [] current_file = os.path.join(root, name) print(current_file) if any([ignore_file in current_file for ignore_file in ignore_files]): pass else: with open(current_file, &quot;r&quot;) as in_file: in_file_lines = in_file.readlines() print(&quot;IN FILE:&quot;) print(in_file_lines) for in_file_line in in_file_lines: print(in_file_line) keep_var = True for remove_pattern in remove_patterns: if remove_pattern in in_file_line: keep_var = False print(&quot;R: &quot; + remove_pattern + &quot; IS IN &quot; + in_file_line) break if keep_var: print(&quot;OUTPUTTING&quot;) print(in_file_line) out.append(in_file_line) print(&quot;\n\n\nFINAL\n\n\n&quot;) print(out) with open(current_file, &quot;w&quot;) as out_file: for line in out: out_file.write(line) </code></pre> <p>The repo, with <code>README</code>, is on <a href="https://github.com/jamesgeddes/removelines" rel="nofollow noreferrer">GitHub</a>.</p> <p>How could I improve this code? Are there ways I could make it more Pythonic? All feedback and criticisms welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T16:03:39.843", "Id": "534319", "Score": "0", "body": "Is there any reason why you opted not to go for a regex based solution? Can you give some example files?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T16:13:45.040", "Id": "534320", "Score": "0", "body": "Was trying to stay purely pythonic. Should work with any files given a `to-remove` file." } ]
[ { "body": "<h2>Picking the right tools</h2>\n<p>Your entire script can be written as the following one-liner</p>\n<pre><code>grep -RiIl 'search' | xargs sed -i's/.*\\(here\\|there\\|why\\).*//g'\n</code></pre>\n<p>Whenever your entire script can be expressed as a oneliner, it is a good indication that something needs to change. The onliner is intentially obtuse, but I would argue your code is equally obtuse. You just do not know it, because you wrote it ;) I combined the ideas from here</p>\n<p><a href=\"https://www.internalpointers.com/post/linux-find-and-replace-text-multiple-files\" rel=\"nofollow noreferrer\">https://www.internalpointers.com/post/linux-find-and-replace-text-multiple-files</a></p>\n<p>with <code>.*</code> to match anything zero or more times and then the list of banned words. Another solution from Overflow looks like this <a href=\"https://stackoverflow.com/questions/14443935/regex-search-replace-for-multiple-files-in-a-directory-using-python\">https://stackoverflow.com/questions/14443935/regex-search-replace-for-multiple-files-in-a-directory-using-python</a> which is closer, but not quite where we want</p>\n<h3>Pythonic</h3>\n<p>What does pythonic mean? Does it mean &quot;this code was written in Python&quot;? No, see for instance <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">Zen of Python</a>.</p>\n<pre><code>Readability counts.\n</code></pre>\n<p>Take a step back. Breathe. Now look at your code. would you understand this code in a few hours, what about a few weeks, years? Your code is the <em>first step</em> to writing good code. Step 1, just make the freakin thing work.</p>\n<p>A working code is like a book with a story but with no commas sections paragraphs commas or periods and it is just a big blob of text while the whole story is in there and every part makes sense to the author but it can be a big challenging for another person or your future self to read it dont you agree</p>\n<p>Pythons chapters is files. Our table of contents is the docstring of each file. Then we put our code into paragraphs or functions, and explain the purpose of each paragraph. This is done by clear variable names, doctests and docstrings and typing hints.</p>\n<h3>Improvements</h3>\n<ul>\n<li><p>Today we try to prefer to use the <code>pathlib</code> library to handle paths instead of <code>os</code>. (I know many still prefer walk), but learning to use the pathlib is never a bad idea.</p>\n</li>\n<li><p>Explicit is better than implicit. You need to name &quot;to-remove&quot; better. 1) It needs a filetype to be specific. 2) You need to inform that this is a &quot;user created file&quot;.\n<code>user_words_to_remove.txt</code> Notice how we used underscores as this is prefered by python. 3) This should really be a global constant, or even better prompted using <code>sys.args</code> or even better <code>argparse</code> (click is overkill)</p>\n</li>\n<li><p>Learn to use early exits. This</p>\n<pre><code> if any([ignore_file in current_file for ignore_file in ignore_files]):\n pass\n else:\n with open(current_file, &quot;r&quot;) as in_file:\n in_file_lines = in_file.readlines()\n print(&quot;IN FILE:&quot;)\n print(in_file_lines)\n</code></pre>\n<p>is better formated as</p>\n<pre><code> if any([ignore_file in current_file for ignore_file in ignore_files]):\n continue\n\n with open(current_file, &quot;r&quot;) as in_file:\n in_file_lines = in_file.readlines()\n print(&quot;IN FILE:&quot;)\n print(in_file_lines)\n</code></pre>\n</li>\n</ul>\n<p>Do not print everywhere! Separate business logic from the UI. Have functions that have a sole purpose of printing, and one that has a sole purpose of fetching files.\nsomething like the below would be a <em>start</em></p>\n<pre><code> from pathlib import Path \n\n def walk(path:Path, recursive:bool=False, depth:int=0) -&gt; Path: \n if depth &gt; 0 and not recursive:\n return\n for p in Path(path).iterdir(): \n if p.is_dir(): \n yield from walk(p, depth=depth+1)\n continue\n yield p.resolve()\n\n def legal_files(directory:Path|str=Path.cwd(), files_2_exclude:list[str]) -&gt; Path:\n for f in walk(Path(directory)): \n if f.name not in files_2_exclude: \n yield f\n</code></pre>\n<p>Note how no file directory will ever hit the recursion limit so using recursion here is fine.. Now we can simply iterate over the legal files.\nFrom here I would compile some regex, and possibly do something like below</p>\n<pre><code>import re\n\nWORDS_2_EXCLUDE = [&quot;sit&quot;, &quot;lorem&quot;, &quot;lipsum&quot;]\nREPLACE_LINES = re.compile(r&quot;^.*(&quot;+&quot;|&quot;.join(WORDS_2_EXCLUDE)+&quot;).*$&quot;)\n\ndef replace_files_in_path(path, recursive:bool=False) -&gt; None:\n for filepath in legal_files(path, recursive=recursive):\n with open(filepath, &quot;r&quot;) as f:\n new_content = REPLACE_LINES.sub(&quot;&quot;, f.read())\n with open(filepath, &quot;w&quot;) as f:\n f.write(new_content)\n</code></pre>\n<p>Note that the code above is <em>not</em> tested, it will have bugs. The best way to learn is to fix those bugs, and understand the code. I would also to recommend implementing the <code>recursive</code> option so your users can choose to iterate recursively, or just search the current directory. I gave it an attempt, but make sure it actually works.</p>\n<p>Good luck improving!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T17:42:17.777", "Id": "534332", "Score": "0", "body": "Not my finest code :D thanks for the suggestions :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T17:16:08.447", "Id": "270544", "ParentId": "270530", "Score": "4" } }, { "body": "<p>I find programs like yours to be excellent vehicles for improving one's coding\nskills. Why? Because they have the potential to be incredibly destructive. One\nfalse move and an entire directory tree can be obliterated. In my youth, on\nmore than one occasion I wrote programs like this only to find myself\nfrantically pressing <code>CTRL-C</code> moments later. Let's use that danger to our\nbenefit.</p>\n<p><strong>When you're doing something dangerous, don't multitask</strong>. Your current code\ntries to do everything at the same time: reading paths from a directory tree;\nfiltering out paths to be ignored; reading lines from specific files; filtering\nout unwanted lines; and then writing desired lines back to the files.\nInterspersed in all of those operations are various print operations, perhaps\nmotivated by your sense of the risks: if we print everything we're doing, one\nmight hope, perhaps we can convince ourselves that everything is going alright.</p>\n<p><strong>Separate dangerous things from safe things</strong>. Of course, most of those\noperations are not dangerous (reading, filtering, etc). Only the final writing\nis destructive. At a minimum, keep the dangerous part separate from the rest.\nEven better, of course, is organize the program more fully to separate the\ndifferent operations from each other.</p>\n<p><strong>Design for partial execution</strong>. Writing, debugging, and modifying highly\ncomingled code like this is a hassle, because every execution leads to a\npotentially destructive ending if you make a mistake. Recognize that risk at\nthe beginning and design the program to allow you to run it in &quot;safe mode&quot;.\nThere are various ways to do that (e.g. command-line options or environment\nvariables), but the simple idea is to provide an easy usage mechanism to\ncontrol which parts of the program to execute at all or for real.</p>\n<p><strong>Approach one-liners with a similar mindset</strong>. You already have a useful\nreview that includes a suggested grep-xargs-sed one-liner to do all of this\ndestruction with a single swing of the axe. As an old-school Unix guy, I love\nthat kind of trickeration. However, you have to treat those tools as the unruly\nchainsaws that they are. Approach them incrementally, with caution, and don't\nrun the whole monstrosity on the first attempt. Instead, first convince\nyourself that the grep-xargs combo is correct. Then experiment with sed on a\nsmall subset of copied files. Only after you have high confidence should you\nturn it loose on a real directory tree (often after making a backup rsync first).</p>\n<p><strong>Embrace functions and data objects</strong>. If a one-liner is insufficient for your needs (it often is), the key to applying those ideas is to decompose your program into discrete\nfunctions, each focusing narrowly on a specific operation. Here's a top-level\nsketch. The specific implementation will depend on your precise needs for the\nprogram. This illustration uses a simple data object, a <code>Line</code>, to represent\none line of text from file plus a flag to indicate whether the line matched any of the remove-patterns.</p>\n<pre><code>from dataclasses import dataclass\n\n@dataclass\nclass Line:\n text: str\n matched: bool\n\ndef main(args):\n # Parse command-line arguments to control what/how to run.\n # See argparse.\n opts = parse_command_line(args)\n\n # Collect path of interest.\n # If you want to do printing of any kind, try to do it here (or in\n # a separate function), not inside these functions doing the core work.\n remove_patterns = read_remove_patterns(pattern_path)\n all_paths = collect_file_paths(root_path)\n relevant_paths = filter_file_paths(all_paths, ignore_files)\n\n # Process each file.\n for path in relevant_paths:\n lines = tuple(process_file(path, remove_patterns))\n\n # At this point, you can do whatever is needed\n # based on command-line options. Examples:\n #\n # - Print lines to be omitted/kept or both.\n # - Print affected/unaffected file paths.\n # - Or actually overwrite files.\n #\n # Of course, do those things in their own functions as well.\n ...\n\ndef process_file(path, remove_patterns):\n for line in read_file(path):\n matched = line_matches(line, remove_patterns)\n yield Line(line, matched)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T22:03:59.240", "Id": "534351", "Score": "1", "body": "_\"Instead, first convince yourself that the grep-xargs combo is correct. Then experiment with sed on a small subset of copied files. Only after you have high confidence should you turn it loose on a real directory tree (often after making a backup rsync first).\"_ This is precisely what I did when writing the answer =D Tested it incrementally in small chunks without actually replacing the output. This can be done by removing the `i` flag (in place) from `sed` so it instead writes to STDOUT =) Great answer!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T21:12:20.360", "Id": "270552", "ParentId": "270530", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T09:54:06.610", "Id": "270530", "Score": "4", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Remove matching lines from all files" }
270530
<p><a href="https://i.stack.imgur.com/n2SGk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n2SGk.png" alt="enter image description here" /></a></p> <p>I have 2 datafarme And need result, date of datefarme 2 between date of dataframe 1 result = A of datefarme 2 add in datafarme 1</p> <pre><code>import pandas as pd df1 = pd.DataFrame( columns=[&quot;date&quot;, &quot;C&quot;], data=[ (pd.Timestamp(&quot;2020-10-10 10:00:00&quot;), 0 ), (pd.Timestamp(&quot;2020-10-10 12:00:00&quot;),0 ), (pd.Timestamp(&quot;2020-10-10 14:00:00&quot;), 0 ), (pd.Timestamp(&quot;2020-10-10 16:00:00&quot;), 0 ), (pd.Timestamp(&quot;2020-10-10 18:00:00&quot;), 0 ), (pd.Timestamp(&quot;2020-10-10 20:00:00&quot;), 0 ), (pd.Timestamp(&quot;2020-10-10 22:00:00&quot;), 0 ), ], ) df2 = pd.DataFrame( columns=[&quot;date&quot;, &quot;A&quot;], data=[ (pd.Timestamp(&quot;2020-10-10 14:30:00&quot;), 2), (pd.Timestamp(&quot;2020-10-10 18:40:00&quot;), 5), (pd.Timestamp(&quot;2020-10-10 22:10:00&quot;), 9), ], ) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T13:02:25.827", "Id": "534302", "Score": "1", "body": "Please include **your** code to achieve the result needed in the question: See [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T13:03:08.320", "Id": "534303", "Score": "1", "body": "(Consider accepting help from a *spelling checker*.)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T10:00:59.297", "Id": "270532", "Score": "-1", "Tags": [ "python", "pandas" ], "Title": "Merge two Dataframe with condition" }
270532
<h3>Resolving circular references in VBA via ObjectStore class and CleanUp cascade</h3> <p>I have been working on a VBA database library and realized I had a few circular reference loops in my class hierarchy, as illustrated in the figure (left panel). I recalled reading an RDVBA blog <a href="https://rubberduckvba.wordpress.com/2018/09/11/lazy-object-weak-reference/" rel="nofollow noreferrer">post</a> about the circular reference issue and the <a href="https://codereview.stackexchange.com/questions/202414/">weak reference</a> technique, as well as a CRQ question about an optimized <a href="https://codereview.stackexchange.com/questions/245660/">WeakReference</a> class. However, I wanted to try two native approaches to managing circular references in VBA: one employing a termination clean-up cascade and another using a helper object preventing the formation of the loops. To keep this question focused, I prepared a stripped-down version of the classes shown in the figure: I have removed all business logic and only kept the code relevant to this question.</p> <p><img src="https://github.com/pchemguy/ObjectStore/raw/develop/Assets/Diagrams/CircularReferenceCombi.png" alt="CircularReferences" /></p> <p><strong>Simplified class diagram of a database library (left) and a diagram with ObjectStore (right).</strong></p> <hr /> <h3>ObjectStore class</h3> <p>ObjectStore essentially maintains an <strong>ObjPtr → Obj</strong> map in a wrapped dictionary. With ObjectStore employed, the child object (DbStatement) constructor saves the address of its parent object (DbConnection), saving the latter to ObjectStore. To avoid replacing one loop with another, the Child cannot keep an ObjectStore reference necessitating a public variable. While the predeclared instance could do the job, a similarly behaving public auto-assigned variable named after the class is preferable because it resets if set to Nothing.</p> <p>The DbManager class is not involved in circular references, is terminated automatically by VBA, and can destroy ObjectStore. However, because the ObjectStore variable is global and more than one DbManager instance may exist, ObjectStore should not be destroyed from the Class_Terminate() method. Instead, the default DbManager instance <a href="https://codereview.stackexchange.com/questions/270483/predeclared-class-instance-tracks-the-number-of-regular-instances">counts existing regular instances</a>. Whenever this count goes to zero, the <em>default</em> instance of DbManager sets ObjectStore to Nothing, destroying the wrapped dictionary object alone with all saved object references and freeing the stored objects.</p> <p><strong>ObjectStoreGlobals</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;Object Store&quot; Option Explicit Public ObjectStore As New ObjectStore </code></pre> <p><strong>ObjectStore</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;Object Store&quot; '@ModuleDescription &quot;Manages object references using scalar handles.&quot; '@IgnoreModule IndexedDefaultMemberAccess Option Explicit Private Type TObjectStore Store As Scripting.Dictionary End Type Private this As TObjectStore Private Sub Class_Initialize() Set this.Store = New Scripting.Dictionary this.Store.CompareMode = TextCompare End Sub Private Sub Class_Terminate() this.Store.RemoveAll Set this.Store = Nothing End Sub #If VBA7 Then Public Sub DelRef(ByVal Handle As LongPtr) #Else Public Sub DelRef(ByVal Handle As Long) #End If If this.Store.Exists(Handle) Then this.Store.Remove Handle End Sub #If VBA7 Then Public Function SetRef(ByVal ObjRef As Object) As LongPtr Dim Handle As LongPtr #Else Public Function SetRef(ByVal ObjRef As Object) As Long Dim Handle As Long #End If Handle = ObjPtr(ObjRef) If Not this.Store.Exists(Handle) Then Set this.Store(Handle) = ObjRef End If SetRef = Handle End Function #If VBA7 Then Public Function GetRef(ByVal Handle As LongPtr) As Object #Else Public Function GetRef(ByVal Handle As Long) As Object #End If If this.Store.Exists(Handle) Then Set GetRef = this.Store(Handle) Else Set GetRef = Nothing End If End Function </code></pre> <hr /> <h3>CleanUp cascade</h3> <p>A CleanUp cascade is an alternative approach to resolving circular references. It relies on a network of routines relaying clean-up flow control between affected objects and clearing attributes forming reference loops. This process can be initiated from the <em>Class_Terminate()</em> method of a top-level unaffected object. With loops due to Parent ↔ Children relationships, clearing parent references should suffice. The code below, however, resets both parent and children attributes. But once it has reset a given instance, it severs all links to other objects, making further traversal impossible. For this reason, the clean-up code traverses the object hierarchy in depth-first fashion via the CleanUp routines, nesting the calls and paving its way back via the call stack. After reaching the lowest affected node, the clean-up process resets the node and passes control back to its parent via a return from a nested CleanUp call.</p> <hr /> <p>The DbManager, DbConnection, and DbStatement classes incorporate both approaches for illustrative purposes, with one or the other (or neither) being conditionally selected by setting a public variable flag.</p> <p><strong>DbManager</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;Demo&quot; '@ModuleDescription &quot;Top database API class. Abstract factory for DbConnection.&quot; '@PredeclaredId Option Explicit Private Type TDbManager Connections As Scripting.Dictionary '''' Children collection InstanceCount As Long '''' Number of DbManager objects TimeStamp As Double DefaultInstance As Boolean End Type Private this As TDbManager Public Function Create() As DbManager Dim Instance As DbManager Set Instance = New DbManager Instance.Init Set Create = Instance End Function Friend Sub Init() Set this.Connections = New Scripting.Dictionary this.Connections.CompareMode = TextCompare this.DefaultInstance = False this.TimeStamp = GetEpoch() End Sub Private Sub Class_Initialize() If Me Is DbManager Then this.InstanceCount = 0 Else DbManager.InstanceAdd End If this.DefaultInstance = True Dim InstanceType As String InstanceType = IIf(Me Is DbManager, &quot;Default&quot;, &quot;Regular&quot;) Debug.Print EpochToString(this.TimeStamp) &amp; &quot;: DbManager /&quot; &amp; _ InstanceType &amp; &quot; - Class_Initialize&quot; End Sub Private Sub Class_Terminate() If ObjectStoreGlobals.ReferenceLoopManagementMode = REF_LOOP_CLEANUP_CASCADE Then CleanUp End If DbManager.InstanceDel Dim InstanceType As String InstanceType = IIf(this.DefaultInstance, &quot;Default&quot;, &quot;Regular&quot;) Debug.Print GetTimeStampMs &amp; &quot;: DbManager /&quot; &amp; _ InstanceType &amp; &quot; - Class_Terminate&quot; End Sub Friend Sub CleanUp() Dim DbConn As DbConnection Dim DbConnHandle As Variant For Each DbConnHandle In this.Connections.Keys Set DbConn = this.Connections(DbConnHandle) DbConn.CleanUp Next DbConnHandle Set DbConn = Nothing this.Connections.RemoveAll Set this.Connections = Nothing End Sub Public Function CreateConnection(ByVal DbConnStr As String) As DbConnection Dim DbConn As DbConnection Set DbConn = DbConnection.Create(DbConnStr) Set this.Connections(DbConnStr) = DbConn Set CreateConnection = DbConn End Function Public Property Get InstanceCount() As Long If Me Is DbManager Then InstanceCount = this.InstanceCount Else InstanceCount = DbManager.InstanceCount End If End Property Public Property Let InstanceCount(ByVal Value As Long) If Me Is DbManager Then this.InstanceCount = Value Else DbManager.InstanceCount = Value End If End Property Public Sub InstanceAdd() If Me Is DbManager Then this.InstanceCount = this.InstanceCount + 1 Else DbManager.InstanceCount = DbManager.InstanceCount + 1 End If End Sub Public Sub InstanceDel() If Me Is DbManager Then this.InstanceCount = this.InstanceCount - 1 If this.InstanceCount = 0 Then If ObjectStoreGlobals.ReferenceLoopManagementMode = _ REF_LOOP_OBJECT_STORE Then Set ObjectStore = Nothing End If End If Else DbManager.InstanceCount = DbManager.InstanceCount - 1 End If End Sub '' </code></pre> <p><strong>DbConnection</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;Demo&quot; '@ModuleDescription &quot;Handles database connections. Abstract factory for DbStatement.&quot; '@PredeclaredId Option Explicit Private Type TDbConnection DbConnStr As String Statements As Scripting.Dictionary '''' Children collection TimeStamp As Double DefaultInstance As Boolean End Type Private this As TDbConnection '@DefaultMember Public Function Create(ByVal DbConnStr As String) As DbConnection Dim Instance As DbConnection Set Instance = New DbConnection Instance.Init DbConnStr Set Create = Instance End Function Friend Sub Init(ByVal DbConnStr As String) this.DbConnStr = DbConnStr Set this.Statements = New Scripting.Dictionary this.Statements.CompareMode = TextCompare this.DefaultInstance = False this.TimeStamp = GetEpoch() End Sub Private Sub Class_Initialize() this.DefaultInstance = True Dim InstanceType As String InstanceType = IIf(Me Is DbConnection, &quot;Default&quot;, &quot;Regular&quot;) Debug.Print EpochToString(this.TimeStamp) &amp; &quot;: DbConnection/&quot; &amp; _ InstanceType &amp; &quot; - Class_Initialize&quot; End Sub Private Sub Class_Terminate() Dim InstanceType As String InstanceType = IIf(this.DefaultInstance, &quot;Default&quot;, &quot;Regular&quot;) Debug.Print GetTimeStampMs &amp; &quot;: DbConnection/&quot; &amp; _ InstanceType &amp; &quot; - Class_Terminate&quot; End Sub Friend Sub CleanUp() Dim DbStmt As DbStatement Dim DbStmtHandle As Variant For Each DbStmtHandle In this.Statements.Keys Set DbStmt = this.Statements(DbStmtHandle) DbStmt.CleanUp Next DbStmtHandle Set DbStmt = Nothing this.Statements.RemoveAll Set this.Statements = Nothing End Sub Public Property Get DbConnStr() As String DbConnStr = this.DbConnStr End Property Public Function CreateStatement(ByVal DbStmtID As String) As DbStatement Dim DbStmt As DbStatement Set DbStmt = DbStatement.Create(Me, DbStmtID) Set this.Statements(DbStmtID) = DbStmt Set CreateStatement = DbStmt End Function </code></pre> <p><strong>DbStatement</strong></p> <pre class="lang-vb prettyprint-override"><code>'@Folder &quot;Demo&quot; '@ModuleDescription &quot;Prepares database queries.&quot; '@PredeclaredId Option Explicit Private Type TDbStatement DbConn As Variant DbStmtID As String TimeStamp As Double DefaultInstance As Boolean End Type Private this As TDbStatement Public Function Create(ByVal DbConn As DbConnection, ByVal DbStmtID As String) As DbStatement Dim Instance As DbStatement Set Instance = New DbStatement Instance.Init DbConn, DbStmtID Set Create = Instance End Function Friend Sub Init(ByVal DbConn As DbConnection, ByVal DbStmtID As String) this.DbStmtID = DbStmtID If ObjectStoreGlobals.ReferenceLoopManagementMode = REF_LOOP_OBJECT_STORE Then this.DbConn = ObjectStore.SetRef(DbConn) Else Set this.DbConn = DbConn End If this.DefaultInstance = False this.TimeStamp = GetEpoch() End Sub Private Sub Class_Initialize() this.DefaultInstance = True Dim InstanceType As String InstanceType = IIf(Me Is DbStatement, &quot;Default&quot;, &quot;Regular&quot;) Debug.Print EpochToString(this.TimeStamp) &amp; &quot;: DbStatement /&quot; &amp; _ InstanceType &amp; &quot; - Class_Initialize&quot; End Sub Private Sub Class_Terminate() Dim InstanceType As String InstanceType = IIf(this.DefaultInstance, &quot;Default&quot;, &quot;Regular&quot;) Debug.Print GetTimeStampMs &amp; &quot;: DbStatement /&quot; &amp; _ InstanceType &amp; &quot; - Class_Terminate&quot; End Sub Friend Sub CleanUp() this.DbConn = Empty End Sub Public Property Get DbConn() As DbConnection If ObjectStoreGlobals.ReferenceLoopManagementMode = REF_LOOP_OBJECT_STORE Then Set DbConn = ObjectStore.GetRef(this.DbConn) Else Set DbConn = this.DbConn End If End Property </code></pre> <p>The code is available from a GitHub <a href="https://github.com/pchemguy/ObjectStore" rel="nofollow noreferrer">repository</a> and further documentation - from GitHub <a href="https://github.com/pchemguy/ObjectStore" rel="nofollow noreferrer">pages</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T10:47:01.063", "Id": "270533", "Score": "1", "Tags": [ "object-oriented", "vba" ], "Title": "Resolving circular references in VBA via ObjectStore class and CleanUp cascade" }
270533
<p>Checking return flags is generally very important. But, when you don't need to based on meeting pre-conditions, the syntax gets unnecessarily ugly.</p> <p>This class allows returning a value with flags that the caller can ignore.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;tuple&gt; template &lt;class T, class U&gt; struct retval { T val; U flags; ~retval() = default; retval() = default; retval(T v) : val{v}, flags{} {} retval(T v, U u) : val{v}, flags{u} {} retval(const retval&amp;) = default; retval(retval&amp;&amp;) = default; retval&amp; operator=(const retval&amp;)=default; retval&amp; operator=(retval&amp;&amp;)=default; operator std::tuple&lt;T&amp;, U&amp;&gt; () { return as_tuple(); } operator T () { return val; } std::tuple&lt;T&amp;, U&amp;&gt; as_tuple() { return {val, flags}; } }; </code></pre> <p>Some usage examples:</p> <pre class="lang-cpp prettyprint-override"><code>retval&lt;int, bool&gt; foo(int x) { if (x &gt;= 0) { return {2*x, true}; } return {-2*x, false}; } // just return the first arg int goo1(int x) { return foo(x); } // use tie to grab args (needs the cvt to tuple&lt;&amp;,&amp;&gt;) int goo2(int x) { int y; bool z; std::tie(y, z) = foo(x); return y; } // using get -- this is fairly ugly int goo2b(int x) { return std::get&lt;0&gt;(foo(x).as_tuple()); } // Structured binding declarations int goo3(int x) { auto [y, z] = foo(x); return y; } </code></pre>
[]
[ { "body": "<h2>Naming:</h2>\n<p><code>retval</code> would be better named something like <code>[specific_function]_result</code> where the <code>[specific_function]</code> is the name of the function whose return value it is (e.g. <code>std::from_chars</code> and <code>std::from_chars_result</code>).</p>\n<hr />\n<h2>Compiler generated code:</h2>\n<pre><code>~retval() = default;\nretval() = default;\nretval(T v) : val{v}, flags{} {}\nretval(T v, U u) : val{v}, flags{u} {}\nretval(const retval&amp;) = default;\nretval(retval&amp;&amp;) = default;\n\nretval&amp; operator=(const retval&amp;)=default;\nretval&amp; operator=(retval&amp;&amp;)=default;\n</code></pre>\n<p>The compiler should generate most of these for us; we don't need to specify them explicitly.</p>\n<p>We can use aggregate initialization to initialize a <code>retval</code>. We can specify the default flags value in the declaration to ensure it's always initialized: <code>U flags = {};</code>.</p>\n<hr />\n<h2>Unnecessary tuples:</h2>\n<pre><code>operator std::tuple&lt;T&amp;, U&amp;&gt; () { return as_tuple(); }\nstd::tuple&lt;T&amp;, U&amp;&gt; as_tuple() { return {val, flags}; }\n</code></pre>\n<p>Structured binding can be used on a struct. So there's really no reason to convert to a tuple in the examples.</p>\n<hr />\n<h2>Avoid implicit conversions:</h2>\n<pre><code>operator std::tuple&lt;T&amp;, U&amp;&gt; () { return as_tuple(); }\noperator T () { return val; }\n</code></pre>\n<p>Implicit conversions are nearly always a bad idea (they're unclear and error-prone). Use <code>explicit</code> conversion operators, or simply delete these functions, as they are unnecessary. If we want to use only the first argument, we can simply do:</p>\n<pre><code>return foo(x).val;\n</code></pre>\n<hr />\n<h2>Use assertions to document reasoning:</h2>\n<p>If we're relying on logic to reason that we can ignore a particular value, it's better to make that explicit in the code using an assertion.</p>\n<hr />\n<p>So:</p>\n<pre><code>template&lt;class T, class F&gt;\nstruct retval {\n T value;\n F flags = {};\n};\n\nretval&lt;double, bool&gt; foo() { return { 1.0, true }; }\n\ndouble bar() {\n auto [value, flags] = foo();\n assert(flags);\n return value;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T18:33:45.930", "Id": "270545", "ParentId": "270543", "Score": "0" } }, { "body": "<p>I appreciate the idea. You want to be able to ignore the supplementary information being returned and keep just the main value.</p>\n<p>But I think using a <code>tuple</code> is just going out of your way to be complicated. It's not needed at all. Rather, just give two public fields of that type.</p>\n<p>Allow aggregate initialization to work (automatically).<br />\nAllow structured binding to work (automatically).</p>\n<p>The <em>only</em> thing you are adding is an implicit conversion to grab the first value.</p>\n<pre><code>template &lt;class T, class U&gt;\nstruct retval {\n T val;\n U flags;\n operator T () { return val; }\n};\n</code></pre>\n<p>That is, delete everything that merely added complexity without doing anything that wasn't happening already, or is automatically provided.</p>\n<p>Now you could get fancier to make it more efficient if <code>T</code> is not a trivial or built-in type. Prevent copying where it safely can, by overloading it for lvalue and rvalue objects.</p>\n<pre><code> operator T&amp; () &amp; { return val; }\n operator T () &amp;&amp; { return std::move(val); }\n</code></pre>\n<p>Assuming I got that right (not tested, just banged out) then if you write</p>\n<pre><code>void bar (const std::string&amp;);\nvoid baz (std::string_view);\nretval&lt;std::string,int&gt; foo (int placeholder);\n ⋮\nstd::string ans = foo(1);\n</code></pre>\n<p>it will <em>move</em> the principle value out of the structure before destroying it. But if you write:</p>\n<pre><code>auto result= foo(2);\nstd::string value = result;\n/* or */ bar(result);\n</code></pre>\n<p>then it will use a reference to the string that lives in the structure you decided to keep. But</p>\n<pre><code>baz(result); /* or */\nbaz(foo(3));\n</code></pre>\n<p>still won't work because it's a double user-defined conversion.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T15:55:53.810", "Id": "270648", "ParentId": "270543", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T17:07:08.020", "Id": "270543", "Score": "0", "Tags": [ "c++", "c++20" ], "Title": "Allow caller optional flags for returns" }
270543
<p>I have a vector of values <code>vals</code>, a same-dimension vector of frequencies <code>freqs</code>, and a set of frequency values <code>pins</code>.</p> <p>I need to find the max values of <code>vals</code> within the corresponding interval around each pin (from pin-1 to pin+1). However, the intervals merge if they overlap (e.g., [1,2] and [0.5,1.5] become [0.5,2]).</p> <p>I have a code that (I think) works, but I feel is not optimal at all:</p> <pre><code>import numpy as np freqs = np.linspace(0, 20, 50) vals = np.random.randint(100, size=(len(freqs), 1)).flatten() print(freqs) print(vals) pins = [2, 6, 10, 11, 15, 15.2] # find one interval for every pin and then sum to find final ones islands = np.zeros((len(freqs), 1)).flatten() for pin in pins: island = np.zeros((len(freqs), 1)).flatten() island[(freqs &gt;= pin-1) * (freqs &lt;= pin+1)] = 1 islands += island islands = np.array([1 if x&gt;0 else 0 for x in islands]) print(islands) maxs = [] k = 0 idxs = [] for i,x in enumerate(islands): if (x &gt; 0) and (k == 0): # island begins k += 1 idxs.append(i) elif (x &gt; 0) and (k &gt; 0): # island continues pass elif (x == 0) and (k &gt; 0): # island finishes idxs.append(i) maxs.append(np.max(vals[idxs[0]:idxs[1]])) k = 0 idxs = [] continue print(maxs) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T19:20:05.873", "Id": "270546", "Score": "1", "Tags": [ "python", "numpy" ], "Title": "find max value in islands defined by other vector" }
270546
<p>I'm interested in how I can improve my HTML and CSS? I didn't yet learn JS, even though I used it for onclick function, so I'm not currently interested in how to improve the JS in this code. I was wondering:</p> <p>Is it alright to use spans inside button for accessibility? First I had all divs, than made the parent div into a button tag so that the HTML is more accessible. Then I read that divs shouldn't be in button tags so I switched them for spans. Also input tag with checkbox is less informative probably?</p> <p>Is it OK to use span tags instead of ::before and ::after? I was first trying with pseudoelements but they didn't work with flex and alignments somehow, so I used spans, and later didin't try with pseudoelements. Is there any benefit to writing pseudo as opposed to two additional spans?</p> <p>Could I use flex and then style the transitions? I found that it was really hard to get the right dimensions when using flex, so I switched to position: absolute and insets. What is best practice when also doing transitions and having to calculate stuff?</p> <p>I also don't understand why the effect after deleting this part of the code causes misalignment as I thought it should only cause the span &quot;lines&quot; to be &quot;longer&quot;:</p> <p>.burger-top-open, .burger-bot-open { width: 50%; }</p> <p>LINK: <a href="https://jsitor.com/kAkUItFAM" rel="nofollow noreferrer">https://jsitor.com/kAkUItFAM</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function myFunction() { var burgerTop = document.getElementsByClassName("burger-top"); burgerTop[0].classList.toggle("burger-top-open"); var burgerMid = document.getElementsByClassName("burger-mid"); burgerMid[0].classList.toggle("burger-mid-open"); var burgerBot = document.getElementsByClassName("burger-bot"); burgerBot[0].classList.toggle("burger-bot-open"); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { padding: 0; margin: 0; box-sizing: border-box; } article { width: 100%; min-height: 100vh; display: grid; place-items: center; background-color: black; } .burger-box { all: unset; height: clamp(2rem, 20vw, 10rem); width: clamp(2rem, 20vw, 10rem); cursor: pointer; position: absolute; } .burger { position: absolute; height: 15%; width: 55%; background-color: darkblue; border-radius: 15rem; transition: transform 0.2s linear; } .burger-top { top: calc(25% - 6.25%); left: 0 } .burger-mid { top: calc(50% - 6.25%); width: 100%; } .burger-bot { top: calc(75% - 6.25%); right: 0 } .burger-top-open, .burger-bot-open { width: 50%; } .burger-mid-open { transform: rotate(-45deg); } .burger-top-open { transform: rotate(-315deg) translateX(25%) translateX(-6.25%); } .burger-bot-open { transform: rotate(-315deg) translateX(-25%) translateX(6.25%); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;article&gt; &lt;button class="burger-box" onclick="myFunction()"&gt; &lt;span class="burger burger-top"&gt;&lt;/span&gt; &lt;span class="burger burger-mid"&gt;&lt;/span&gt; &lt;span class="burger burger-bot"&gt;&lt;/span&gt; &lt;/button&gt; &lt;/article&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:23:18.660", "Id": "534375", "Score": "0", "body": "We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T09:14:54.790", "Id": "534385", "Score": "0", "body": "@BCdotWEB I don't know what you mean, it does work correctly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T10:10:33.867", "Id": "534387", "Score": "1", "body": "I misread the `I also don't understand why the effect after deleting this part of the code causes misalignment as I thought it should only cause the span \"lines\" to be \"longer\":`. Still, that part is off-topic here." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T19:44:04.730", "Id": "270548", "Score": "0", "Tags": [ "javascript", "html", "css", "html5" ], "Title": "Suggestions on how to upgrade HTML and CSS making a hamburger icon that transitions to \"X\" in the code below?" }
270548
<p>I am using a <code>KeyNotFoundException</code> to check if an item exists in a <code>Dictionary</code>, creating it when the exception is thrown:</p> <pre><code>public Section GetSection(int plankNo, int sectionNo) { if (plankNo &lt; 1 || plankNo &gt; NumberOfPlanks || sectionNo &lt; 1 || sectionNo &gt; SectionsPerPlank) { return Section.UNKNOWN; } try { return Sections[(plankNo, sectionNo)]; } catch (KeyNotFoundException) { var section = new Section(plankNo, sectionNo); Sections[(plankNo, sectionNo)] = section; return section; } } </code></pre> <p>In Python, this is more or less okay, but in C# it feels &quot;wrong&quot;. How can this be made better?</p> <p>(Note: I mistranslated &quot;shelve&quot; into &quot;plank&quot;, but it is everywhere in the system now...)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T20:43:05.657", "Id": "534348", "Score": "3", "body": "Using an exception will cause the stack to unwind every time you find a missing key, which will be very expensive. Just use the `ContainsKey` method on Dictionary, or `TryGetValue`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T15:16:18.553", "Id": "534423", "Score": "1", "body": "Since this is code review and not stack overflow we like to see more of the code to do a good review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T18:03:50.260", "Id": "534583", "Score": "1", "body": "Your implementation is not thread-safe since the existence check and creation are two separate operations (not a single atomic one as it suppose to). Depending on your application may or may not be a problem but you should be aware of it." } ]
[ { "body": "\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trygetvalue?view=net-6.0\" rel=\"nofollow noreferrer\"><code>TryGetValue</code></a> would be the way to go without using <code>KeyNotFoundException</code>.<br />\nIt would look like the below:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>(int, int) key = (plankNo, sectionNo);\nif (!Sections.TryGetValue(key, out Section section))\n{\n section = new Section(plankNo, sectionNo);\n Sections[key] = section;\n}\n\nreturn section;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:03:48.790", "Id": "270564", "ParentId": "270550", "Score": "1" } } ]
{ "AcceptedAnswerId": "270564", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T19:55:01.370", "Id": "270550", "Score": "0", "Tags": [ "c#", "hash-map", "error-handling" ], "Title": "Use an exception to check if item in dictionary" }
270550
<p>Given the current table:</p> <pre><code>+------------+-------+ | date | value | +------------+-------+ | 01/01/2000 | 1 | | 03/04/2000 | 3 | | 05/08/2000 | 4 | | 07/11/2000 | 2 | +------------+-------+ </code></pre> <p>For each <code>date</code> I'm looking to get an average of the values for the preceding dates where each value is discounted by a time factor. The time factor is calculated as follows:</p> <pre><code>discount_constant ** (date - date_of_value) </code></pre> <p>So if I want to calculate the average for <code>07/11/2000</code> then I would first get the time discounted value for <code>05/08/2000</code>:</p> <pre><code>date_diff_0508 = 07/11/2000 - 05/08/2000 time_discount_0508 = discount_constant ** date_diff time_discounted_value_0508 = time_discount * 4 </code></pre> <p>Then the time discounted value for <code>03/04/2000</code></p> <pre><code>date_diff_0304 = 05/08/2000 - 03/04/2000 time_discount_0304 = discount_constant ** date_diff time_discounted_value_0304 = time_discount * 3 </code></pre> <p>Then the time discounted value for <code>01/01/2000</code></p> <pre><code>date_diff_0101 = 03/04/2000 - 01/01/2000 time_discount_0101 = discount_constant ** date_diff time_discounted_value_0101 = time_discount * 1 </code></pre> <p>Where <code>td</code> = <code>time_discount</code> and <code>tdv</code> = <code>time_discount_value</code> I can then calculate the average as follows:</p> <pre><code>sum_tdv = sum([tdv_0508, tdv_0304, tdv_0101]) sum_td = sum([td_0508, td_0304, td_0101]) avg_stat = sum_tdv / sum_td </code></pre> <p>The final output would be:</p> <pre><code>+------------+-------+-----------------------+ | date | value | avg_discounted_value | +------------+-------+-----------------------+ | 01/01/2000 | 1 | NULL | | 03/04/2000 | 3 | 1.0000 | | 05/08/2000 | 4 | 2.0465 | | 07/11/2000 | 2 | 2.7732 | +------------+-------+-----------------------+ </code></pre> <p>In reality though there is another layer of complexity as the actual table has a <code>class</code> column and the time discounted averages need to be calculated by <code>class</code>. Below is the final output:</p> <pre><code>+------------+-------+-------+-----------------------+ | date | class | value | avg_discounted_value | +------------+-------+-------+-----------------------+ | 01/01/2000 | 1 | 1 | NULL | | 03/04/2000 | 1 | 3 | 1.0000 | | 05/08/2000 | 1 | 4 | 2.0465 | | 07/11/2000 | 1 | 2 | 2.7732 | | 01/01/2000 | 2 | 2 | NULL | | 03/04/2000 | 2 | 7 | 2.0000 | | 05/08/2000 | 2 | 3 | 4.6162 | | 07/11/2000 | 2 | 9 | 4.0150 | +------------+-------+-------+-----------------------+ </code></pre> <p>Via a for loop I currently query a database to extract all the records for each <code>class</code> and convert them into a dictionary:</p> <pre><code>values_by_date = [ {&quot;datetime&quot;: dt.datetime(2000, 1, 1), &quot;value&quot;: 1}, {&quot;datetime&quot;: dt.datetime(2000, 4, 3), &quot;value&quot;: 3}, {&quot;datetime&quot;: dt.datetime(2000, 8, 5), &quot;value&quot;: 4}, {&quot;datetime&quot;: dt.datetime(2000, 11, 7), &quot;value&quot;: 2}, ] </code></pre> <p>I then run the following code over it:</p> <pre><code>import copy discount_constant = 0.999 desc_values_by_date = sorted(values_by_date, key=lambda d: d[&quot;datetime&quot;], reverse=True) iter_values_by_date = copy.deepcopy(desc_values_by_date) for isbd in iter_values_by_date[:-1]: del desc_values_by_date[0] for dsbd in desc_values_by_date: date_diff = (isbd[&quot;datetime&quot;] - dsbd[&quot;datetime&quot;]).days dsbd[&quot;discount_factor&quot;] = discount_constant ** date_diff dsbd[&quot;discount_value&quot;] = dsbd[&quot;discount_factor&quot;] * dsbd[&quot;value&quot;] sum_discount_factor = sum(dsbd[&quot;discount_factor&quot;] for dsbd in desc_values_by_date) sum_discount_value = sum(dsbd[&quot;discount_value&quot;] for dsbd in desc_values_by_date) avg_discounted_value = sum_discount_value / sum_discount_factor # some code to update the original database record with avg_discounted_value </code></pre> <p>Some additional notes:</p> <ol> <li>There are circa 1 million records in the database table with around 50k <code>class</code> variations which each have 1 - 2000 records</li> <li>The <code>class</code> column is indexed</li> <li>In the non-MRE version of my code I already make use of parallel processing</li> </ol> <p>The process above can take several minutes and there are currently over a hundred different <code>value</code> columns so the whole process can take hours to run.</p> <p>I've been reading about how numpy can be used to take advantage of vectorisation and speed up for loops. However, the examples I've found are rather simple and I can't extrapolate them into a solution for the above especially when my end point is inserting calculated values back into a database. I'm also conscious that I think in Python and that the solution may actually lie with keeping all the calculations in the database via an SQL query.</p> <p>Solution thoughts I've had:</p> <ol> <li>Use numpy and vectorisation on a 'per <code>class</code>' basis</li> <li>Use numpy and vectorisation on all <code>class</code> variations at the same time</li> <li>Convert everything into a single SQL <code>UPDATE</code> query</li> </ol> <p>Would anyone here have any ideas on the best approach?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T20:18:55.463", "Id": "270551", "Score": "0", "Tags": [ "python", "mysql", "numpy" ], "Title": "Calculate of the average of time discounted values" }
270551
<p>I was looking for C++ versions of the machine learning metrics implemented in Python's sklearn, but they were surprisingly hard to find. I came across <a href="https://cppsecrets.com/user/index.php?id=articles&amp;uid=5758" rel="nofollow noreferrer">a website that had most of the loss functions implemented in Python</a>, so I did my best to translate them to C++.</p> <p>Below is what I have so far. I plan to implement most of the metrics on that page.</p> <p>From testing, I'm not really getting the speed I was expecting.</p> <p>Two notes:</p> <ol> <li><p>I've found that object members having their own local variables, rather than having to access shared class variables, gives a small speed boost. That's why several functions have their own similar variables that I decided not to make class members.</p> </li> <li><p>I also found that using my own squaring function is faster than <code>std::pow(n, 2)</code>.</p> </li> </ol> <pre><code>// metrics.hpp #include &lt;vector&gt; #include &lt;cmath&gt; class Metrics { // utils double square (double res) { return res * res ; } public: // regression double mean_absolute_error ( const std::vector&lt;double&gt; &amp;y_true, const std::vector&lt;double&gt; &amp;y_pred) { double store {0} ; size_t size {y_true.size()} ; for (int i {0}; i &lt; size ; ++ i) { store += std::abs(y_true[i] - y_pred[i]) ; } return store/size ; } double root_mean_square_error ( const std::vector&lt;double&gt; &amp;y_true, const std::vector&lt;double&gt; &amp;y_pred) { double store {0} ; size_t size {y_true.size()} ; for (int i {0}; i &lt; size ; ++ i) { store += square((y_true[i] - y_pred[i])) ; } return std::sqrt(store / size) ; } double mean_gamma_deviance ( const std::vector&lt;double&gt; &amp;y_true, const std::vector&lt;double&gt; &amp;y_pred) { double store {0} ; size_t size {y_true.size()} ; for (int i {0}; i &lt; size ; ++ i) { store += 2.0 * (std::log(y_pred[i]/y_true[i]) + (y_true[i]/y_pred[i]) - 1.0) ; } return store / size ; } double mean_poisson_deviance ( const std::vector&lt;double&gt; &amp;y_true, const std::vector&lt;double&gt; &amp;y_pred) { double store {0} ; size_t size {y_true.size()} ; for (int i {0}; i &lt; size ; ++ i) { store += 2.0 * ((y_true[i]*std::log(y_true[i]/y_pred[i])) + (y_pred[i]-y_true[i])) ; } return store / size ; } // classification double accuracy ( const std::vector&lt;double&gt; &amp;y_true, const std::vector&lt;double&gt; &amp;y_pred) { double store {0} ; size_t size {y_true.size()} ; for (int i {0}; i &lt; size ; ++ i) { if (y_true[i] == y_pred[i]){ store += 1.0 ; } } return -(store / size) ; } double precision ( const std::vector&lt;double&gt; &amp;y_true, const std::vector&lt;double&gt; &amp;y_pred ) { double tp {0} ; // true positive double fp {0} ; // false positive size_t size {y_true.size()} ; for (int i {0}; i &lt; size ; ++ i) { if (y_true[i] == y_pred[i] == 1) { tp += 1.0 ; } } for (int i {0}; i &lt; size ; ++ i) { if (y_true[i] != y_pred[i] &amp;&amp; y_pred[i]==1) { fp += 1.0 ; } } return tp/(tp+fp) ; } double recall ( const std::vector&lt;double&gt; &amp;y_true, const std::vector&lt;double&gt; &amp;y_pred ) { double tp {0} ; // true positive double fn {0} ; // false negative size_t size {y_true.size()} ; for (int i {0}; i &lt; size ; ++ i) { if (y_true[i] == y_pred[i] == 1) { tp += 1.0 ; } } for (int i {0}; i &lt; size ; ++ i) { if (y_true[i] != y_pred[i] &amp;&amp; y_pred[i] == 0) { fn += 1.0 ; } } return tp/(tp+fn) ; } double f1 ( const std::vector&lt;double&gt; &amp;y_true, const std::vector&lt;double&gt; &amp;y_pred) { double prec {precision(y_true, y_pred)} ; double rec {recall(y_true, y_pred)} ; return -(2 * ((prec*rec) / (prec+rec))) ; } double jaccard_score ( const std::vector&lt;double&gt; &amp;y_true, const std::vector&lt;double&gt; &amp;y_pred) { double intersect {0} ; double uni {0} ; size_t size {y_true.size()} ; for (int i {0}; i &lt; size ; ++ i) { if (y_true[i] == y_pred[i]) { intersect += 1.0 ; } } for (int i {0}; i &lt; size ; ++ i) { uni += 1.0 ; } return intersect / uni ; } } met ; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T22:25:02.787", "Id": "534353", "Score": "0", "body": "The biggest reason why you don't get good speed is because you're not exactly using the right tools. You should look into CUDA programming or at least use a library like Eigen to benefit from hardware optimization and parallelism :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T06:01:16.757", "Id": "534372", "Score": "0", "body": "`y_pred[i] == 1`, `y_pred[i] == 0)` - are you sure `y_pred[]` is really `double`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T08:33:20.047", "Id": "534381", "Score": "0", "body": "@vnp Yes, my data and model predictions are all double. Obviously that can be changed if someone wants to use these methods with different types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T20:49:02.013", "Id": "534454", "Score": "0", "body": "@craftycroft, could you please also post your benchmarks? I believe those as important as the code being benchmarked. Collecting performance metrics correctly is an art on its own. Did you compile with optimizations? Could you please also provide python code to compare against." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T21:50:14.563", "Id": "534461", "Score": "0", "body": "I may write a review later (it usually takes me a few days because I write long reviews). However, as a quickie suggestion… are you sure you’re actually profiling optimized code? [GCC optimizes `std::pow(x, 2);` to `mulsd %xmm0, %xmm0` even at `-O1`](https://godbolt.org/z/9vb7x8rx7). Frankly the level of micro-optimizing you’re doing is ridiculous with modern compilers. *Are* you using a modern compiler?" } ]
[ { "body": "<h1>Design review</h1>\n<p>There are two very common mistakes people make when trying to translate code from other languages to C++ looking for a performance boost.</p>\n<p>The first is trying a direct translation: that is, literally rewriting the exact same code logic from the other language to C++. There are <em>countless</em> posts on StackOverflow from people who rewrote some code from another language in C++, and are baffled why they aren’t getting a massive speed improvement. The reason for that should be obvious; if you just do the exact same thing in C++ that you did in Python or Java or whatever… what else would you expect to happen? C++ isn’t magical. It will take your CPU the same time to add, multiply, and do all the other operations regardless of the language you specified those operations in. If you do the same operations, you’ll get roughly the same performance.</p>\n<p>Each programming language has its own philosophy. When I write Python, I <em>think</em> very differently than when I write C++. If you want to get the most out of C++, you need to align your thinking with the philosophy of C++. You need to do things the C++ way. You need to learn and use the language’s idioms. Good code looks <em>very</em> different in C++ than it does in Python, even when that code is supposed to be doing the same thing.</p>\n<p>That being said…</p>\n<p>Sometimes—quite often, in fact—you <em>will</em> get a performance boost from a simple direct translation to C++. Maybe not as much as you were hoping for, but the exact same algorithm <em>usually</em> runs at least a little bit faster when implemented in C++. And the reason for that is: the compiler.</p>\n<p>Which brings us to the second common mistake people trying to translate code to C++ for a performance boost make: thinking that it’s all about the language.</p>\n<p>C++, more so than perhaps any other popular language, <em><strong>DEPENDS</strong></em> on the compiler. That’s the true secret to its power and efficiency; C++ is designed, from the ground up, to work <em><strong>WITH</strong></em> the compiler—hand-in-hand, as a partnership. C++ without a compiler is… nothing; it’s actually a pretty shitty language, on its own. So if you’re just looking at the code—the language—without taking into account what the compiler can, should, and probably will do for you, you’re just not going to get the promised performance benefits of C++.</p>\n<p>So if you have an algorithm or tool implemented in another language, and you want better performance, you can <em>always</em>† get it with C++… but you need to do two things:</p>\n<ol>\n<li>You need to completely rethink, redesign, and rewrite the code, starting from scratch, using C++ philosophy.</li>\n<li>You need to work <em>with</em> the compiler. Don’t think of it just as a tool. In C++, the compiler is your partner in performance.</li>\n</ol>\n<p>(† There is no qualifier there; it is <em>always</em> possible, at least in theory, to get equivalent <em>or better</em> performance if you rewrite something in C++ <em>properly</em>. Yes, <a href=\"https://theory.stanford.edu/%7Eamitp/rants/c++-vs-c/\" rel=\"nofollow noreferrer\">C++ can even beat C</a>.)</p>\n<p>So let’s look at your code, keeping those two common mistakes in mind.</p>\n<p>So the original Python code put everything in classes for… reasons? A direct translation of <a href=\"https://cppsecrets.com/users/575811210512111711510410010510711510410511657575764103109971051084699111109/Python-Scikit-Learn-Precision-Score.php\" rel=\"nofollow noreferrer\">the precision score code</a> would look something like this:</p>\n<pre><code>class Precision\n{\n std::size_t tp = 0;\n std::size_t fp = 0;\n\npublic:\n auto true_positive(std::vector&lt;double&gt; const&amp; l1, std::vector&lt;double&gt; const&amp; l2)\n {\n for (auto i : std::views::iota(decltype(l1.size()){}, l1.size()))\n {\n if (l1[i] == l2[i] and l2[i] == 1) // *\n tp += 1;\n }\n\n // *: Note that Python promises that l2[i] is only evaluated once,\n // while C++ does not. However, even the most half-assed C++\n // compiler will optimize it to a single load.\n }\n\n auto false_positive(std::vector&lt;double&gt; const&amp; l1, std::vector&lt;double&gt; const&amp; l2)\n {\n for (auto i : std::views::iota(decltype(l1.size()){}, l1.size()))\n {\n if (l1[i] != l2[i] and l2[i] == 1)\n fp += 1;\n }\n }\n\n auto calc_precision(std::vector&lt;double&gt; const&amp; l1, std::vector&lt;double&gt; const&amp; l2)\n {\n true_positive(l1, l2);\n false_positive(l1, l2);\n\n std::cout &lt;&lt; (tp / double(tp + fp));\n }\n};\n</code></pre>\n<p>However, that’s <em>horrible</em> C++.</p>\n<p>Your version of the precision score code is essentially just that, with <code>true_positive()</code> and <code>false_positive()</code> inlined, and the member variables <code>tp</code> and <code>fp</code> turned into local variables (and, of course, you return the value instead of printing it). That’s a <em>slight</em> improvement—some bugs are fixed, some new bugs are introduced, but overall it’s a bit better. However, it’s still not what you’d write if you were actually trying to solve this problem in C++.</p>\n<p>Additionally, the “fixes” you made—like moving the member variables to be locals, creating your own <code>square()</code> function, and so on—are mostly micro-optimizations attempting to “outsmart” or work around the compiler. But the compiler is a <em><strong>LOT</strong></em> smarter than you give it credit for. I dare say: the compiler is smarter than you are. I don’t say that to imply you’re not smart: in point of fact, I know the compiler is smarter than I am, too.</p>\n<p>Let’s consider the squaring issue. You claim that manually squaring via <code>x * x</code> is faster than <code>std::pow(x, 2)</code>. I call bullshit. I mentioned in a comment that <a href=\"https://godbolt.org/z/9vb7x8rx7\" rel=\"nofollow noreferrer\">GCC optimizes <code>std::pow(x, 2)</code> to a single multiply instruction even at optimization level 1</a>, but I also offer <a href=\"https://quick-bench.com/q/jTITYv4mPxGECAU03Lmdo_cVJlo\" rel=\"nofollow noreferrer\">this Quick Bench comparison (which uses Clang, just for variation) that shows <em>exactly</em> the same performance either way</a>.</p>\n<p>But let’s dig deeper. Let’s try <em>cubing</em>. <a href=\"https://godbolt.org/z/E1bh4M9Wf\" rel=\"nofollow noreferrer\">Aha! Now we see that GCC <em>doesn’t</em> replace the call to <code>std::pow(x, 3)</code></a>! Have we finally outsmarted the compiler?</p>\n<p>Nope. In fact, the compiler has <em>way</em> outsmarted both of us.</p>\n<p>See, what’s happening here is super-complex, and goes deep into the weeds of how numbers and calculations work in a computer, IEEE 754 crap, and so on. But the very, very basic explanation is that the compiler can always transform <code>pow(x, 2)</code> into a single multiply instruction because the multiply is done using double-wide registers. In other words, <code>double</code> is 64 bits, but the <code>xmm0</code> register is 128 bits. If you multiply 2 64-bit numbers, the result can <em>never</em> exceed 128 bits. But if you multiply <em>3</em> 64-bit numbers, as in cubing, the answer could potentially be 192 bits. That’s overflowing the <code>xmm0</code> register, so it is necessary to include error-handling code to detect and report that.</p>\n<p><em>However</em>…</p>\n<p>You can disable proper IEEE 754 behaviour in GCC. Just add the <code>-ffast-math</code> flag (in the top right box, just after <code>-O1</code>). Now look at what happened. In fact, try replacing the <code>3</code> with <code>4</code>. Try <code>10</code>. Try <code>1254</code>. Hell, try <code>0.5</code>! See? The compiler knows what’s going on.</p>\n<p>For the record, moving those member variables to be local variables… probably also doesn’t make a lick of difference. The compiler probably just does all the computation in registers in any case. You just wrote more code for no reason.</p>\n<p>The lesson here is <em><strong>TRUST THE COMPILER</strong></em>. More precisely, don’t assume the compiler is dumb and that you can do better by manually micro-optimizing. The compiler <em><strong>WILL</strong></em> beat you. Almost every time.</p>\n<p><em>Sometimes</em> the compiler might need more information to help it out. All compilers currently have ways to give the compiler this information, but there is not a standard, portable way, yet. There are several proposals in flight, though, like the contracts proposal, and <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p1774r4.pdf\" rel=\"nofollow noreferrer\">one specifically about assumptions</a>.</p>\n<p>The reason I’m hammering on this is because the fact that you’re finding performance improvements by manually squaring or moving variables around tells me that <em><strong>SOMETHING IS WRONG</strong></em>. I don’t know what you’re doing wrong, but I know that you’re doing <em>something</em> wrong. You shouldn’t have to treat the compiler like a dumb tool that has to be outsmarted to get performance. You should be able to cooperate with the compiler—basically, just write good, clear, idiomatic C++ code—and get top-notch performance. It’s 2021 (almost 2022!); if you can get better performance merely by doing silly stuff like manually unrolling loops, moving variables around, or expanding calculations with constants, something is <em>horribly</em> wrong.</p>\n<p>Before I go further, I want to address a comment by @IEatBagels, saying that you should be using numerics libraries like Eigen, or GPGPU techniques (as with CUDA). They’re not wrong that you <em>might</em> get some performance boosts with a numerics library… and <em>certainly</em> will if you offload the program to a number-crunching co-processor (which is essentially what a GPU is). But do you <em>need</em> either of those things? No, not really. All modern C++ compilers worth mentioning can already vectorize your code right out of the box, and most have OpenMP or the like built right-in. Frankly, the stuff you’re doing really isn’t complicated enough to warrant a third-party numerics library.</p>\n<p>As for using CUDA/OpenCL/Vulkan Compute/whatever… well, yeah, obviously that will make your code run faster, in the same sense that running <em>any</em> code on two or more computers rather than one will be faster. (Assuming the data set is large enough to make splitting the work over several processors, assuming the work is splittable, assuming blah blah blah all the other stuff that comes along with heterogeneous computing.) But that’s a whole different world of programming, at least for the time being; standard C++ doesn’t <em>yet</em> speak heterogeneous computing (but it’s coming!).</p>\n<p>Now, you’ve written your code as a class, where all the functions are member functions. Why? This doesn’t actually make any sense. Think of it from the mathematical/statistics sense: if someone wanted the MAE of a set of predictions, why would they need to first construct a “metrics object” before they can run the calculation they actually need?</p>\n<pre><code>auto const predictions = calculate_predictions();\nauto const observations = make_observations();\n\n// okay, now I want the MAE, so I *should* just be able to do:\nauto error = mean_absolute_error(predictions, observations);\n\n// but no, apparently I have to do:\nauto metrics = Metrics{};\nauto error = metrics.mean_absolute_error(predictions, observations);\n</code></pre>\n<p>And why? The <code>Metrics</code> object doesn’t serve any purpose. You just need it to call the function. So why not just have the function?</p>\n<p>Every one of those member functions (except <code>square()</code>, which serves no purpose) should be a free function. You could group them in a namespace if you really wanted to. (You should put <em>all</em> of your code in your own namespace, and these functions could be in their own sub-namespace.) But there doesn’t seem to be a need for a class.</p>\n<p>In addition, there is a remarkable amount of code duplication in those functions. Every one of the “regression” functions is (with modifications to correct the bugs):</p>\n<pre><code>template &lt;typename Func1, typename Func2&gt;\nauto regression(\n std::vector&lt;double&gt; const&amp; y_true,\n std::vector&lt;double&gt; const&amp; y_pred,\n Func1&amp;&amp; func_1,\n Func2&amp;&amp; func_2)\n{\n auto store = 0.0;\n auto size = y_true.size();\n\n for (auto i = decltype(size){}; i &lt; size ; ++i)\n {\n store += func_1(y_true[i], y_pred[i]);\n }\n\n return func_2(store / size);\n}\n</code></pre>\n<p>For example, <code>root_mean_square_error()</code> is:</p>\n<pre><code>auto root_mean_square_error(\n std::vector&lt;double&gt; const&amp; y_true,\n std::vector&lt;double&gt; const&amp; y_pred)\n{\n return regression(\n y_true,\n y_pred,\n [] (auto a, auto b) { return std::pow(a - b, 2); },\n [] (auto r) { return std::sqrt(r); }\n );\n}\n</code></pre>\n<p>And, because you are worried about performance and such, you can verify with Compiler Explorer that the code I wrote above generates <em>literally identical</em> assembly to the code in your version of <code>root_mean_square_error()</code> (once I correct the bugs, of course).</p>\n<p>The next step worth taking is to generalize. First, instead of hard-coding vectors, you could use <code>std::span</code>. That will allow you to use these functions with vectors, C++ arrays, C arrays, and even third-party numeric library array types. While we’re at it, we’ll remove the hard-coded <code>double</code> type:</p>\n<pre><code>template &lt;typename T, typename Func1, typename Func2&gt;\nauto regression(\n std::span&lt;T const&gt; y_true,\n std::span&lt;T const&gt; y_pred,\n Func1&amp;&amp; func_1,\n Func2&amp;&amp; func_2)\n{\n auto store = T{};\n\n auto p = y_true.begin();\n auto q = y_pred.begin();\n for (; p != y_true.end(); ++p, ++q)\n {\n store += func_1(*p, *q);\n }\n\n return func_2(store / y_true.size());\n}\n\n// For example:\ntemplate &lt;typename T&gt;\nauto root_mean_square_error(std::span&lt;T const&gt; y_true, std::span&lt;T const&gt; y_pred)\n{\n return regression&lt;T&gt;(\n y_true,\n y_pred,\n [] (auto a, auto b) { return std::pow(a - b, 2); },\n [] (auto r) { return std::sqrt(r); }\n );\n}\n</code></pre>\n<p>We could go even further, and make the code even more generic. But before we do that, I want to point out that what that <code>regression()</code> function is doing is a bog-standard algorithm. In fact, it’s such a common pattern, that there are actually <em>multiple</em> algorithms in the standard library that could do it. The old dog would be <code>std::inner_product()</code>:</p>\n<pre><code>template &lt;typename T, typename Func1, typename Func2&gt;\nauto regression(\n std::span&lt;T const&gt; y_true,\n std::span&lt;T const&gt; y_pred,\n Func1&amp;&amp; func_1,\n Func2&amp;&amp; func_2)\n{\n return func_2(\n std::inner_product(\n y_true.begin(),\n y_true.end(),\n y_pred.begin(),\n T{},\n std::plus&lt;&gt;{},\n std::forward&lt;Func1&gt;(func_1))\n / y_true.size());\n}\n</code></pre>\n<p>However, <code>std::transform_reduce()</code> is the out-of-order, parallelizable version of <code>std::inner_product()</code>. In your case, it’s okay to parallelize the algorithm, so you can use <code>std::transform_reduce()</code>.</p>\n<p>Now, without further comment, I’m just going to show you the way I would write <code>root_mean_square_error()</code> using C++20. I’m not saying my way is the “right” way, or the only way. I just want to illustrate a point.</p>\n<p>Here’s (basically) your version (with bugs fixed):</p>\n<pre><code>double root_mean_square_error (\n std::vector&lt;double&gt; const&amp; y_true, \n std::vector&lt;double&gt; const&amp; y_pred)\n{\n auto const size = y_true.size();\n\n auto store = 0.0;\n\n for (auto i = decltype(size){}; i &lt; size ; ++i)\n store += std::pow(y_true[i] - y_pred[i], 2);\n\n return std::sqrt(store / size) ;\n}\n</code></pre>\n<p>Here’s my version (just a rough, first pass… later I might properly constrain the detail function, and support sized and non-sized ranges, and so on):</p>\n<pre><code>namespace detail_ {\n\ntemplate &lt;typename T&gt;\nconcept not_bool = not std::is_same_v&lt;std::remove_cv_t&lt;T&gt;, bool&gt;;\n\ntemplate &lt;typename T&gt;\nconcept arithmetic = std::integral&lt;T&gt; or std::floating_point&lt;T&gt;;\n\n// This is just a basic implementation.\n//\n// To improve this, I'd constrain the template parameters, and account\n// for non-sized ranges and non-default constructible types and so on.\ntemplate &lt;typename R1, typename R2, typename F1, typename F2&gt;\nauto regression(R1&amp;&amp; y_true, R2&amp;&amp; y_pred, F1&amp;&amp; f1, F2&amp;&amp; f2)\n{\n return f2(\n std::transform_reduce(\n std::ranges::begin(y_true),\n std::ranges::end(y_true),\n std::ranges::begin(y_pred),\n std::ranges::range_value_t&lt;R1&gt;{},\n std::plus&lt;&gt;{},\n std::forward&lt;F1&gt;(f1))\n / std::ranges::size(y_true));\n}\n\n} // namespace detail_\n\ntemplate &lt;typename T&gt;\nconcept number = detail_::arithmetic&lt;T&gt; and detail_::not_bool&lt;T&gt;;\n\ntemplate &lt;std::ranges::input_range R1, std::ranges::input_range R2&gt;\n requires number&lt;std::ranges::range_value_t&lt;R1&gt;&gt;\n and std::same_as&lt;\n std::remove_cv_t&lt;std::ranges::range_value_t&lt;R1&gt;&gt;,\n std::remove_cv_t&lt;std::ranges::range_value_t&lt;R2&gt;&gt;&gt;\nauto root_mean_square_error_2(R1&amp;&amp; y_true, R2&amp;&amp; y_pred)\n // pre: not std::ranges::empty(y_true)\n // pre: std::ranges::size(y_true) == pre: std::ranges::size(y_pred)\n{\n return detail_::regression(\n std::forward&lt;R1&gt;(y_true),\n std::forward&lt;R2&gt;(y_pred),\n [] (auto a, auto b) { return std::pow(a - b, 2); },\n [] (auto r) { return std::sqrt(r); });\n}\n</code></pre>\n<p>Couple things about my version:</p>\n<ol>\n<li><p>It’s a lot longer, but remember that that detail function gets reused for all the regression functions (<code>mean_absolute_error()</code>, <code>mean_gamma_deviance()</code>, etc.). You only need to test and optimize the one function, and all the regression functions will benefit from it.</p>\n</li>\n<li><p>That means that adding new regression functions is trivial. You want mean squared log error, max error, or whatever else? It’s a one-liner (not counting constraints, of course, but if you wanted to, you could make a single concept with all constraints, and reuse that).</p>\n</li>\n<li><p>It supports any numeric value type, not just <code>double</code>: integer types, <code>float</code>, <code>long double</code>, and even <code>float16</code>.</p>\n</li>\n<li><p>It supports any range type, not just <code>std::vector</code>: C++ arrays, C arrays, arbitrary third-party numeric library types, and even stream views.</p>\n</li>\n</ol>\n<p>And here’s the kicker. Are you ready for this? All that power, flexibility, and extensibility I gained—not to mention the simplification of testing, optimizing, and extending due to extracting the guts of all the regression functions into a single function—surely must come with a performance cost, right?</p>\n<p>Nope. <a href=\"https://quick-bench.com/q/P8oqVMaIfdQyJ8fcin6JrzZwGPU\" rel=\"nofollow noreferrer\">My version is up to 2× faster</a>.</p>\n<p><em>That</em> is what programming in C++ is all about: writing portable, high-level, reusable, and extensible code… that <em>still</em> melts CPUs and beats any other language out there.</p>\n<p>So here’s my summary of the high-level design review:</p>\n<ul>\n<li><p>Mechanically translating Python code to C++ will probably gain you some performance improvements, but <em>nothing</em> compared to what you could do if you just started from scratch in C++, writing code based on C++ philosophy, using C++ idioms.</p>\n</li>\n<li><p>You have an antagonistic relationship with your compiler, where you’re trying to tweak this and that to get around what you imagine the dumb tool’s limitations are. That kind of thinking made sense in the 1980s, maybe most of the 1990s, and <em>possibly</em> the early 2000s. But it doesn’t fly anymore. Modern compilers are so freaking advanced, that even <em>experts</em> are frequently gobsmacked by how smart they are at optimizing their code. Instead of trying to undermine, outmanoeuvre, and outsmart the compiler, you need to learn to respect it as a partner in your coding endeavours. You need to learn how to communicate with it—how to tell it what you want in a way it can understand, so it can work its magic to your benefit. Don’t say “the compiler is failing to optimize the code as much as I want, so I need to work around it”, say “what information do I need to give the compiler so it knows what I need it to do”.</p>\n</li>\n<li><p>Rather than simply throwing coding constructs at a problem because they’re the proverbial hammer that makes everything look like nails, think about what you’re trying to create on a conceptual level, and implement that in code. For example, if you want to calculate the mean value of a set of data, do you first get/build a “statistics object”, and then use that to do the calculation? No, of course not. You just do the calculation; you just plug the data into the formula, and get an answer out of it. A formula is a function (mathematically speaking and programatically speaking). So you don’t need a class, you just need a function.</p>\n<p>Incidentally, this is the kind of micro-optimization you generally don’t need to worry about, but in point of fact, having your statistics functions be non-static member functions of a class, rather than free functions, makes them less efficient. Member functions take an additional, hidden parameter—<code>this</code>—which you pay the price for ever time they’re called. Even if you don’t use it, that hidden <code>this</code> also prevents a number of other optimizations; for example, member functions can never be <code>[[gnu:const]]</code> (though they can be <code>[[gnu:pure]]</code>). This is yet another example of when doing the right thing in C++—in this case, making functions be just functions, without requiring unnecessary classes—automatically gives you better performance.</p>\n</li>\n<li><p>“DRY”—“don’t repeat yourself”. All of your functions can be refactored to pull common elements out into reusable detail functions, with no loss of usability or efficiency. Doing so makes everything easier to test and optimize, because the core of <em>all</em> the functions is in a single place. You only need to make it perfect once, and <em>all</em> of the functions will be better.</p>\n</li>\n<li><p>Think big. Rather than just writing functions that solve your immediate problem, step back and consider how you could solve <em>future</em> problems as well. Today you want to calculate the F-score of a vector of <code>double</code>s. Tomorrow you might need the F-score of a <code>boost::numeric::ublas::vector_slice&lt;boost::numeric::ublas::vector&lt;long double&gt;&gt;</code>. It takes virtually the same amount of effort to write the one function with <code>std::vector&lt;double&gt;</code> as it does to write a template that takes an arbitrary range (you can always add all the constraints and other concepts bells and whistles later; they’re not strictly necessary).</p>\n<p>Even if you never do end up using the function for anything other than <code>std::vector&lt;double&gt;</code>, you can still benefit from the practice of <em>trying</em> to generalize your code.</p>\n</li>\n</ul>\n<h1>Code review</h1>\n<p>Alright, now let’s dig into the actual code. Because the functions are so repetitive, I will mostly be able to review a single function, and the notes will apply to most/all.</p>\n<p>Before I get into the code, I have to comment on what’s <em>missing</em>.</p>\n<ul>\n<li><p>There is no namespace. You should always put your code in your own, personal namespace.</p>\n</li>\n<li><p>There is a serious lack of comments. You have comments grouping the functions—that’s very good—and comments explaining what <code>tp</code> and <code>fp</code> stand for—also good. (Though, honestly, I’d normally prefer to write out <code>true_positive</code> and <code>false_positive</code>. That’s a personal preference, though, and it doesn’t really apply to situations where the short version is the mathematical standard, as it is for <code>tp</code> and <code>fp</code>.)</p>\n<p>But there are no other comments explaining your reasoning. You don’t need to write useless comments that explain what the code is doing, but you do really need to explain when you are doing something non-obvious. For example, why do you loop over the data twice in <code>precision()</code> and <code>recall()</code>? Is there a reason? What about in <code>jaccard_score()</code>… isn’t <code>uni</code> just <code>size</code>?</p>\n<p>Note that merely the act of writing the comments—trying to explain your reasoning—forces you to <em>think</em> about your reasoning. Had you tried to explain why you were simply counting in the second loop in <code>jaccard_score()</code>, you would have realized you got the algorithm wrong. (Actually, you would have realized that <a href=\"https://cppsecrets.com/users/575811210512111711510410010510711510410511657575764103109971051084699111109/Python-Scikit-Learn-Jaccard-Score.php\" rel=\"nofollow noreferrer\">the original code’s documentation is wrong</a>.)</p>\n</li>\n<li><p>Most egregiously, there is not a single letter documenting the functions’ interfaces, preconditions, or usage. I can deduce from the code that you are not expecting empty vectors (otherwise, you’d be dividing by zero when you do <code>store / size</code>). But the only way I could spot that is by doing a detailed scan of the code… which most people are not going to have the time or inclination to do. I can also deduce that the sizes of the two vectors passed to all the functions must be the same. Those are important preconditions that users of your functions really need to know. Are there any other preconditions? For example, is, perhaps, the range of values in the two data sets supposed to be between zero and one?</p>\n</li>\n<li><p>Finally, no tests. How do you even know your functions work? (Spoiler: some of them don’t.) Code without tests is garbage code, in the sense that if someone checks in code without tests into a project I’m working on, I will immediately and summarily reject the code with prejudice, and throw the whole commit into the garbage. I won’t even look at it, so it doesn’t matter if it’s the most incredible code ever written by a god-level programmer. If it’s got no tests, it’s worse than useless to me.</p>\n<p>Writing tests for your code should be the <em>first</em> thing you do. It forces you to <em>think</em> about your interface and usability, so you will automatically write better code. You should use a proper test library, like Catch or Google Test, or Boost.Test, write the tests for your code first, and only <em>then</em> start writing your actual functions.</p>\n</li>\n</ul>\n<p>One more thing before we start: all of your functions have very restricted interfaces. They all take <code>std::vector&lt;double&gt;</code> and <em>only</em> <code>std::vector&lt;double&gt;</code>. This is unnecessarily restrictive. It is so easy to write generic code in C++. Let's start with one of your functions:</p>\n<pre><code> double mean_absolute_error (\n const std::vector&lt;double&gt; &amp;y_true, \n const std::vector&lt;double&gt; &amp;y_pred) {\n \n double store {0} ;\n size_t size {y_true.size()} ;\n \n for (int i {0}; i &lt; size ; ++ i) {\n \n store += std::abs(y_true[i] - y_pred[i]) ;\n \n }\n \n return store/size ;\n \n }\n</code></pre>\n<p>First, we refactor to use iterators rather than indexes. Iterators are not only more generic, they are… theoretically… faster. Why? Well, if you have an index and two arrays/vectors, you need 4 values:</p>\n<ol>\n<li>the start pointer of the first array</li>\n<li>the start pointer of the second array</li>\n<li>the index; and</li>\n<li>the end index.</li>\n</ol>\n<p>And on each loop iteration, you need to do three things:</p>\n<ol>\n<li>increment the index (<code>++index</code>)</li>\n<li>calculate the pointer for the first array (<code>start_1 + index</code>)</li>\n<li>calculate the pointer for the second array (<code>start_2 + index</code>)</li>\n</ol>\n<p>But with iterators you only need 3 values:</p>\n<ol>\n<li>the iterator for the first array</li>\n<li>the iterator for the second array; and</li>\n<li>the end iterator.</li>\n</ol>\n<p>And on each loop iteration, you only need to do two things:</p>\n<ol>\n<li>increment the iterator for the first array (<code>++p_1</code>)</li>\n<li>increment the iterator for the second array (<code>++p_2</code>)</li>\n</ol>\n<p>You see? Iterators are intrinsically more efficient. (In practice, the compiler might be able to optimize an index just as well… or it might simply ignore the index and use iterators internally.)</p>\n<p>So, refactoring the code to use iterators:</p>\n<pre><code> double mean_absolute_error (\n const std::vector&lt;double&gt; &amp;y_true, \n const std::vector&lt;double&gt; &amp;y_pred) {\n \n double store {0} ;\n \n auto p_1 = y_true.begin();\n auto p_2 = y_pred.begin();\n \n auto const q_1 = y_true.end();\n \n for (; p_1 != q_1; ++p_1, ++p_2) {\n \n store += std::abs(*p_1 - *p_2) ;\n \n }\n \n return store / y_true.size() ;\n \n }\n</code></pre>\n<p>And to make that completely generic, we just template the argument types, and use generic <code>begin()</code>, <code>end()</code>, and so on:</p>\n<pre><code> template &lt;typename R&gt;\n double mean_absolute_error (\n R const&amp; y_true, \n R const&amp; y_pred) {\n \n double store {0} ;\n \n auto p_1 = std::ranges::begin(y_true);\n auto p_2 = std::ranges::begin(y_pred);\n \n auto const q_1 = std::ranges::end(y_true);\n \n for (; p_1 != q_1; ++p_1, ++p_2) {\n \n store += std::abs(*p_1 - *p_2) ;\n \n }\n \n return store / std::ranges::size(y_true) ;\n \n }\n</code></pre>\n<p>That’s all there is to it.</p>\n<p>(It would be even simpler if we had <code>views::zip</code>, of course:</p>\n<pre><code> template &lt;typename R&gt;\n double mean_absolute_error (\n R const&amp; y_true, \n R const&amp; y_pred) {\n \n double store {0} ;\n \n for (auto const [a, b] : std::views::zip(y_true, y_pred))\n store += std::abs(a - b) ;\n \n return store / std::ranges::size(y_true) ;\n \n }\n</code></pre>\n<p>But we don’t get <code>zip</code> until C++23.)</p>\n<p>You could add further improvements from there, like constraining the template parameters, supporting value types other than <code>double</code>, and supplying different implementations for ranges that don’t have a constant size. But that’s just gravy. The code above already does everything your current code does, and much, much more, with no loss of efficiency.</p>\n<p>Alright, from the top:</p>\n<pre><code> double mean_absolute_error (\n const std::vector&lt;double&gt; &amp;y_true, \n const std::vector&lt;double&gt; &amp;y_pred) {\n</code></pre>\n<p><a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#nl18-use-c-style-declarator-layout\" rel=\"nofollow noreferrer\">The convention in C++ is to put the type modifiers with the type</a>. In plain English:</p>\n<ul>\n<li><code>T &amp;t</code> is C style.</li>\n<li><code>T&amp; t</code> is C++ style.</li>\n</ul>\n<pre><code> double store {0} ;\n</code></pre>\n<p>It’s good to space out your code a bit when it makes sense, but <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#nl15-use-spaces-sparingly\" rel=\"nofollow noreferrer\">there’s a point where it gets ridiculous</a>. There is no purpose to spacing the semicolon away from the statement it terminates; we don’t put spaces between the last letter and the period at the end of sentences. Nor is there any purpose to separating the braced initializer from the variable it’s initializing; <code>store {0}</code> makes it look like the <code>{0}</code> is unrelated to the <code>store</code>. (It’s also inconsistent to write <code>store {0}</code> but <code>y_true[0]</code>.)</p>\n<p>Also, you seem to really like the <code>type var{init};</code> form of variable declarations. That’s fine, but it does get a little weird when you <em>really</em> go all-in. For example, I’ve been programming C++ since before it was standardized, and I think this is the first time I’ve <em>ever</em> seen <code>for (int i {0}; ...)</code>. Tradition and convention has it as <code>for (int i = 0; ...)</code>. <em>Modern</em> convention is moving toward “<s>Almost</s> Always <code>auto</code>”, possibly with concept constraints, which would be <code>for (auto i = 0; ...)</code>, which is pretty much the same thing. One thing you need to be cautious of if you’re going to stick with the <code>type var{init};</code> form is that you should never use <code>auto</code> to get type deduction with that form. That’s because <code>auto var{init};</code> behaves differently depending on the version of C++, and in more recent versions, will deduce to an initializer list, not the type of <code>init</code>. Personally, I’m a big proponent of consistency, and there is only one declaration form that is perfectly consistent, and perfectly behaved in <em>all</em> cases: <code>auto var = init;</code>, or <code>auto var = type{init};</code> to force a type. But the form you like is fine… just don’t use <code>auto</code> with it.</p>\n<pre><code> size_t size {y_true.size()} ;\n \n for (int i {0}; i &lt; size ; ++ i) {\n</code></pre>\n<p>There are some insidious bugs lurking here.</p>\n<p>First, it’s <code>std::size_t</code>, not <code>size_t</code>.</p>\n<p>Second, the type of <code>y_true.size()</code> is <em>not</em> (necessarily) <code>std::size_t</code>. It’s <code>std::vector&lt;double&gt;::size_type</code>. It should be harmless to force that into a <code>std::size_t</code>, though. However…</p>\n<p>This is not good: <code>i &lt; size</code>. This is comparing a signed <code>int</code> to an unsigned <code>std::size_t</code>. Signed/unsigned comparisons are dangerous; if you compile with warnings turned on (and you should!) you should be getting warnings about this code.</p>\n<p>But there’s an even bigger problem. On some platforms, <code>int</code> is a <em>lot</em> smaller than either <code>std::size_t</code> or <code>std::vector&lt;double&gt;::size_type</code>… which means you could be getting truncation or wraparound (which would be UB). I believe <code>int</code> is only 32 bits on Windows, but <code>std::size_t</code> (and probably <code>std::vector&lt;double&gt;::size_type</code>) is 64, so this is not a rare problem you will only run into on obscure systems.</p>\n<p>This is why you may have noticed I rewrote these lines as:</p>\n<pre><code> auto size = y_true.size();\n\n for (auto i = decltype(size){}; i &lt; size ; ++i)\n</code></pre>\n<p>The <code>auto</code> here correctly sets the type of <code>size</code> to <code>std::vector&lt;double&gt;::size_type</code>, and the <code>decltype(size)</code> makes sure <code>i</code> is the same type.</p>\n<p>Even better, though, would be to use iterators. It’s unfortunately a little clunky because we don’t have <code>std::views::zip_view</code> until C++23, but it’s still safer, more flexible, and more efficient than indexes.</p>\n<p>Even <em>better</em>, though, would be to stop and think about what these loops and such are actually doing, identifying the patterns, and using standard library algorithms when appropriate.</p>\n<p>I’ll admit this is a little tricky in current C++, because all of the functions are working with two ranges simultaneously. Once we get <code>views::zip</code> in C++23, it will become easy. For example, <code>accuracy()</code> is:</p>\n<pre><code>auto accuracy(\n std::vector&lt;double&gt; const&amp; y_true,\n std::vector&lt;double&gt; const&amp; y_pred)\n{\n return -(double{\n std::ranges::count_if(\n std::views::zip(y_true, y_pred),\n [] (auto&amp;&amp; p) { return std::get&lt;0&gt;(p) == std::get&lt;1&gt;(p); })}\n / y_true.size());\n}\n</code></pre>\n<p>That’s just “zip the elements of <code>y_true</code> and <code>y_pred</code> together, then count the ones that are equal” (and convert to <code>double</code> and divide by the size for the final answer, of course).</p>\n<p>But even today, you can still do this with <code>std::inner_product()</code> or <code>std::transform_reduce()</code>… easy to spot, because there are very few algorithms that take two ranges, and even fewer that take two ranges <em>and</em> produce a single value (rather than another range). These functions are a bit more verbose because they don’t support ranges, but:</p>\n<pre><code>auto accuracy(\n std::vector&lt;double&gt; const&amp; y_true,\n std::vector&lt;double&gt; const&amp; y_pred)\n{\n return -(double{\n std::transform_reduce(\n std::ranges::begin(y_true),\n std::ranges::end(y_true),\n std::ranges::begin(y_pred),\n std::plus&lt;&gt;{},\n [] (auto&amp;&amp; a, auto&amp;&amp; b) { return a == b ? std::size_t{1} : std::size_t{0}; })}\n / y_true.size());\n}\n\n// or:\n\nauto accuracy(\n std::vector&lt;double&gt; const&amp; y_true,\n std::vector&lt;double&gt; const&amp; y_pred)\n{\n return -(double{\n std::inner_product(\n std::ranges::begin(y_true),\n std::ranges::end(y_true),\n std::ranges::begin(y_pred),\n std::size_t{0},\n std::plus&lt;&gt;{},\n [] (auto&amp;&amp; a, auto&amp;&amp; b) { return a == b ? std::size_t{1} : std::size_t{0}; })}\n / y_true.size());\n}\n</code></pre>\n<p><code>std::transform_reduce()</code> is better than <code>std::inner_product()</code>, though, because <code>std::inner_product()</code> <em>must</em> be done in order, while <code>std::transform_reduce()</code> can be done out-of-order, and even parallelized, which can be faster.</p>\n<p>And as I illustrated above, using standard algorithms can be <em>much</em> faster than hand-rolling your own loops, and that’s even before you start using things like <code>std::execution::par_unseq</code>.</p>\n<pre><code>store += 2.0 * ((y_true[i]*std::log(y_true[i]/y_pred[i])) + (y_pred[i]-y_true[i])) ;\n</code></pre>\n<p>There’s some really odd spacing going on there. I don’t get the logic of putting a space between the semicolon and the rest of the statement, but not a single space in <code>(y_true[i]*std::log(y_true[i]/y_pred[i]))</code>. I don’t see how that improves readability.</p>\n<p>Also, you’re not defending against <code>y_pred[i]</code> being zero. Same goes elsewhere where you divide by <code>y_true[i]</code>. And, of course, you never account for empty data sets where the size is zero.</p>\n<pre><code> double accuracy (\n const std::vector&lt;double&gt; &amp;y_true, \n const std::vector&lt;double&gt; &amp;y_pred) {\n \n double store {0} ;\n size_t size {y_true.size()} ;\n \n for (int i {0}; i &lt; size ; ++ i) {\n \n if (y_true[i] == y_pred[i]){\n \n store += 1.0 ;\n \n }\n \n }\n \n return -(store / size) ;\n \n }\n</code></pre>\n<p>All of your classification functions are essentially counting. In this case, you’re counting the number of times in the data set when the true and predicted values match.</p>\n<p>The problem is: you’re using a <code>double</code> to count. Yes, you <em>ultimately</em> want a <code>double</code>, so you can do the division and not get truncation. But for the actual counting, doing <code>store += 1.0</code> on most hardware will be <em>significantly</em> slower than doing <code>++store</code> (assuming <code>store</code> is an integer). On most hardware, you will get a <em>dramatic</em> performance boost if you do:</p>\n<pre><code>double accuracy (\n std::vector&lt;double&gt; const&amp; y_true, \n std::vector&lt;double&gt; const&amp; y_pred)\n{\n auto store = std::size_t{0};\n\n auto const size = y_true.size();\n for (auto i = decltype(store){0}; i &lt; size ; ++i)\n {\n if (y_true[i] == y_pred[i])\n ++store;\n }\n\n return -(double{store} / size);\n}\n</code></pre>\n<p>This is even more true for <code>precision()</code> and <code>recall()</code>, where you’re incrementing <em>two</em> <code>double</code>s, in <em>two</em> loops:</p>\n<pre><code>double precision (\n std::vector&lt;double&gt; const&amp; y_true, \n std::vector&lt;double&gt; const&amp; y_pred)\n{\n auto tp = std::size_t{0}; // true positive\n auto fp = std::size_t{0}; // false positive\n\n auto const size = y_true.size();\n for (auto i = decltype(store){0}; i &lt; size ; ++i)\n {\n if (y_true[i] == y_pred[i] and y_pred[i] == 1)\n ++tp;\n\n if (y_true[i] != y_pred[i] and y_pred[i] == 1)\n ++fp;\n }\n\n return tp / double{tp + fp};\n}\n</code></pre>\n<p>(Your compiler is probably smart enough to merge the two loops on its own. Still, it doesn’t really make sense to write two loops when you really only need one.)</p>\n<p>Before I move on, I need to comment about all the times you’re using <code>==</code> and <code>!=</code> with <code>double</code>s. That is almost always wrong. It is almost impossible to get <em>exactly</em> the same result from a set of mathematical operations if they’re not done in the <em>exact</em> same order. Also, if you’re dealing at all with any sort of analog input (like a sensor), line noise alone will screw up two readings that are supposed to be exactly the same.</p>\n<p>Comparing floating point numbers is a dark art. If I even <em>start</em> to explain it here, we’ll be here all day. But the bottom line is that you should give the user a way to specify a comparison function. You could always provide a sensible default for simplicity. For example:</p>\n<pre><code>template &lt;std::floating_point T&gt;\nconstexpr auto numeric_compare(T a, T b, T max_relative_error) noexcept\n // pre: not std::isnan(max_relative_error)\n{\n if (std::isunordered(a, b))\n return std::partial_ordering::unordered;\n\n if (std::abs(a - b) &lt;= (std::max(std::abs(a), std::abs(b)) * max_relative_error))\n return std::partial_ordering::equivalent;\n\n return (a &lt; b) ? std::partial_ordering::less : std::partial_ordering::greater;\n}\n\ntemplate &lt;std::floating_point T&gt;\nconstexpr auto numeric_compare(T a, T b) noexcept\n{\n return numeric_compare(a, b, std::numeric_limits&lt;T&gt;::epsilon());\n}\n\ntemplate &lt;std::integer T&gt;\nconstexpr auto numeric_compare(T a, T b) noexcept\n{\n return a &lt;=&gt; b;\n}\n\ntemplate &lt;typename NumericCompare&gt;\ndouble accuracy (\n std::vector&lt;double&gt; const&amp; y_true, \n std::vector&lt;double&gt; const&amp; y_pred,\n NumericCompare&amp;&amp; compare)\n{\n auto store = std::size_t{0};\n\n auto const size = y_true.size();\n for (auto i = decltype(store){0}; i &lt; size ; ++i)\n {\n if (compare(y_true[i], y_pred[i]) == 0)\n ++store;\n }\n\n return -(double{store} / size);\n}\n\ndouble accuracy (\n std::vector&lt;double&gt; const&amp; y_true, \n std::vector&lt;double&gt; const&amp; y_pred)\n{\n return accuracy(y_true, y_pred,\n [] (auto a, auto b) { return numeric_compare(a, b); });\n}\n</code></pre>\n<p>Then if I want, say, 6 digits of precision, I can do:</p>\n<pre><code>auto acc = accuracy(y_true, y_pred, [] (auto a, auto b) { return numeric_compare(a, b, 0.000001); });\n\n// or:\nauto my_compare = [] (auto a, auto b) { return numeric_compare(a, b, 0.000001); };\nauto acc = accuracy(y_true, y_pred, my_compare);\n</code></pre>\n<p>One more note about comparisons:</p>\n<pre><code> double precision (\n const std::vector&lt;double&gt; &amp;y_true, \n const std::vector&lt;double&gt; &amp;y_pred\n ) {\n \n double tp {0} ; // true positive\n double fp {0} ; // false positive\n \n size_t size {y_true.size()} ;\n \n for (int i {0}; i &lt; size ; ++ i) {\n \n if (y_true[i] == y_pred[i] == 1) { // &lt;--\n</code></pre>\n<p>That last line is wrong. Python allows chaining comparisons, so <code>a == b == c</code> gets rewriten as <code>a == b and b == c</code>. C++ does not support that. So <code>y_true[i] == y_pred[i] == 1</code> is interpreted as <code>(y_true[i] == y_pred[i]) == 1</code>. Which reduces to either <code>true == 1</code> or <code>false == 1</code>… which is just <code>true</code> or <code>false</code>. In other words, that whole expression is basically just <code>y_true[i] == y_pred[i]</code>. To mimic the Python behaviour, you want <code>y_true[i] == y_pred[i] and y_pred[i] == 1</code>. (Python needs chained operators because it does not have an optimizing compiler, so if you write <code>y_true[i] == y_pred[i] and y_pred[i] == 1</code>, <code>y_pred[i]</code> gets evaluated twice. C++ expects the compiler to optimize the repeated evaluation (presuming it has no side effects, of course).)</p>\n<pre><code> double jaccard_score (\n const std::vector&lt;double&gt; &amp;y_true, \n const std::vector&lt;double&gt; &amp;y_pred) {\n \n double intersect {0} ;\n double uni {0} ;\n \n size_t size {y_true.size()} ;\n \n \n for (int i {0}; i &lt; size ; ++ i) {\n \n if (y_true[i] == y_pred[i]) {\n \n intersect += 1.0 ;\n \n }\n }\n \n for (int i {0}; i &lt; size ; ++ i) {\n \n uni += 1.0 ;\n \n }\n \n return intersect / uni ;\n \n }\n</code></pre>\n<p>I believe this function is incorrect. (Did you test your code? If you’d written proper tests, and applied them, you would have discovered this.)</p>\n<p>As far as I understand it, the Jaccard index is <code>| y_true ∩ y_pred | ÷ | y_true ∪ y_pred |</code>. In other words, the size of the intersection divided by the size of the union. <code>uni</code> is not the size of the union, it’s just the size of the set. That loop:</p>\n<pre><code> for (int i {0}; i &lt; size ; ++ i) {\n \n uni += 1.0 ;\n \n }\n</code></pre>\n<p>is just <code>uni = double{size};</code>, calculated the long way around.</p>\n<p>You can calculate the size of the union as the size of both sets minus the size of the intersection… and you’ve already got the size of the intersection. So you could do:</p>\n<pre><code>auto jaccard_score (\n std::vector&lt;double&gt; const&amp; y_true, \n std::vector&lt;double&gt; const&amp; y_pred)\n{\n auto const set_size = y_true.size();\n\n auto intersection_size = std::size_t{0};\n for (auto i = decltype(set_size){0}; i &lt; set_size; ++i)\n {\n if (y_true[i] == y_pred[i]) // should do a proper comparison here\n ++intersection_size;\n }\n\n return double{intersection_size} / ((2 * set_size) - intersection_size);\n}\n</code></pre>\n<p>Finally:</p>\n<pre><code>} met ;\n</code></pre>\n<p>Why?</p>\n<p>Summary of code review:</p>\n<ul>\n<li><p>There are no comments at all, which means:</p>\n<ol>\n<li>No explanations of usage, so there’s no way to decide whether there might be better ways of accomplishing something.</li>\n<li>No precondition expectations, so there’s no way to know whether an unconsidered corner case is a bug or not.</li>\n<li>No postcondition promises, so there’s no way for a user of the code to know what state it might leave their program in.</li>\n<li>No explanations of rationale for any of the code, so there’s no way to know if something done in the code was done for very smart reasons, or was just a brain fart.</li>\n</ol>\n</li>\n<li><p>There are no tests at all. Untested code is garbage code, not even worthy of review in a serious project.</p>\n</li>\n<li><p>The usage of whitespace is… idiosyncratic, to say the least, and quite excessive. By my estimate, over half the lines of your code are just blank lines. Indenting is also excessive, and inconsistent: you indent the class access specifier (<code>public:</code>) by four spaces… and then indent the functions by <em>another</em> four spaces, except for <code>square()</code>. That’s 10% of the horizontal space in an 80 line text editor just wasted. There are spaces before semicolons, but not around binary operators… both of which hurt readability.</p>\n</li>\n<li><p>These functions should all be free functions; the <code>Metrics</code> class serves no purpose. There should be a namespace, though.</p>\n</li>\n<li><p>There is a massive amount of repetition. A refactor pulling out common code would make your functions simpler, easier to test, and easier to optimize (because you’d only need to test/optimize in one place).</p>\n</li>\n<li><p>Hand-rolled loops are a code smell. Use algorithms. Not only do they make your code easier to understand, they can also offer performance benefits.</p>\n</li>\n<li><p>Watch out for truncation and signed/unsigned comparisons. These are a common problem with hand-rolled loops. (Better yet, don’t write hand-rolled loops, or, if you must, use iterators, which are more flexible, and (theoretically) faster.)</p>\n</li>\n<li><p>Don’t compare floating point numbers with <code>==</code>.</p>\n</li>\n<li><p>Make your interfaces more generic. It’s not that much harder to support completely generic interfaces than it is to restrict it to <code>std::vector&lt;double&gt;</code>, and there is no performance cost.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T23:47:35.077", "Id": "270687", "ParentId": "270553", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-30T21:19:05.770", "Id": "270553", "Score": "3", "Tags": [ "c++", "performance", "machine-learning" ], "Title": "Machine Learning Loss Functions In C++" }
270553
<p>I have a function <code>general_statistics</code> that takes a dict as input and get the wanted information. the function is working without any problem, but I want to know if I can do it with a pythonic way because I'm trying to improve my skills.</p> <pre><code>def general_statistics(input_data: dict): result = {} if 'general' in input_data.keys(): if bool(input_data['general']): result['name'] = input_data['general']['name'] result['information'] = input_data['general']['information'] result['date'] = input_data['general']['creation_date'] result['adress'] = input_data['general']['adress'] if 'two' in input_data['general']['photo'].keys(): result['picture_person'] = input_data['general']['photo']['two']['ids'] else: result['picture_person'] = input_data['general']['photo']['one']['ids'] if 'phones' in input_data['general'].keys(): result['phones'] = input_data['general']['phones'] else: pass else: result['name'] = '' result['information'] = '' result['date'] = '' result['adress'] = '' else: result['name'] = '' result['information'] = '' result['date'] = '' result['adress'] = '' if 'intrest' in input_data.keys(): if bool(input_data['intrest']): intrest_list = [] for gender in input_data['intrest']['gender_type']: intrest_list.append(gender.split('/')[-1]) result['genders'] = intrest_list else: result['genders'] = [] if 'command_details' in input_data.keys(): if bool(input_data['command_details']): result['shiping'] = input_data['command_details']['shiping'] else: result['shiping'] = '' if 'command_statistics' in input_data.keys(): if bool(input_data['command_statistics']): result['com_statistics'] = input_data['command_statistics'] else: command_statistics = {} command_statistics['count'] = '' command_statistics['items'] = '' command_statistics['payed'] = '' command_statistics['unpayed'] = '' result['com_statistics'] = command_statistics else: command_statistics = {} command_statistics['count'] = '' command_statistics['items'] = '' command_statistics['payed'] = '' command_statistics['unpayed'] = '' result['com_statistics'] = command_statistics result['com_statistics'] = input_data['command_statistics'] if 'receiver_info' in input_data.keys(): if bool(input_data['receiver_info']): if 'general' in input_data['receiver_info'].keys(): result['receiver_date'] = input_data['receiver_info']['general']['creation_date'] result['receiver_info'] = input_data['receiver_info']['general']['information'] if 'adress' in input_data['receiver_info']['general'].keys(): result['receiver_adress'] = input_data['receiver_info']['general']['adress'] else: result['receiver_adress'] = '' if 'two' in input_data['receiver_info']['general']['photo'].keys(): result['receiver_pictures'] = input_data['receiver_info']['general']['photo']['two']['ids'] else: result['receiver_pictures'] = input_data['receiver_info']['general']['photo']['one']['ids'] result['receiver_stats'] = input_data['receiver_info']['command_statistics'] receiver_commands = [] if 'intrest' in input_data['receiver_info'].keys(): if input_data['receiver_info']['intrest']: for gender in input_data['receiver_info']['intrest']['gender_type']: receiver_commands.append( gender.split('/')[-1]) result['receiver_genders'] = receiver_commands if 'receiver_photo' in input_data['receiver_info']['receiver_brand'].keys(): result['receiver_brand_id_photo'] = input_data[ 'receiver_info']['receiver_brand']['receiver_photo']['id'] else: result['receiver_brand_id_photo'] = '' else: result['receiver_date'] = '' result['receiver_adress'] = '' result['receiver_stats'] = {} result['receiver_pictures'] = '' else: result['receiver_date'] = '' result['receiver_adress'] = '' result['receiver_stats'] = {} result['receiver_pictures'] = '' else: result['receiver_date'] = '' result['receiver_adress'] = '' result['receiver_stats'] = {} result['receiver_pictures'] = '' return result </code></pre> <p>A small example of the <code>input_data</code></p> <pre><code>input_data={ &quot;general&quot;: { &quot;creation_date&quot;: &quot;10/10/2015&quot;, &quot;first_id&quot;: &quot;10kahd&quot;, &quot;name&quot;: &quot;jacky&quot;, &quot;information&quot;: &quot;&quot;, &quot;photo&quot;: { &quot;one&quot;: { &quot;ids&quot;: &quot;1598&quot;, }, &quot;two&quot;: { &quot;ids&quot;: &quot;1489&quot; }, &quot;tree&quot;: { &quot;ids&quot;: &quot;0298&quot; } }, &quot;adress&quot;: &quot;10,new york 159&quot;, &quot;phones&quot;: [ &quot;number 1&quot;, &quot;number 2&quot; ], &quot;cat&quot;: &quot;01&quot;, }, &quot;command_details&quot;: { &quot;shiping&quot;: &quot;allowed&quot;, }, &quot;command_statistics&quot;: { &quot;count&quot;: &quot;226558&quot;, &quot;items&quot;: &quot;2015&quot;, &quot;payed&quot;: &quot;1500&quot;, &quot;unpayed&quot;: &quot;0&quot; }, &quot;intrest&quot;: { &quot;gender_type&quot;: [ &quot;chairs&quot; ] }, &quot;cmd_id&quot;: &quot;alsd952d&quot;, &quot;receiver_info&quot;: { &quot;general&quot;: { &quot;name&quot;: &quot;10,new york 159&quot;, &quot;information&quot;: &quot;&quot;, &quot;creation_date&quot;: &quot;01/06/2012&quot;, &quot;photo&quot;: { &quot;one&quot;: { &quot;ids&quot;: &quot;159z&quot; }, &quot;two&quot;: { &quot;ids&quot;: &quot;98zzf&quot; }, &quot;tree&quot;: { &quot;ids&quot;: &quot;pokAcs6&quot; } }, }, &quot;command_statistics&quot;: { &quot;count&quot;: &quot;15987643325&quot;, &quot;all_cmd_count&quot;: &quot;16549878466245&quot;, &quot;all_cmd_count_years&quot;: 125, &quot;sub_cmd&quot;: &quot;1664987322&quot; }, &quot;intrest&quot;: { &quot;gender_ids&quot;: [ &quot;qsmplos&quot; ], &quot;gender_type&quot;: [ &quot;chairs&quot;, &quot;pens&quot; ] }, &quot;receiver_brand&quot;: { &quot;brand_abdress&quot;: { &quot;adress&quot;: &quot;10,new york 159&quot; } }, } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:23:47.240", "Id": "534376", "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": "<p>Your</p>\n<pre><code>if 'general' in input_data.keys():\n if bool(input_data['general']):\n</code></pre>\n<p>could be</p>\n<pre><code>if 'general' in input_data:\n if input_data['general']:\n</code></pre>\n<p>or even</p>\n<pre><code>if general := input_data.get('general'):\n</code></pre>\n<p>and then use <code>general</code> instead of repeating <code>input_data['general']</code>.</p>\n<p>Alternatively, instead of mostly repeated statements extracting the data, you could configure the extractions as data and then use some general extraction code. Something like this (only some of the entries):</p>\n<pre><code>def general_statistics(input_data: dict):\n def genders(data):\n return [gender.split('/')[-1] for gender in data]\n config = [\n ('name', ('general', 'name'), ''),\n ('information', ('general', 'information'), ''),\n ('date', ('general', 'creation_date'), ''),\n ('adress', ('general', 'adress'), ''),\n ('picture_person', ('general', 'photo', 'one', 'ids')),\n ('picture_person', ('general', 'photo', 'two', 'ids')),\n ('phones', ('general', 'phones')),\n ('genders', ('intrest', 'gender_type', genders), []),\n ]\n result = {}\n for key, path, *default in config:\n data = input_data\n for step in path:\n if isinstance(step, str):\n if step not in data:\n if default:\n result[key] = default[0]\n break\n data = data[step]\n else:\n data = step(data)\n else:\n result[key] = data\n return result\n</code></pre>\n<p>You might also want to use a spell checker, as your data has quite a few typos (&quot;intrest&quot;, &quot;tree&quot;, &quot;adress&quot;, &quot;shiping&quot;, &quot;payed&quot;, &quot;unpayed&quot;).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T01:28:46.443", "Id": "270559", "ParentId": "270556", "Score": "1" } } ]
{ "AcceptedAnswerId": "270559", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T00:24:40.727", "Id": "270556", "Score": "1", "Tags": [ "python" ], "Title": "best way to get data from dict" }
270556
<p>I have two large arrays of objects, which look something like:</p> <pre class="lang-js prettyprint-override"><code>[ { key: &quot;prop&quot;, Email: &quot;someEmail@email.com&quot; }, //... ] </code></pre> <p>and</p> <pre class="lang-js prettyprint-override"><code>[ { key: &quot;prop&quot;, &quot;AN EMAIL&quot;: &quot;SomeEmail@emailcom&quot; }, //... ] </code></pre> <p>To compare the array of objects by email, I first map the arrays to only grab the emails, then I format the emails as follows:</p> <pre class="lang-js prettyprint-override"><code>const formatEmail = email =&gt; String(email).toLowerCase().replace(/\W/g, &quot;&quot;); const emails1 = objects1.map(o =&gt; formatEmail(o.Email)); const emails2 = objects2.map(o =&gt; formatEmail(o[&quot;AN EMAIL&quot;])); //... comparison code follows </code></pre> <p>However I was thinking of instead doing this as follows:</p> <pre class="lang-js prettyprint-override"><code>const formatEmail = email =&gt; String(email).toLowerCase().replace(/\W/g, &quot;&quot;); const emails1 = objects1.map(o =&gt; o.Email).map(formatEmail); const emails2 = objects2.map(o =&gt; o[&quot;AN EMAIL&quot;]).map(formatEmail); //... comparison code follows </code></pre> <p>I feel the second way is more readable, and there is not a significant performance difference in my use case. I would love feedback on this small exert from my project, and a reasoning of which way is better. Any feedback is appreciated. I did use generic naming for this example.</p> <p>For context of the use case for this code, the main reason I am writing this script is that we have lots of data that only partially matches in each system. This is usually due to human error on repeating data entry. I can run reports on each system and turn the data into objects to compare in javascript, and am building some logic that will attempt to draw a connection between the two objects based on their emails.</p>
[]
[ { "body": "<p>I also prefer the second example, due to the functional programming style. I believe it's easier to read because you've decoupled the getter from the transformation.</p>\n<p>The only change I'm tempted with is to pull out and share the getter logic with some currying. Something like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const emailGetter = key =&gt; o =&gt; o[key];\n\nconst emails1 = objects1.map(emailGetter('Email')).map(formatEmail);\nconst emails2 = objects2.map(emailGetter('AN EMAIL')).map(formatEmail);\n</code></pre>\n<p>If however, you have a preference for the point free function approach, like you did for <code>map(formatEmail)</code>, then this may be more fitting:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const emailGetter = key =&gt; o =&gt; o[key];\nconst o1Getter = emailGetter('Email');\nconst o2Getter = emailGetter('AN EMAIL');\n\nconst emails1 = objects1.map(o1Getter).map(formatEmail);\nconst emails2 = objects2.map(o2Getter).map(formatEmail);\n</code></pre>\n<p>The compromise being a higher setup fee for a cleaner call site.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T18:39:12.410", "Id": "534436", "Score": "2", "body": "I love the second example- how beautiful. I didn't even think about a getter. It might take a few more lines of code, but it feels consistent. I think the biggest issue I have with my example is it doesn't feel consistent. Thanks for your input " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:33:08.720", "Id": "534567", "Score": "2", "body": "Y'all are about 3 neuron impulses away from saying [currying](https://stackoverflow.com/q/36314/463206)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:40:52.183", "Id": "534568", "Score": "1", "body": "@radarbob you're right! I've edited to explictly call it out. I hope that's what you meant :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T14:31:19.923", "Id": "270579", "ParentId": "270557", "Score": "1" } } ]
{ "AcceptedAnswerId": "270579", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T00:27:36.643", "Id": "270557", "Score": "0", "Tags": [ "javascript", "array" ], "Title": "Map chaining vs execute on first map" }
270557
<p>I have some code that needs to return a <code>datetime</code> of the next 9am or 9pm, UTC. I've figured out some code to do this, but it feels unnecessarily complex to me. Is there a way to simplify this?</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime, timezone, timedelta class NineOClockTimes: @staticmethod def get_next_nineoclock_time(current_time: datetime) -&gt; datetime: if current_time.hour &lt; 9: return NineOClockTimes._get_nineoclock_time(current_time, hour=9) elif current_time.hour &gt;= 21: return NineOClockTimes._get_nineoclock_time(current_time, hour=9, next_day=True) return NineOClockTimes._get_nineoclock_time(current_time, hour=21) @staticmethod def _get_nineoclock_time(current_time, hour, next_day=False): new_time = current_time.replace( hour=hour, minute=0, second=0, microsecond=0, tzinfo=timezone.utc, ) if next_day: new_time += timedelta(days=1) return new_time </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T05:27:41.037", "Id": "534370", "Score": "0", "body": "what if the given `current_time` was 9:49 AM in UTC+1 timezone? (8:49 AM UTC)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:54:12.150", "Id": "534377", "Score": "0", "body": "@hjpotter92 I don't understand the question." } ]
[ { "body": "<p>There is a much simpler approach using <code>timedelta</code> to do this.</p>\n<p>You start by getting the current hour from <code>now</code> (<code>now.hour</code>). If you subtract this from <code>now</code> it will take you to midnight. Then we add/remove an appropriate number of extra hours to get to the 9am/pm you want - in this example I add 3:</p>\n<pre><code>now = datetime.now()\nprint(now)\n# datetime.datetime(2021, 12, 1, 10, 23, 32, 830310)\nnineish = now - timedelta(days=-1, hours=now.hour - 9) #-18 for 9pm\nprint(nineish)\ndatetime.datetime(2021, 12, 2, 9, 23, 32, 830310)\n</code></pre>\n<p>You can optionally also then throw away the mins/secs/usecs to get an exact date:</p>\n<pre><code>print(nineish.replace(minute=0, second=0, microsecond=0))\n# datetime.datetime(2021, 12, 2, 9, 0)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:10:23.650", "Id": "534438", "Score": "0", "body": "How do I figure out the \"appropriate number of hours\"? Doesn't that depend on what `now` is?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:12:32.433", "Id": "534439", "Score": "0", "body": "The first part gets you to midnight - you then need to either add 3, or subtract 9, depending on whether you want 9pm or am. In the code I add 3 to get to the previous 9pm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:19:05.930", "Id": "534440", "Score": "0", "body": "Isn't this giving me the *previous* day's 9pm? I'm asking for the next." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:24:17.580", "Id": "534444", "Score": "0", "body": "Apologies - misread the question. Have updated with different values to `timedelta`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T00:52:33.327", "Id": "534484", "Score": "0", "body": "This is definitely less code to think about, but I find myself thinking about how this answer works longer than I think about my existing solution. It might be a matter of extracting things into variable names or methods, etc." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T10:30:16.330", "Id": "270572", "ParentId": "270558", "Score": "1" } }, { "body": "<p>The class has no data, and only static methods. That suggests we don't need a class at all; plain functions should be perfectly adequate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T20:31:18.820", "Id": "534453", "Score": "1", "body": "Since the class is used as namespace we can keep the functions in a stand alone file and just `import {file} as NineOClockTimes`. There are some drawbacks to the approach as you won't be able to subclass `NineOClockTimes`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T20:11:19.980", "Id": "270596", "ParentId": "270558", "Score": "2" } }, { "body": "<p>Your function <code>_get_nineoclock_time</code> does two things, it replaces the <code>timezone</code> and it returns the next 9 O'clock time. The function will return different values depending on whether <code>current_time</code> has a timezone or not. That may be unexpected and seems a likely source of bugs. I'd set the timezone somewhere else.</p>\n<p>It is easy to calculate how many hours to add from midnight based on the current hour. Then use <code>timedelta</code> to add that many hours.</p>\n<pre><code>def get_next_nineoclock_time(current_time: datetime) -&gt; datetime:\n hours = 9 if current_time.hour &lt; 9 else 21 if current_time.hour &lt; 21 else 33\n \n midnight = current_time.replace(\n hour=0,\n minute=0,\n second=0,\n microsecond=0,\n )\n \n return midnight + timedelta(hours=hours)\n</code></pre>\n<p>Your could use this formula for <code>hours</code>, but I thinks it is less clear:</p>\n<pre><code>hours = 9 + 12*((current_time.hour + 3)//12)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T03:25:42.203", "Id": "534490", "Score": "0", "body": "Coincidentally, we realized that time zone issue today. I like this solution, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:29:06.083", "Id": "534566", "Score": "0", "body": "@DanielKaplan this timezone issue was what I had pointed out earlier in the comment on question :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T17:16:01.307", "Id": "534577", "Score": "0", "body": "@hjpotter92 ah, sorry I didn't understand it" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T02:32:15.377", "Id": "270603", "ParentId": "270558", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T00:40:14.073", "Id": "270558", "Score": "3", "Tags": [ "python", "python-3.x", "datetime" ], "Title": "Finding the next 9am/pm from now" }
270558
<p><a href="https://www.hackerrank.com/challenges/absolute-permutation/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/absolute-permutation/problem</a></p> <p>I know that if you work out the math and logic first, the algorithm can be simplified greatly (shifting indices), but is that the only way to solve this and pass all test cases? Checking if a value is in a list can be slow, but I don't know how to optimize/change that to a better code. Without altering the whole logic of my code, is it possible to tweak it to pass all test cases?</p> <pre><code>def absolutePermutation(number, k): newlist=[] for i in range(1,number+1): bigger=k+i smaller=i-k tmp=set(newlist) if (bigger&gt;number and smaller&lt;=0) or (bigger&gt;number and smaller in tmp) or (smaller&lt;=0 and bigger in tmp): return [-1] if smaller&lt;=0 or smaller in tmp: newn=bigger else: newn=smaller #print(newn) newlist.append(newn) return newlist </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T05:11:46.277", "Id": "534369", "Score": "0", "body": "_Does_ it pass all the test cases?" } ]
[ { "body": "<p>Yeah, you are recreating <code>tmp</code> every iteration of your loop. This makes your solution O(n^2). You could easily make your solution O(n) by setting <code>tmp</code> before your loop and then updating it along with <code>newlist</code>. The reason your current solution is O(n^2) is that building the tmp set with all the items in newlist would take as long as new list. For example, if <code>newlist=[1,2,3,4,5,6,7,...1000]</code> then constructing the tmp set would take 1000 steps.</p>\n<pre><code>def absolutePermutation(number, k):\n newlist=[]\n tmp=set()\n for i in range(1,number+1):\n bigger=k+i\n smaller=i-k\n if (bigger&gt;number and smaller&lt;=0) or (bigger&gt;number and smaller in tmp) or (smaller&lt;=0 and bigger in tmp):\n return [-1]\n\n if smaller&lt;=0 or smaller in tmp:\n newn=bigger\n else:\n newn=smaller\n\n #print(newn)\n\n newlist.append(newn)\n tmp.add(newn)\n\n return newlist\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T00:53:29.337", "Id": "534485", "Score": "0", "body": "Nice! Such a simple change actually passed all the tests. So I don't need the most efficient but hard to get to algorithm to solve this. Thanks for noticing the inefficiency!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T05:47:27.680", "Id": "270562", "ParentId": "270560", "Score": "1" } } ]
{ "AcceptedAnswerId": "270562", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T01:44:59.950", "Id": "270560", "Score": "0", "Tags": [ "python", "performance", "combinatorics" ], "Title": "Absolute Permutation | Hacker Rank: Any way to make this python code faster without changing it's whole logic?" }
270560
<p>Consider the following two classes:</p> <pre><code>public class Person&lt;P extends Comparable&lt;P&gt;&gt; { private List&lt;Person&lt;P&gt;&gt; following = new ArrayList&lt;Person&lt;P&gt;&gt;(); private List&lt;Person&lt;P&gt;&gt; friends = new ArrayList&lt;Person&lt;P&gt;&gt;(); private P id; public Person(P id) { this.id = id; } public P getId() { return id; } public List&lt;Person&lt;P&gt;&gt; getFollowing() { return following; } public List&lt;Person&lt;P&gt;&gt; getFriends() { return friends; } public boolean isFollowing(Person&lt;P&gt; person) { return following.contains(person); } public void addFriend(Person&lt;P&gt; person) { friends.add(person); } } public class WasteBookController&lt;P extends Comparable&lt;P&gt;&gt; { List&lt;Person&lt;P&gt;&gt; people = new ArrayList&lt;Person&lt;P&gt;&gt;(); /** * Adds a new member with the given name to the network. */ public void addPersonToNetwork(P name) { people.add(new Person&lt;P&gt;(name)); } /** * @preconditions person1 and person2 already exist in the social media network. * person1 follows person2 in the social media network. */ public void follow(P person1, P person2) { if (person1.equals(person2)) { return; } for (Person&lt;P&gt; member1 : people) { if (member1.getId().equals(person1)) { for (Person&lt;P&gt; member2 : people) { if (member2.getId().equals(person2)) { List&lt;Person&lt;P&gt;&gt; following = member1.getFollowing(); following.add(member2); if (member2.isFollowing(member1)) { member1.addFriend(member2); member2.addFriend(member1); } } } } } } public int getPopularity(P person) { Person&lt;P&gt; member = people.stream().filter(p -&gt; p.getId().equals(person)).findFirst().get(); int popularity = 0; for (Person&lt;P&gt; other : people) { List&lt;Person&lt;P&gt;&gt; following = other.getFollowing(); if (following.contains(member)) { popularity += 1; } } return popularity; } public int getFriends(P person) { Person&lt;P&gt; member = people.stream().filter(p -&gt; p.getId().equals(person)).findFirst().get(); return member.getFriends().size(); } /** * Returns an iterator to the network (each member) * ordered by the given parameter. */ public NetworkIterator&lt;P&gt; getIterator(String orderBy) { Comparator&lt;Person&lt;P&gt;&gt; comparator = null; if (orderBy.equals(&quot;popularity&quot;)) { comparator = Comparator.comparing(p -&gt; -getPopularity(p.getId())); } else if (orderBy.equals(&quot;friends&quot;)) { comparator = Comparator.comparing(p -&gt; -getFriends(p.getId())); } comparator = comparator.thenComparing(Person::getId); return new NetworkIterator&lt;P&gt;(people.stream() .sorted(comparator) .map(Person::getId) .collect(Collectors.toList()) .iterator()); } public void switchIteratorComparisonMethod(NetworkIterator&lt;P&gt; iter, String orderBy) { // TODO Part d) } } </code></pre> <p>I want to identify if there are any design issues or code smells in this.</p> <p>It's for a backend implementation for a face book where people can have followers and friends.</p> <p>A person cannot follow itself, and if a person1 follows person2 and person2 follows person1, they are friends.</p> <p>I am looking for some ways to improve it.</p> <p><code>P extends Comparable&lt;P&gt;</code> - Since I want the IDs to be comparable, I did this. But I am not sure if this is ideal.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T05:43:32.490", "Id": "534371", "Score": "0", "body": "Welcome to Code Review. Did you test any of this? It seems like a couple of library functions without implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T06:35:32.490", "Id": "534373", "Score": "1", "body": "In my opinion the template parameter `P` could be renamed as `PersonIdType`, it would be more insightful when re-reading the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T06:39:03.837", "Id": "534374", "Score": "0", "body": "Template parameters should only have a single letter names, otherwise they look like concrete class names. If P should be a PersonIdType then it should be defined as <P extends PersonIdType>" } ]
[ { "body": "<p>Surely, as you are aware of the term <em>code smell</em>, you have reads this? <a href=\"https://blog.codinghorror.com/code-smells/\" rel=\"nofollow noreferrer\">https://blog.codinghorror.com/code-smells/</a></p>\n<p>The first stench I sense is that you <em>indecently expose</em> the internal data structures of <code>Person</code> by returning the list instances directly from <code>getFollowing</code> and <code>getFriends</code>. This allows anyone to modify their content without any oversight leading in &quot;easy to make, hard to find&quot; ways of breaking the application data structures.</p>\n<p>Related to that, you define a single manipulation method <code>addFriend</code> for modifying the <code>friends</code>-list and a single query method <code>isFollowing</code>. There is no clear distinction on who is responsible for controlling the manipulation of the data structures or what manipulation and query operations should be available to the lists. Is the responsibility on <code>Person</code>, <code>WasteBookController</code> or whoever gets a handle to the lists?</p>\n<p>The <code>WasteBookController</code>, as it is now, gives out all the scents that make me expect it to become a monolith, a <em>large class</em>, loaded with <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">every possible responsibility</a>.</p>\n<p>You probably wil eventually want to store more information about relationship between two accounts (like when it was created, etc). Remember that secretly hoarding data from your users and selling it is the central business plan of the platform you are creating. For that you cannot just store lists of direct object references to <code>People</code>. You need classes for <code>Friendship</code> and <code>Following</code>. Then you would need a class for <code>Blocked</code> accounts. Maybe at this point it becomes easier to create a <code>Relationship</code> class with properties indicating the aforementioned statuses.</p>\n<p>You represent network with a field named <code>people</code>. That is <em>inconsistent naming</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T06:22:47.737", "Id": "270563", "ParentId": "270561", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T05:17:59.113", "Id": "270561", "Score": "0", "Tags": [ "java" ], "Title": "Objects for a face book" }
270561
<p>I have invented the fastest string search algorithm. It is called &quot;&quot;Choudhary String Search Algorithm (choudharyStringSearchAlgorithm)&quot;&quot;. I have compared my algorithm with Brute Force Algorithm, Boyer Moore Algorithm, Rabin Karp Algorithm, and Knuth Morris Pratt Algorithm and my algorithm is the fastest.</p> <p>You can copy this code and compile and run and see the results.</p> <p>Can someone do the code review please. The code is below:</p> <hr /> <h2>Fastest_String_Search_Algorithm.java</h2> <pre><code> import java.math.BigInteger; import java.util.*; import java.io.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; class Algo { String name; int numTimesCameFastest; long timeTaken; Algo(String name, int num, long timeTaken) { this.name = name; this.numTimesCameFastest = num; this.timeTaken = timeTaken; } // end of Algo constructor } // end of Algo public class Fastest_String_Search_Algorithm { static int numAlgos = 5; static int ASIZE = 256; static LinkedHashMap&lt;String, Algo&gt; algoMap = new LinkedHashMap&lt;String, Algo&gt;(); /* * Brute Force algorithm */ public static int bruteForceStringSearchAlgorithm(char[] text, char[] pattern) { int n = text.length; int m = pattern.length; //brute force it -- loop over all characters in text O(n) for (int i = 0; i &lt;= n - m; i++) { //index into the text //loop over all characters in pattern while characters match O(m) int k = 0; //index into the pattern while (k &lt; m &amp;&amp; text[i + k] == pattern[k]) { k++; } //if at end of pattern, then found match starting at index i in text if (k == m) { return i; } } // end of for loop return -1; } // end of bruteForceStringSearchAlgorithm /* * Boyer Moore algorithm */ public static void preBmBc(char[] pattern, int m, int[] bmBc) { int i = 0; for (i = 0; i &lt; ASIZE; ++i) { bmBc[i] = m; } for (i = 0; i &lt; m - 1; ++i) { bmBc[pattern[i]] = m - i - 1; } } // end of preBmBc public static void suffixes(char[] pattern, int m, int[] suff) { int f = 0; int g = 0; int i = 0; suff[m - 1] = m; g = m - 1; for (i = m - 2; i &gt;= 0; --i) { if (i &gt; g &amp;&amp; suff[i + m - 1 - f] &lt; i - g) { suff[i] = suff[i + m - 1 - f]; } else { if (i &lt; g) { g = i; } f = i; while (g &gt;= 0 &amp;&amp; pattern[g] == pattern[g + m - 1 - f]) { --g; } suff[i] = f - g; } } } // end of suffixes public static void preBmGs(char[] pattern, int m, int[] bmGs) { int i = 0; int j = 0; int[] suff = new int[m]; suffixes(pattern, m, suff); for (i = 0; i &lt; m; ++i) { bmGs[i] = m; } j = 0; for (i = m - 1; i &gt;= 0; --i) { if (suff[i] == i + 1) { for (; j &lt; m - 1 - i; ++j) { if (bmGs[j] == m) { bmGs[j] = m - 1 - i; } } } } for (i = 0; i &lt;= m - 2; ++i) { bmGs[m - 1 - suff[i]] = m - 1 - i; } } // end of preBmGs public static int boyerMooreStringSearchAlgorithm(char[] text, char[] pattern) { int i = 0; int j = 0; int m = pattern.length; int n = text.length; int[] bmGs = new int[m]; int[] bmBc = new int[ASIZE]; /* Preprocessing */ preBmGs(pattern, m, bmGs); preBmBc(pattern, m, bmBc); /* Searching */ j = 0; while (j &lt;= n - m) { for (i = m - 1; (i &gt;= 0) &amp;&amp; (pattern[i] == text[i + j]); --i); if (i &lt; 0) { return j; } else { j = j + ((bmGs[i] &gt; (bmBc[text[i + j]] - m + 1 + i)) ? bmGs[i] : (bmBc[text[i + j]] - m + 1 + i)); } } return -1; } // end of boyerMooreStringSearchAlgorithm /* * Rabin Karp algorithm */ public static int rabinKarpStringSearchAlgorithm(char[] text, char[] pattern) { int patternSize = pattern.length; // m int textSize = text.length; // n long prime = (BigInteger.probablePrime((Integer.SIZE - Integer.numberOfLeadingZeros(patternSize)) + 1, new Random())).longValue(); long r = 1; for (int i = 0; i &lt; patternSize - 1; i++) { r *= 2; r = r % prime; } long[] t = new long[textSize]; t[0] = 0; long pfinger = 0; for (int j = 0; j &lt; patternSize; j++) { t[0] = (2 * t[0] + text[j]) % prime; pfinger = (2 * pfinger + pattern[j]) % prime; } int i = 0; boolean passed = false; int diff = textSize - patternSize; for (i = 0; i &lt;= diff; i++) { if (t[i] == pfinger) { passed = true; for (int k = 0; k &lt; patternSize; k++) { if (text[i + k] != pattern[k]) { passed = false; break; } } if (passed) { return i; } } if (i &lt; diff) { long value = 2 * (t[i] - r * text[i]) + text[i + patternSize]; t[i + 1] = ((value % prime) + prime) % prime; } } return -1; } // end of rabinKarpStringSearchAlgorithm /* * Knuth Morris Pratt algorithm */ public static int[] KnuthMorrisPrattShift(char[] pattern) { int patternSize = pattern.length; int[] shift = new int[patternSize]; shift[0] = 1; int i = 1, j = 0; while ((i + j) &lt; patternSize) { if (pattern[i + j] == pattern[j]) { shift[i + j] = i; j++; } else { if (j == 0) { shift[i] = i + 1; } if (j &gt; 0) { i = i + shift[j - 1]; j = (((j - shift[j - 1]) &gt; 0) ? (j - shift[j - 1]) : 0); } else { i = i + 1; j = 0; } } } return shift; } // end of KnuthMorrisPrattShift public static int knuthMorrisPrattStringSearchAlgorithm(char[] text, char[] pattern) { int patternSize = pattern.length; // m int textSize = text.length; // n int i = 0, j = 0; int[] shift = KnuthMorrisPrattShift(pattern); while ((i + patternSize) &lt;= textSize) { while (text[i + j] == pattern[j]) { j += 1; if (j &gt;= patternSize) { return i; } } if (j &gt; 0) { i += shift[j - 1]; j = (((j - shift[j - 1]) &gt; 0) ? (j - shift[j - 1]) : 0); } else { i++; j = 0; } } return -1; } // end of knuthMorrisPrattStringSearchAlgorithm /* * Choudhary algorithm */ public static int choudharyStringSearchAlgorithm(char[] text, char[] pattern) { int i = 0; int j = 0; int text_len = text.length; int pattern_len = pattern.length; int pi_44 = pattern_len - 1; int[] skip_table = new int[ASIZE]; // preprocess pattern and fill skip_table for (i = 0; i &lt; ASIZE; i++) { skip_table[i] = -1; } for (i = 0; i &lt; pattern_len; i++) { skip_table[pattern[i]] = pattern_len - 1 - i; } // now search for (i = 0; i &lt; text_len; i++) { if ((text_len - i) &lt; pattern_len) { return -1; } if (pattern[pi_44] != text[i + pi_44]) { if (skip_table[(int) (text[i + pi_44])] == -1) { // this character doesn't occur in pattern, so skip i = i + pi_44; } else if (skip_table[(int) (text[i + pi_44])] &gt; 0) { i = i + skip_table[(int) (text[i + pi_44])] - 1; } continue; } for (j = pi_44 - 1; j &gt;=0; j--) { if (pattern[j] != text[i + j]) { if (skip_table[(int) (text[i + j])] == -1) { // this character doesn't occur in pattern, so skip i = i + j; } break; } } // end of inner for loop if (j == -1) { //string matched return i; } } // end of outer for loop return -1; } // end of choudharyStringSearchAlgorithm public static Algo getFastestAlgoEntryFromMap() { Algo tmpAlgo = null; Algo fastestAlgo = algoMap.get(&quot;BruteForce&quot;); for (Map.Entry&lt;String, Algo&gt; entry : algoMap.entrySet()) { tmpAlgo = entry.getValue(); if (tmpAlgo.timeTaken &lt; fastestAlgo.timeTaken) { fastestAlgo = tmpAlgo; } } return fastestAlgo; } // end of getFastestAlgoEntryFromMap public static void initializeTimeTakenOfAllMapEntries() { for (Map.Entry&lt;String, Algo&gt; entry : algoMap.entrySet()) { entry.getValue().timeTaken = 0; } } // end of initializeTimeTakenOfAllMapEntries public static void initializeNumTimesCameFastestOfAllMapEntries() { for (Map.Entry&lt;String, Algo&gt; entry : algoMap.entrySet()) { entry.getValue().numTimesCameFastest = 0; } } // end of initializeNumTimesCameFastestOfAllMapEntries public static void initializeAlgoMap() { algoMap.put(&quot;BruteForce&quot;, new Algo(&quot;Brute Force&quot;, 0, 0)); algoMap.put(&quot;BoyerMoore&quot;, new Algo(&quot;Boyer Moore&quot;, 0, 0)); algoMap.put(&quot;RabinKarp&quot;, new Algo(&quot;Rabin Karp&quot;, 0, 0)); algoMap.put(&quot;KnuthMorrisPratt&quot;, new Algo(&quot;KnuthMorrisPratt&quot;, 0, 0)); algoMap.put(&quot;Choudhary&quot;, new Algo(&quot;Choudhary&quot;, 0, 0)); } // end of initializeAlgoMap public static void main(String[] args) { Console c = new Console(); c.createAndShowConsole(); Console.jf.setTitle(&quot;Console&quot;); Algo tmpAlgo = null; int correctIndex = -1; int index = -1; long startTime = 0; long endTime = 0; String text = &quot;This past summer, I had the privilege of participating in the University of Notre Dame's Research Experience for Undergraduates (REU) program . Under the mentorship of Professor Wendy Bozeman and Professor Georgia Lebedev from the department of Biological Sciences, my goal this summer was to research the effects of cobalt iron oxide cored (CoFe2O3) titanium dioxide (TiO2) nanoparticles as a scaffold for drug delivery, specifically in the delivery of a compound known as curcumin, a flavonoid known for its anti-inflammatory effects. As a high school student trying to find a research opportunity, it was very difficult to find a place that was willing to take me in, but after many months of trying, I sought the help of my high school biology teacher, who used his resources to help me obtain a position in the program. Using equipment that a high school student could only dream of using, I was able to map apoptosis (programmed cell death) versus necrosis (cell death due to damage) in HeLa cells, a cervical cancer line, after treating them with curcumin-bound nanoparticles. Using flow cytometry to excite each individually suspended cell with a laser, the scattered light from the cells helped to determine which cells were living, had died from apoptosis or had died from necrosis. Using this collected data, it was possible to determine if the curcumin and/or the nanoparticles had played any significant role on the cervical cancer cells. Later, I was able to image cells in 4D through con-focal microscopy. From growing HeLa cells to trying to kill them with different compounds, I was able to gain the hands-on experience necessary for me to realize once again why I love science. Living on the Notre Dame campus with other REU students, UND athletes, and other summer school students was a whole other experience that prepared me for the world beyond high school. For 9 weeks, I worked, played and bonded with the other students, and had the opportunity to live the life of an independent college student. Along with the individually tailored research projects and the housing opportunity, there were seminars on public speaking, trips to the Fermi National Accelerator Laboratory, and one-on-one writing seminars for the end of the summer research papers we were each required to write. By the end of the summer, I wasn't ready to leave the research that I was doing. While my research didn't yield definitive results for the effects of curcumin on cervical cancer cells, my research on curcumin-functionalized CoFe2O4/TiO2 core-shell nanoconjugates indicated that there were many unknown factors affecting the HeLa cells, and spurred the lab to expand their research into determining whether or not the timing of the drug delivery mattered and whether or not the position of the binding site of the drugs would alter the results. Through this summer experience, I realized my ambition to pursue a career in research. I always knew that I would want to pursue a future in science, but the exciting world of research where the discoveries are limitless has captured my heart. This school year, the REU program has offered me a year-long job, and despite my obligations as a high school senior preparing for college, I couldn't give up this offer, and so during this school year, I will be able to further both my research and interest in nanotechnology. I believe that humans will always have the ability to rise above any situation, because life is what you make of it. We don't know what life is or why we are in this world; all we know, all we feel, is that we must protect it anyway we can. Buddha said it clearly: \&quot;Life is suffering.\&quot; Life is meant to be challenging, and really living requires consistent work and review. By default, life is difficult because we must strive to earn happiness and success. Yet I've realized that life is fickler than I had imagined; it can disappear or change at any time. Several of my family members left this world in one last beating symphony; heart attacks seem to be a trend in my family. They left like birds; laughing one minute and in a better place the next. Steve Jobs inspired me, when in his commencement address to Stanford University in 2005, he said \\\&quot;Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma--which is living with the results of other people's thinking.\\\&quot; I want to make mistakes, because that is how I learn; I want to follow the beat of my own drum even if it is \\\&quot;out of tune.\\\&quot; The important thing is to live without regrets, so when my heart ceases to beat, it will make one last happy note and move on. I want to live my life daily. Every day I want to live. Every morning when I wake up, I want to be excited by the gift of a new day. I know I am being idealistic and young, and that my philosophy on life is comparable to a calculus limit; I will never reach it. But I won't give up on it because, I can still get infinitely close and that is amazing. Every day is an apology to my humanity; because I am not perfect, I get to try again and again to \\\&quot;get it right.\\\&quot; I breathe the peace of eternity, knowing that this stage is temporary; real existence is continuous. The hourglass of life incessantly trickles on and we are powerless to stop it. So, I will forgive and forget, love and inspire, experience and satire, laugh and cry, accomplish and fail, live and die. This is how I want to live my life, with this optimistic attitude that every day is a second chance. All the time, we have the opportunity to renew our perspective on life, to correct our mistakes, and to simply move on. Like the phoenix I will continue to rise from the ashes, experienced and renewed. I will not waste time for my life is already in flux. In all its splendor The Phoenix rises In a burst of orange and yellow It soars in the baby blue sky Heading to that Great Light Baptized in the dance of time Fearless, eternal, beautiful It releases a breathtaking aurora And I gasp at the enormity In most conventional classrooms, we are taught to memorize material. We study information to regurgitate it on a test and forget it the following day. I thought this was learning. But this past summer, I realized I was wrong. I attended the SPK Program, a five-week enrichment program with New Jersey's best and brightest students. I lived on a college campus with 200 students and studied a topic. I selected Physical Science. On the first day of class, our teacher set a box on the table and poured water into the top, and nothing came out. Then, he poured more water in, and everything slowly came out. We were told to figure out what had happened with no phones or textbooks, just our brains. We worked together to discover in the box was a siphon, similar to what is used to pump gas. We spent the next weeks building solar ovens, studying the dynamic of paper planes, diving into the content of the speed of light and space vacuums, among other things. We did this with no textbooks, flashcards, or information to memorize. During those five weeks, we were not taught impressive terminology or how to ace the AP Physics exam. We were taught how to think. More importantly, we were taught how to think together. Learning is not memorization or a competition. Learning is working together to solve the problems around us and better our community. To me, learning is the means to a better future, and that's exciting. As I sip a mug of hot chocolate on a dreary winter's day, I am already planning in my mind what I will do the next summer. I briefly ponder the traditional routes, such as taking a job or spending most of the summer at the beach. However, I know that I want to do something unique. I am determined to even surpass my last summer, in which I spent one month with a host family in Egypt and twelve days at a leadership conference in New York City The college courses I have taken at Oregon State University since the summer after 7th grade will no longer provide the kind of challenge I seek. Six months later, I step off the airplane to find myself surrounded by palm trees, with a view of the open-air airport. I chuckle to myself about the added bonus of good weather, but I know I have come to Palo Alto, California, with a much higher purpose in mind. I will spend six weeks here in my glory, not only studying and learning, but actually pursuing new knowledge to add to the repertoire of mankind. Through the Stanford Institutes of Medicine Summer Research Program, I will earn college credit by conducting original molecular biology research, writing my own research paper, and presenting my findings in a research symposium. I decided to spend my summer doing research because I knew that I liked scientific thought, and that I would passionately throw myself into any new challenge. I always want to know more - to probe deeper into the laws of the universe, to explore the power and beauty of nature, to solve the most complicated problems. I have an insatiable curiosity and a desire to delve deeper down in the recesses of my intellect. At the Summer Research Program, I found out how much I enjoy thinking critically, solving problems, and applying my knowledge to the real world. While pursuing research in California, I was also able to meet many similarly motivated, interesting people from across the United States and abroad. As I learned about their unique lifestyles, I also shared with them the diverse perspectives I have gained from my travel abroad and my Chinese cultural heritage. I will never forget the invaluable opportunity I had to explore California along with these bright people. I could have easily chosen to spend that summer the traditional way; in fact, my parents even tried to persuade me into taking a break. Instead, I chose to do molecular biology research at Stanford University. I wanted to immerse myself in my passion for biology and dip into the infinitely rich possibilities of my mind. This challenge was so rewarding to me, while at the same time I had the most fun of my life, because I was able to live with people who share the same kind of drive and passion as I do. I held my breath as my steady hands gently nestled the crumbly roots of the lettuce plant into the soil trench that I shoveled moments before. Rainwater and sweat dripped from my brow as I meticulously patted and pressed the surrounding earth, stamping the leafy green creature into its new home. After rubbing the gritty soil off of my hands, I looked at Brian, a co-volunteer and nonverbal 20-year-old with autism, who extended his arm for a high-five. In the year that I've been working with him, I've watched him revel in planting, nurturing, and eventually harvesting his veggies, especially the grape tomatoes, which we enjoy eating fresh off the vine! Upon walking to the next row of hollowed cavities, we were not contemplating the lengthy work that lay ahead, but rather, we sought to liberate the helpless lettuces, imprisoned in produce cartons that were too small for them to grow in. Finally, after taking a step back to admire the day's last plant, my chest swelled as a wave of contentment flushed through my body. My love for gardening began when I moved to Georgia during my sophomore year. In the time I've spent learning how to garden, I've developed an affinity for watching my vegetables grow to maturity, eager to be harvested and sold at the Saturday market. Though many see gardening as tedious busywork, I find it meditative, as I lose track of time while combining peat moss and soil in the garden's compost mixer. Saturday morning garden work has become a weekend ritual, ridding me of all extraneous responsibilities. My body goes into autopilot as I let my mind wander. I don't actively focus on focusing, but rather I observe myself internally digest the week's events. I'm a bystander to fireworks of thought that explode in my mind as my perception of important matters becomes trivial. Sometimes, it's the physics midterm that suddenly seems less daunting or the deadlines I need to meet for my Spanish project that push back farther. Other times, I contemplate alternative endings to conversations or make perfect sense of the calculus answer that was at the tip of my tongue in class. I met Brian, a close friend of mine who also basks in the tranquility of nature, through my gardening endeavors. While we aren't able to communicate verbally, we speak the language of earth, water, peat, and seedlings. He doesn't speak with words, but his face tells stories of newly found purpose and acceptance, a pleasant contrast to the typical condescension and babying he feels by those who don't think he's capable of independent thought. Throughout my time in the garden with Brian, I began to understand that he, like everyone, has a particular method of communicating. There are the obvious spoken languages, body languages, facial expressions, and interactions we share on a day-to-day basis that reflect who we are and communicate what we represent. Brian expresses himself through various manifestations of unspoken language that he uses to signal how he feels or what he wants. But the nuanced combinations of different methods of communicating are oftentimes overlooked, raising a barrier to mutual understanding that prevents one from being capable of truly connecting with others. I began to understand that in order to reach people, I have to speak in their language, be it verbally or otherwise. Working with Brian over the past year has made me more aware that people can have difficulty expressing themselves. I found that I can positively lead people if I can communicate with them, whether on the track or in my Jewish youth group discussions. As I move into the next phases of my life, I hope to bring these skills with me because, in order to effectuate positive change in my community, I learned that I must speak in the language of those around me. Those are the words Brian taught me.&quot;; char[] ctext = text.toCharArray(); int textLen = text.length(); ArrayList&lt;Integer&gt; al = new ArrayList&lt;&gt;(); al.add(4); al.add(8); al.add(16); al.add(32); al.add(36); al.add(40); al.add(48); al.add(56); al.add(64); al.add(128); al.add(256); al.add(512); al.add(1024); int patternLen = 0; String pattern = &quot;&quot;; char[] cpattern = null; int totalNumberOfRunsPerPattern = 25; // initialize algo map initializeAlgoMap(); while (al.isEmpty() != true) { patternLen = al.remove(0); System.out.println(); System.out.println(&quot;===================== Summary (Text Len: &quot; + textLen + &quot;, Pattern Len: &quot; + patternLen + &quot;, Total number of runs per pattern: &quot; + totalNumberOfRunsPerPattern + &quot;) =====================&quot;); initializeNumTimesCameFastestOfAllMapEntries(); // initialize time taken by all algorithms to zero. initializeTimeTakenOfAllMapEntries(); pattern = text.substring(textLen - patternLen); cpattern = pattern.toCharArray(); correctIndex = text.indexOf(pattern); if (correctIndex == -1) { System.out.println(&quot;Pattern not found by indexOf() method...Exiting...&quot;); return; } for (int j = 0; j &lt; totalNumberOfRunsPerPattern; j++) { Console.jf.setTitle(&quot;Console (Current Run Number: &quot; + (j + 1) + &quot; / &quot; + totalNumberOfRunsPerPattern + &quot;, Pattern Len: &quot; + patternLen + &quot;)&quot;); // Brute Force algorithm startTime = System.nanoTime(); index = bruteForceStringSearchAlgorithm(ctext, cpattern); endTime = System.nanoTime(); if (index != correctIndex) { System.out.println(&quot;bruteForceStringSearchAlgorithm is not correct...Exiting...&quot;); return; } tmpAlgo = algoMap.get(&quot;BruteForce&quot;); tmpAlgo.timeTaken = tmpAlgo.timeTaken + (endTime - startTime); // Boyer Moore algorithm startTime = System.nanoTime(); index = boyerMooreStringSearchAlgorithm(ctext, cpattern); endTime = System.nanoTime(); if (index != correctIndex) { System.out.println(&quot;boyerMooreStringSearchAlgorithm is not correct...Exiting...&quot;); return; } tmpAlgo = algoMap.get(&quot;BoyerMoore&quot;); tmpAlgo.timeTaken = tmpAlgo.timeTaken + (endTime - startTime); // Rabin Karp algorithm startTime = System.nanoTime(); index = rabinKarpStringSearchAlgorithm(ctext, cpattern); endTime = System.nanoTime(); if (index != correctIndex) { System.out.println(&quot;rabinKarpStringSearchAlgorithm is not correct...Exiting...&quot;); return; } tmpAlgo = algoMap.get(&quot;RabinKarp&quot;); tmpAlgo.timeTaken = tmpAlgo.timeTaken + (endTime - startTime); // Knuth Morris Pratt algorithm startTime = System.nanoTime(); index = knuthMorrisPrattStringSearchAlgorithm(ctext, cpattern); endTime = System.nanoTime(); if (index != correctIndex) { System.out.println(&quot;knuthMorrisPrattStringSearchAlgorithm is not correct...Exiting...&quot;); return; } tmpAlgo = algoMap.get(&quot;KnuthMorrisPratt&quot;); tmpAlgo.timeTaken = tmpAlgo.timeTaken + (endTime - startTime); // Choudhary algorithm startTime = System.nanoTime(); index = choudharyStringSearchAlgorithm(ctext, cpattern); endTime = System.nanoTime(); if (index != correctIndex) { System.out.println(&quot;choudharyStringSearchAlgorithm is not correct...Exiting...&quot;); return; } tmpAlgo = algoMap.get(&quot;Choudhary&quot;); tmpAlgo.timeTaken = tmpAlgo.timeTaken + (endTime - startTime); tmpAlgo = getFastestAlgoEntryFromMap(); tmpAlgo.numTimesCameFastest = tmpAlgo.numTimesCameFastest + 1; } // end of for loop j &lt; totalNumberOfRunsPerPattern System.out.println(); for (Map.Entry&lt;String, Algo&gt; entry : algoMap.entrySet()) { tmpAlgo = entry.getValue(); float percent = (((((float) (tmpAlgo.numTimesCameFastest)) * 100) / totalNumberOfRunsPerPattern) * 100) / 100; System.out.println(tmpAlgo.name + &quot; algorithm is fastest \&quot;&quot; + percent + &quot;%\&quot; of times.&quot;); } System.out.println(); System.out.println(&quot;===================== End of Summary =====================&quot;); } // end of while true } // end of main } // end of Fastest_String_Search_Algorithm class Console implements KeyListener, ActionListener { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; String title = null; String text = null; static JFrame jf = null; JTextArea jta = null; JScrollPane jsp = null; JMenuBar jmb = null; JMenu jm = null; JMenuItem jmi = null; // key codes int BACKSPACE = 8; int ENTER = 10; int PG_UP = 33; // do nothing for this key pressed int PG_DN = 34; // do nothing for this key pressed int END = 35; int HOME = 36; int LEFT_ARROW = 37; int UP_ARROW = 38; // do nothing for this key pressed //int RIGHT_ARROW = 39; // handled by JTextArea int DOWN_ARROW = 40; // do nothing for this key pressed int CTRL = 128; int A = 65; // disable ctrl-a int H = 72; // handle ctrl-h //int DELETE = 127; // handled by JTextArea int initialCaretPosition = 0; int endOfInputCaretPosition = 0; Object lock1 = new Object(); Object lock2 = new Object(); boolean inputAvailable = false; byte[] b = null; int len = -1; int indexIntoByteArray = -1; boolean newLineSent = false; byte endOfInput = -1; byte newLine = 10; boolean enterAlreadyPressedEarlier = false; long Id_keyPressed = 0; long Id_getNextByteFromJTextArea = 0; long Id_outputToJTextArea = 0; public void actionPerformed(ActionEvent ae) { int cCurrPos = jta.getCaretPosition(); jta.selectAll(); jta.copy(); jta.select(cCurrPos, cCurrPos); } // end of actionPerformed public void keyTyped(KeyEvent ke) { } // end of keyTyped public void keyReleased(KeyEvent ke) { } // end of keyReleased public void keyPressed(KeyEvent ke) { Id_keyPressed = Thread.currentThread().getId(); int keyCode = ke.getKeyCode(); if ((keyCode == PG_UP) || (keyCode == PG_DN) || (keyCode == UP_ARROW) || (keyCode == DOWN_ARROW) || ((keyCode == A) &amp;&amp; (ke.getModifiersEx() == CTRL))) { ke.consume(); } else if ((keyCode == LEFT_ARROW) || (keyCode == BACKSPACE) || ((keyCode == H) &amp;&amp; (ke.getModifiersEx() == CTRL))) { synchronized (lock1) { if (jta.getCaretPosition() &lt;= initialCaretPosition) { ke.consume(); } } // end of synchronized block } else if (keyCode == HOME) { synchronized (lock1) { jta.setCaretPosition(initialCaretPosition); ke.consume(); } // end of synchronized block } else if (keyCode == END) { synchronized (lock1) { jta.setCaretPosition(jta.getDocument().getLength()); ke.consume(); } // end of synchronized block } else if (keyCode == ENTER) { // this if block should not exit until all the input has been // processed. synchronized (lock1) { inputAvailable = true; endOfInputCaretPosition = jta.getDocument().getLength(); //if ((endOfInputCaretPosition - initialCaretPosition) == 1) { // only newline was entered, so increment initialCaretPosition if ((enterAlreadyPressedEarlier == true) &amp;&amp; (endOfInputCaretPosition - initialCaretPosition) &gt; 0) { // need to increment initialCaretPosition by 1 to account for last enter pressed initialCaretPosition++; } jta.setCaretPosition(jta.getDocument().getLength()); enterAlreadyPressedEarlier = true; lock1.notifyAll(); } // wait until all input has been processed synchronized (lock2) { //if (Thread.holdsLock(lock2) == true) { System.out.println(&quot;Thread id: &quot; + Thread.currentThread().getId() + &quot;, lock2 is held&quot;); } else { System.out.println(&quot;Thread id: &quot; + Thread.currentThread().getId() + &quot;, lock2 is _not_ held&quot;); } try { lock2.wait(); } catch (Exception e) { //System.out.println(&quot;Exception (debug:1): &quot; + e.getMessage()); } } } // end of if else if } // end of keyPressed byte getNextByteFromJTextArea() { String s = &quot;&quot;; Id_getNextByteFromJTextArea = Thread.currentThread().getId(); synchronized (lock1) { //if (Thread.holdsLock(lock1) == true) { System.out.println(&quot;Thread id: &quot; + Thread.currentThread().getId() + &quot;, lock1 is held&quot;); } else { System.out.println(&quot;Thread id: &quot; + Thread.currentThread().getId() + &quot;, lock1 is _not_ held&quot;); } if (inputAvailable == false) { try { lock1.wait(); } catch (Exception e) { //System.out.println(&quot;Excpetion (debug:2): &quot; + e.getMessage()); //System.exit(1); } // end of try catch } // end of if inputAvailable if (newLineSent == true) { // send endOfInput now, all input has been prcocessed, anyone // waiting on lock2 should be woken up and some variables // should be re-initialized newLineSent = false; b = null; len = -1; indexIntoByteArray = -1; inputAvailable = false; initialCaretPosition = jta.getDocument().getLength(); endOfInputCaretPosition = jta.getDocument().getLength(); synchronized (lock2) { //if (Thread.holdsLock(lock2) == true) { // System.out.println(&quot;lock2 is held..2..Thread id = &quot; + Thread.currentThread().getId()); //} else { // System.out.println(&quot;lock2 is ___not___ held..2..Thread id = &quot; + Thread.currentThread().getId()); //} lock2.notifyAll(); return endOfInput; } } // end of if newLineSent if (len == -1) { // read input len = endOfInputCaretPosition - initialCaretPosition; try { s = jta.getText(initialCaretPosition, len); b = s.getBytes(); // enter is still getting processed, the text area // hasn't been updated with the enter, so send a // newline once all bytes have been sent. } catch (Exception e) { //System.out.println(&quot;Exception (debug:3): &quot; + e.getMessage()); if (b != null) { Arrays.fill(b, (byte) (-1)); } } // end of try catch } // end of if len == -1 // if control reaches here then it means that we have to send a byte indexIntoByteArray++; if (indexIntoByteArray == len) { // send newLine as all input have been sent already newLineSent = true; return newLine; } if (b[indexIntoByteArray] == newLine) { newLineSent = true; } return b[indexIntoByteArray]; } // end of synchronized block } // end of getNextByteFromJTextArea void outputToJTextArea(byte b) { Id_outputToJTextArea = Thread.currentThread().getId(); synchronized (lock1) { char ch = (char) (b); String text = Character.toString(ch); jta.append(text); jta.setCaretPosition(jta.getDocument().getLength()); initialCaretPosition = jta.getCaretPosition(); enterAlreadyPressedEarlier = false; } } // end of outputToJTextArea void configureJTextAreaForInputOutput() { jta.addKeyListener(this); // remove all mouse listeners for (MouseListener listener : jta.getMouseListeners()) { //outputToJTextArea(jta, &quot;\nRemoving mouse listener\n&quot;); jta.removeMouseListener(listener); } // remove all mouse motion listeners for (MouseMotionListener listener : jta.getMouseMotionListeners()) { //outputToJTextArea(jta, &quot;\nRemoving mouse motion listener\n&quot;); jta.removeMouseMotionListener(listener); } // remove all mouse wheel listeners for (MouseWheelListener listener : jta.getMouseWheelListeners()) { //outputToJTextArea(jta, &quot;\nRemoving mouse wheel listener\n&quot;); jta.removeMouseWheelListener(listener); } System.setIn(new InputStream() { @Override public int read() { // we need to sleep here because of some threading issues //try { // Thread.sleep(1); //} catch (Exception e) { //System.out.println(&quot;Exception (debug:4): &quot; + e.getMessage()); //} byte b = getNextByteFromJTextArea(); return ((int) (b)); } }); System.setOut(new PrintStream(new OutputStream() { @Override public void write(int b) { outputToJTextArea((byte) (b)); } })); System.setErr(new PrintStream(new OutputStream() { @Override public void write(int b) { outputToJTextArea((byte) (b)); } })); } // end of configureJTextAreaForInputOutput void createAndShowConsole() { title = &quot;Console&quot;; jf = InitComponents.setupJFrameAndGet(title, (3 * screenWidth) / 4, (3 * screenHeight) / 4); jta = InitComponents.setupJTextAreaAndGet(&quot;&quot;, 5000, 100, true, true, true, false, 0, 0, 0, 0); configureJTextAreaForInputOutput(); jsp = InitComponents.setupScrollableJTextAreaAndGet(jta, 10, 10, (3 * screenWidth) / 4 - 33, (3 * screenHeight) / 4 - 79); jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jf.add(jsp); //jf.setLocation(screenWidth / 5, screenHeight / 6); jmb = InitComponents.setupJMenuBarAndGet(); jm = InitComponents.setupJMenuAndGet(&quot;Copy All to Clipboard&quot;); jm.setBorder(BorderFactory.createLineBorder(Color.green, 2)); jmi = InitComponents.setupJMenuItemAndGet(&quot;Copy All to Clipboard&quot;); jm.add(jmi); jmb.add(jm); jmi.addActionListener(this); jf.setJMenuBar(jmb); jf.setLocationRelativeTo(null); jf.setVisible(true); } // end of createAndShowConsole } // end of Console class InitComponents { public static JFrame setupJFrameAndGet(String title, int width, int height) { JFrame tmpJF = new JFrame(title); tmpJF.setSize(width, height); tmpJF.setLocationRelativeTo(null); tmpJF.setLayout(null); tmpJF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); return tmpJF; } // end of setupJFrameAndGet public static JTextArea setupJTextAreaAndGet(String text, int rows, int columns, boolean setEditableFlag, boolean setLineWrapFlag, boolean setWrapStyleWordFlag, boolean setBoundsFlag, int xpos, int ypos, int width, int height) { JTextArea tmpJTA = new JTextArea(text, rows, columns); tmpJTA.setEditable(setEditableFlag); tmpJTA.setLineWrap(setLineWrapFlag); tmpJTA.setWrapStyleWord(setWrapStyleWordFlag); if (setBoundsFlag == true) { tmpJTA.setBounds(xpos, ypos, width, height); } return tmpJTA; } // end of setupJTextAreaAndGet public static JScrollPane setupScrollableJTextAreaAndGet(JTextArea jta, int xpos, int ypos, int width, int height) { JScrollPane tmpJSP = new JScrollPane(jta); tmpJSP.setBounds(xpos, ypos, width, height); return tmpJSP; } // end of setupScrollableJTextAreaAndGet public static JMenuBar setupJMenuBarAndGet() { JMenuBar tmpJMB = new JMenuBar(); return tmpJMB; } // end of setupJMenuBarAndGet public static JMenu setupJMenuAndGet(String text) { JMenu tmpJM = new JMenu(text); return tmpJM; } // end of setupJMenuAndGet public static JMenuItem setupJMenuItemAndGet(String text) { JMenuItem tmpJMI = new JMenuItem(text); return tmpJMI; } // end of setupJMenuItemAndGet }// end of InitComponents </code></pre> <hr /> <h2>Results</h2> <pre class="lang-none prettyprint-override"><code> == Summary (Text Len: 14013, Pattern Len: 4, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;0.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;44.0%&quot; of times. Choudhary algorithm is fastest &quot;56.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 8, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;92.0%&quot; of times. Boyer Moore algorithm is fastest &quot;0.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;8.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 16, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;0.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;100.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 32, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;0.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;100.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 36, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;4.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;96.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 40, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;4.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;96.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 48, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;4.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;96.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 56, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;16.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;84.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 64, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;0.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;100.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 128, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;4.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;96.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 256, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;0.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;100.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 512, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;0.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;100.0%&quot; of times. ==== End of Summary ==== == Summary (Text Len: 14013, Pattern Len: 1024, Total number of runs per pattern: 25) == Brute Force algorithm is fastest &quot;0.0%&quot; of times. Boyer Moore algorithm is fastest &quot;0.0%&quot; of times. Rabin Karp algorithm is fastest &quot;0.0%&quot; of times. KnuthMorrisPratt algorithm is fastest &quot;0.0%&quot; of times. Choudhary algorithm is fastest &quot;100.0%&quot; of times. ==== End of Summary ==== </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:41:43.787", "Id": "534393", "Score": "5", "body": "*\"I have invented the fastest string search algorithm\"* - My gut feeling: If that were true, I wouldn't hear about it on codereview :-P. Some explanation in addition to the code would be helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:08:32.493", "Id": "534400", "Score": "2", "body": "How did you test/profile your code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T06:23:07.720", "Id": "534498", "Score": "0", "body": "@Mast, The test code is in the program itself. Please see the main() method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T06:24:26.270", "Id": "534499", "Score": "0", "body": "@Kelly, Writing a paper and then giving it out for peer review is a lot of work. So, I didn't do that. I just put the code here for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:44:06.213", "Id": "534527", "Score": "0", "body": "If those are the only tests, I'd definitely agree with Ralf's suggestion refactoring the program in such a way that it's easier to load external data and profile with external tools. I wouldn't trust the current results too much without it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T15:21:45.047", "Id": "534548", "Score": "0", "body": "@Mast, When I get time, I will do something like this - read text from a file (one text per line and length of that text can be in KBs, and file size can be in MBs) and then pick a pattern from that text and then run all algorithms on it and print the results. So, one can test with many different texts. Please let me know if you have some other ideas." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T17:07:07.247", "Id": "534575", "Score": "0", "body": "@Amit I didn't ask for a peer-reviewed paper." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T02:32:55.107", "Id": "534605", "Score": "0", "body": "Given that the first sentence is prima facie ludicrous, this is unserious and I'm not wasting my time with it. I will happily eat my words when you return with a peer-reviewed paper published in a reputable journal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T05:49:15.557", "Id": "534612", "Score": "0", "body": "@Eric, I believe that my algorithm is the fastest. But, I also know that its hard to convince others. May be no one will buy my claim but I am not bothered." } ]
[ { "body": "<p>Maybe your algorithm is really fast, but this site isn't about algorithm review, it's about code review.</p>\n<p>And a &quot;fastest string search algorithm&quot; should come in a software package of an equally high quality, which it doesn't. The current code quality is far below acceptability for any &quot;production level&quot; usage.</p>\n<ul>\n<li>A string search algorithm should be in a ready-to-use library form.</li>\n<li>It should come in a class with one public method like <code>int search(CharSequence text, CharSequence pattern)</code>.</li>\n<li>Requiring <code>char[]</code> instead of <code>CharSequence</code> makes usage clumsier, and slower in most use cases, as the caller first has to convert any <code>String</code> to <code>char[]</code>.</li>\n<li>A string search class should not contain multiple competing algorithms. If you have multiple algorithms, each should come in its own class, with a common interface that they all implement.</li>\n<li>You should add Javadoc for public classes and methods.</li>\n<li>Code should go into a package like e.g. <code>com.stackexchange.codereview.amit.stringsearch</code>.</li>\n<li>Code for performance comparison doesn't belong into your string search class, but into a separate testing class.</li>\n<li>Performance comparison based on a single test text is useless. Anyway, Java performance testing is a tricky thing, and it's very easy to get wrong results.</li>\n<li>If you do performance comparisons, make sure to include Java's own <code>String.indexOf()</code> method as a performance reference.</li>\n<li>The Swing user interface has nothing to do with the search algorithm. It's useless to any potential string-search user.</li>\n<li>Your naming doesn't follow the established Java Naming conventions (e.g. <code>skip_table</code> should be <code>skipTable</code>).</li>\n<li>A variable named <code>pi_44</code>, with its value being the pattern length minus one, is a no-go. It has nothing to do with the mathematical number PI, nor the number 44.</li>\n<li>You should avoid wildcard imports like <code>import java.util.*;</code>, as they are a quality risk.</li>\n<li>Test cases like your long <code>text</code> variable don't belong into a worker class, but should be separated. There are lots of unit testing frameworks available in Java. Use one of them for that purpose.</li>\n<li>You should make sure the algorithm is not only fast, but also correct, by creating lots of test cases, and comparing your results with a trusted reference (e.g. <code>String.indexOf()</code>). Be sure to include corner cases like empty pattern, empty text, matching and non-matching patterns, non-ASCII characters and so on.</li>\n</ul>\n<p>If you're sure that your algorithm is as good as promised, you should invest the time to bring the code quality up to an adequate level. And I'll be happy to review the improved version here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:49:03.820", "Id": "534572", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/131984/discussion-on-answer-by-ralf-kleberhoff-fastest-string-search-algorithm-invented)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:08:28.547", "Id": "270591", "ParentId": "270565", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:32:13.293", "Id": "270565", "Score": "-2", "Tags": [ "java", "strings", "search" ], "Title": "Fastest string search algorithm invented by me. It is called \"\"Choudhary String Search Algorithm\"\"" }
270565
<p>I was doing the Magic Ball 8 project (its task is to read a user's question and output a prediction) on Python and wrote the following code:</p> <pre><code>from random import choice from time import sleep list_of_predictions = [ &quot;Undoubtedly&quot;, &quot;It seems to me - yes&quot;, &quot;It is not clear yet, try again&quot;, &quot;Do not even think&quot;, &quot;A foregone conclusion&quot;, &quot;Most likely&quot;, &quot;Ask later&quot;, &quot;My answer is no&quot;, &quot;No doubt&quot;, &quot;Good prospects&quot;, &quot;Better not to tell&quot;, &quot;According to my information - no&quot;, &quot;You can be sure of this&quot;, &quot;Yes&quot;, &quot;Concentrate and ask again&quot;, &quot;Very doubtful&quot; ] print('I am a magic ball, and I know the answer to any of your questions.') sleep(1) n = input(&quot;What is your name?\n&quot;) print(f'Greetings, {n}.') sleep(1) def is_question(question): return q[-1] == '?' def is_valid_question(question): return ('When' or 'How' or 'Where') not in q again = 'yes' while again == 'yes': print('Enter a question, it must end with a question mark.') q = input() if is_question(q) and is_valid_question(q): sleep(2) print(choice(list_of_predictions)) elif not is_question(q): print('You entered not a question!') continue else: print('You have entered a question that cannot be answered &quot;yes&quot; or &quot;no&quot;!') continue sleep(1) again = input('Are there any other questions?\n') sleep(1) a = input('Come back if they arise!\n') </code></pre> <p>The main feature of my program is that it checks if the user has entered a question, which can be answered &quot;yes&quot; or &quot;no&quot;. It also works with small delays in time (for realism). What do you think about my project implementation?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:57:38.307", "Id": "534378", "Score": "0", "body": "You probably want to reject \"Why?\" and \"Who?\" questions as well..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:58:55.127", "Id": "534379", "Score": "0", "body": "Yes, need to take this into account" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:00:07.657", "Id": "534437", "Score": "4", "body": "@TobySpeight - \"Is the Who the greatest rock band of all time?\" And now we see the difficulty of natural language processing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T20:06:46.647", "Id": "534450", "Score": "0", "body": "@ribs2spare - did you miss the `not` in that condition?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T20:09:56.470", "Id": "534451", "Score": "0", "body": "Sure did! Deleted it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T22:21:01.033", "Id": "534469", "Score": "2", "body": "Forgive me if I am missing some quirk of python, but don't the `is_question` and `is_valid_question` functions completely ignore their inputs as currently implemented?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T23:36:03.473", "Id": "534477", "Score": "0", "body": "@LOTGP You are completely correct. Also, `('When' or 'How' or 'Where') not in q` will only test `'When' not in q`, since `('When' or 'How' or 'Where')` will evaluate to simply `'When'` ... the first truthy value. A proper way of writing what was intended would be `return all(term not in question for term in ('When', 'How', 'Where'))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T07:27:13.173", "Id": "534506", "Score": "0", "body": "Thanks for the clarification, debugged." } ]
[ { "body": "<p>What I see bad in your code is <strong>readability</strong>. It is good if you keep the proper spacing between each component.</p>\n<p>If you have a long list, dict or tuple break it into lines.</p>\n<pre><code>list_of_predictions = [\n &quot;Undoubtedly&quot;,\n &quot;It seems to me - yes&quot;,\n &quot;It is not clear yet, try again&quot;,\n &quot;Do not even think&quot;,\n &quot;A foregone conclusion&quot;,\n &quot;Most likely&quot;,\n &quot;Ask later&quot;,\n &quot;My answer is no&quot;,\n &quot;No doubt&quot;, \n &quot;Good prospects&quot;,\n &quot;Better not to tell&quot;,\n &quot;According to my information - no&quot;,\n &quot;You can be sure of this&quot;,\n &quot;Yes&quot;,\n &quot;Concentrate and ask again&quot;,\n &quot;Very doubtful&quot;\n]\n</code></pre>\n<p>or you can load the data from an external file if it is a very long one.</p>\n<p>And your code needs spacings,</p>\n<pre><code>from random import choice\nfrom time import sleep\n\nlist_of_predictions = [ ... ]\n\nprint('I am a magic ball, and I know the answer to any of your questions.')\nsleep(1)\n\nn = input(&quot;What is your name?\\n&quot;)\nprint(f'Greetings, {n}.')\nsleep(1)\n\ndef is_question(question):\n return q[-1] == '?'\n\ndef is_valid_question(question):\n return ('When' or 'How' or 'Where') not in q\n\nagain = 'yes'\n\nwhile again == 'yes':\n print('Enter a question, it must end with a question mark.')\n q = input()\n\n if is_question(q) and is_valid_question(q):\n sleep(2)\n print(choice(list_of_predictions))\n elif not is_question(q):\n print('You entered not a question!')\n continue\n else:\n print('You have entered a question that cannot be answered &quot;yes&quot; or &quot;no&quot;!')\n continue\n\n sleep(1)\n again = input('Are there any other questions?\\n')\n sleep(1)\n\na = input('Come back if they arise!\\n')\n</code></pre>\n<p>I think you can see the difference. Btw those are personal preferences it will be better if you read the <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">Zen of python</a> and <a href=\"https://www.python.org/dev/peps/pep-0008\" rel=\"nofollow noreferrer\">PEP8</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T08:40:33.337", "Id": "534382", "Score": "0", "body": "Thanks for help! I will take into account your advices." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T08:43:33.420", "Id": "534383", "Score": "1", "body": "Although The Zen of Python is written in a slightly humorous style, I will take it more seriously." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:21:18.663", "Id": "534389", "Score": "1", "body": "More than the Zen of Python, I recommend reading [PEP8](https://www.python.org/dev/peps/pep-0008), which explicitly give guidelines for the use of blank lines, among many other things." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T08:37:54.803", "Id": "270569", "ParentId": "270566", "Score": "5" } }, { "body": "<p>I'd like to address how you handle the yes/no question controlling the loop.</p>\n<p>The relevant sections of your code are:</p>\n<pre class=\"lang-py prettyprint-override\"><code>again = 'yes'\n\nwhile again == 'yes':\n # [...]\n again = input('Are there any other questions?\\n')\n # [...]\n</code></pre>\n<p>Almost all user input are interpreted as &quot;no&quot;. However, the user has no information that they are supposed to enter the exact string <code>yes</code> for a positive answer. It is common for command line programs to accept <code>y</code> or <code>n</code> as an input, but neither of these will be treated as a positive answer in your code. Same for <code>Yes</code>, <code>YES</code> (different capitalization), <code> yes</code>, <code>yes </code> (leading/trailing white space), <code>yeah</code>, <code>yep</code> (different words), while all of these answer are clearly positives.</p>\n<p>Similarly, inputs that are neither positive nor negative will be interpreted as negative, while the issue may be a typo or a misunderstanding of the answer expected. In this case, the input should be discarded, extra information given to the user on why, and the question asked again.</p>\n<p>This makes handling this input much more complex, but as asking yes/no questions is very common in CLI programs, if you write a function that handles this, you only need to write it once and you are then free to reuse it many more times in the future.</p>\n<p>My take on it is:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_yes_no_input(prompt):\n POSITIVE_VALUES = ['yes',\n 'y',\n 'yeah',\n 'yep',\n 'true',\n '1']\n NEGATIVE_VALUES = ['no',\n 'n',\n 'nope',\n 'false',\n '0']\n while True:\n print(prompt)\n val = input('&gt; ').strip().lower()\n if val in POSITIVE_VALUES:\n return True\n if val in NEGATIVE_VALUES:\n return False\n print('Invalid answer. Please answer yes or no.')\n</code></pre>\n<p>Some comments on my code:</p>\n<ul>\n<li>since the function is meant to be reusable, it takes the question text as an argument (<code>prompt</code>)</li>\n<li>it returns a boolean value, as it can be handled differently according to the use case, and they are easier to work with than strings</li>\n<li>it uses constant lists for positive and negative answer, from which you can easily add or remove values</li>\n<li>the input is <code>strip</code>ped to handle potential leading/trailing white space</li>\n<li>the input is <code>lower</code>ed to handle capitalization issues</li>\n<li>if the input is neither positive or negative, it is rejected and information about the expected answer is given</li>\n</ul>\n<p>Use in your code would be something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>again = True\n\nwhile again:\n # [...]\n again = get_yes_no_input('Are there any other questions?')\n # [...]\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:15:06.430", "Id": "534388", "Score": "0", "body": "Or more advanced way NLP can be used if you want more, happy coding ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:36:49.353", "Id": "534411", "Score": "0", "body": "Thank you for the recomendations!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:41:04.370", "Id": "534413", "Score": "0", "body": "Why did You capitalize lists of positive and negative values? I want the program to match the PEP-8, are list names allowed to be formatted like that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:56:49.110", "Id": "534414", "Score": "0", "body": "@vlados155 All caps are used for constants. Although PEP8 recommends this for module-level constants, there is no recommendations for method- or class-level constants, so I did what I thought was best. You are free to disagree with me and use another naming convention in this case, just be consistent throughout your own code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T14:04:15.900", "Id": "534415", "Score": "0", "body": "Thank You for the clarification." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:01:15.107", "Id": "270573", "ParentId": "270566", "Score": "5" } } ]
{ "AcceptedAnswerId": "270573", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:40:35.363", "Id": "270566", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Magic ball 8 program" }
270566
<p>I am learning Python and for practice I have written this function which sorts a list.</p> <p>Can you please provide feedback on how I have structured it and what better ways could be there to write it for optimization/structuring?</p> <pre><code>originallist=[5, 4, 0, 3, 2,1] lowervalue=int() duplicatelist=originallist[:] ## This list is used to compare each element of the list with the first index of original list sortedlist=[] ## Sorted list while len(originallist)&gt;0: # See if there are any elements left in list original list lowervalue=0.01 for i in duplicatelist: if originallist[0]&lt;=i: temp=originallist[0] print('Temp: ', temp) elif originallist[0]&gt;i: temp=i print('Temp: ', temp) if lowervalue&gt;temp or lowervalue==0.01: lowervalue=temp print('LowerValue: ', lowervalue) sortedlist.append(lowervalue) print('Sorted List: ', sortedlist) duplicatelist.remove(lowervalue) print('Duplicate List: ', duplicatelist) originallist.remove(lowervalue) print('original List: ', originallist, ' \n') print(f'Sorted List :' , sortedlist) </code></pre> <p>Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:22:15.813", "Id": "534443", "Score": "0", "body": "You've implemented an insertion sort (I think), which is inherently not really an optimal way to sort things. Do you want answers within the context of implementing insertion sorting in python or optimal sorting of a list in general? (i.e. `originallist.sort()`) :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:33:02.610", "Id": "534447", "Score": "0", "body": "Thank you for the feedback @JeffUk! It would be great if you could share insights on optimal sorting of list in general. list.sort(). And also any feedback to improve the thinking pattern to develop the algorithms based on the above code e.g. if I should be changing the mindset to approach a problem etc" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:36:25.147", "Id": "534448", "Score": "0", "body": "@JeffUK It's selection sort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:46:59.923", "Id": "534449", "Score": "0", "body": "@KellyBundy I was just about to change my comment after doing some research. Should have taken Compsci instead of IT.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T22:17:20.147", "Id": "534467", "Score": "1", "body": "I have added the [tag:reinventing-the-wheel] tag as otherwise the answer \"use the [Timsort](https://en.wikipedia.org/wiki/Timsort) built into Python from Python 2.3 by using `list.sort()` or `sorted`\" is 'the best' but possibly not too helpful answer." } ]
[ { "body": "<p>There's some odd features to this code, even for a coding practice exercise. Python of course has <a href=\"https://docs.python.org/3.7/library/functions.html#sorted\" rel=\"nofollow noreferrer\">a couple</a> of <a href=\"https://docs.python.org/3.7/library/stdtypes.html#list.sort\" rel=\"nofollow noreferrer\">list sorting</a> techniques which <strong>you should absolutely use</strong> in normal circumstances.</p>\n<p>So <em>accepting</em> that you are doing this for practice, I wonder what the point of the <code>duplicatelist</code> is? Or indeed <code>temp</code>? Are these development fossils of some earlier process that you have modified? Looping across this list just seems to find the minimum value in the remaining original list anyway, so</p>\n<pre><code>originallist=[5, 4, 8, 2, 3, 6, 0, 1, 7]\n\nsortedlist=[] ## Sorted list \n\nwhile len(originallist)&gt;0: # See if there are any elements left in original list\n\n lowervalue = originallist[0]\n for i in originallist: \n if lowervalue &gt; i:\n lowervalue = i\n print('New LowerValue: ', lowervalue)\n\n sortedlist.append(lowervalue)\n print('Growing Sorted List: ', sortedlist)\n originallist.remove(lowervalue)\n print('Reduced Original List: ', originallist, ' \\n')\n \n\nprint('Sorted List :' , sortedlist)\n</code></pre>\n<p>would apparently do the same.</p>\n<p>Of course there is also a <a href=\"https://docs.python.org/3.7/library/functions.html#min\" rel=\"nofollow noreferrer\">min</a> function that would find <code>lowervalue</code> quickly. This eliminates the inner loop (is this maybe why you didn't use it?):</p>\n<pre><code>originallist = [5, 4, 8, 2, 3, 6, 0, 1, 7]\n\nsortedlist=[] ## Sorted list \n\nwhile len(originallist)&gt;0: # See if there are any elements left in original list\n\n lowervalue = min(originallist)\n print('LowerValue: ', lowervalue)\n\n sortedlist.append(lowervalue)\n print('Growing Sorted List: ', sortedlist)\n originallist.remove(lowervalue)\n print('Reduced Original List: ', originallist, ' \\n')\n \n\nprint('Sorted List :' , sortedlist)\n</code></pre>\n<p>Using <code>remove</code> from a list can be slow - effectively rewriting the remainder of the list. For the purposes you have here, I don't think it makes an appreciable difference and has the slight advantage of being easy to understand.</p>\n<p>One construct you will often see in a reducing list is phrasing the <code>while</code> loop like this:</p>\n<pre><code>while originallist:\n</code></pre>\n<p>... any non-empty list evaluates as <code>True</code> in such a test, so this is the same test as you are making.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T01:42:38.223", "Id": "534486", "Score": "0", "body": "@Syed You have to be careful with magic numbers as sentinel values. If I put `0.01` into your original list, it doesn't get sorted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T09:15:58.907", "Id": "534510", "Score": "0", "body": "Thank you soo much Joffan!\n\nYour code makes a lot more sense. It is just that I was viewing the problem from very different perspective (given I have started with python recently with no back experience in algorithms and coding). The initial thought was to compare the originallist elements with itself and to visualize it better I went ahead with duplicating the list and comparing the elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T09:16:05.617", "Id": "534511", "Score": "0", "body": "The thought process behind the variable **temp** was there to store the smaller value when ever it compared 2 elements (the one from original list being compared to the one from duplicate). And then compare it with **lowervalue** to see if it is smaller among the list till that point in the iteration. But I can see your method is much simpler and efficient. I just could not see it that way while coding. \n\nI did not use the min function intentionally as I was trying to write code without python helping with the built in functions for practice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T09:17:29.217", "Id": "534512", "Score": "0", "body": "Yes Teepeemm! I was struggling with what value to initialize for **lowervalue** but now i see we should do it with the first value of originallist as in the above code!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T00:31:28.110", "Id": "270602", "ParentId": "270567", "Score": "3" } } ]
{ "AcceptedAnswerId": "270602", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T07:47:50.107", "Id": "270567", "Score": "0", "Tags": [ "python", "beginner", "python-3.x", "sorting", "reinventing-the-wheel" ], "Title": "Simple sort function" }
270567
<p>I have a methods like.</p> <pre><code> public function getReceiptGames(Request $request):JsonResponse{ $result = []; $page = $request-&gt;get('page') ? (int)$request-&gt;get('page') : null; if ($page) { $pagination = $this-&gt;receiptGameRepository-&gt;paginateAll($page); $games = $pagination-&gt;items(); $this-&gt;responseFactory-&gt;withPagination($pagination); } else { $games = $this-&gt;receiptGameRepository-&gt;findAllReceiptGames(); } /** @var ReceiptGame $game */ foreach ($games as $game) { $result[] = $this-&gt;receiptGameFormatter-&gt;format($game); } return $this-&gt;responseFactory -&gt;withPayload(['receiptGames' =&gt; $result]) -&gt;create(); </code></pre> <p>}</p> <p>What possible solutions do you see? What are the solutions with and without inheritance?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:05:30.490", "Id": "534398", "Score": "2", "body": "Sorry, but with only one method, we can't help you. If all the methods are just like this, letter by letter, you can remove all the methods and keep this one; but probably they have some parts changed, and the answer is possible only knowing what parts." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T08:12:13.987", "Id": "270568", "Score": "-2", "Tags": [ "repository", "pagination", "doctrine" ], "Title": "How to remove boilderplate code from the methods" }
270568
<p>I believe that using <code>TryParse</code> is not a great idea here. How to improve this part?</p> <pre><code>using (CustomerDataReader reader = customCommand.ExecuteReader()) { while (reader.Read()) { var person = new Organization { Name = reader[&quot;Name&quot;].ToString(), Country = reader[&quot;Country&quot;].ToString() // much more string here }; Int32.TryParse(reader[&quot;Number1&quot;].ToString(), out person.Number1); DateTime.TryParse(reader[&quot;CreationDate&quot;].ToString(), out person.CreationDate); Double.TryParse(reader[&quot;Income&quot;].ToString(), out person.Income); // a lot more int, datetime and double follow here } } </code></pre> <p>FYI, <code>CustomDataReader</code> is some custom class for connection to some custom storage.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:24:52.860", "Id": "534390", "Score": "1", "body": "`So I believe that using TryParse is not a great idea here` believing and reasoning are two different things. Tell us why you don't need the `TryParse` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:32:02.237", "Id": "534391", "Score": "0", "body": "Not TryParse in general but how it is used here. For instance, we do not cover cases and codes doesn't know what happens if TryParse is false...? Not sure, for this reason I am asking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:38:19.243", "Id": "534392", "Score": "1", "body": "For the current code, it's just parsing values (mapping or modeling). So, business logic should not be involved. If you want a better way to overcome this, use an `ORM` like `Dapper` to handle this, and you just focus on the actual business code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:19:08.200", "Id": "534404", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T15:26:18.507", "Id": "534424", "Score": "0", "body": "\"How to get rid of TryParse in this code?\" - I would say fix the data model ? It does not seem like the fields in the DB are using proper types." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T08:41:24.953", "Id": "270570", "Score": "-2", "Tags": [ "c#" ], "Title": "How to get rid of TryParse in this code?" }
270570
<p>Contextually, I'm evaluating if a member exists with the supplied information. This, ostensibly, is intended to prevent the addition of new members with the same details.</p> <p>The user will be provided with a list of members having the same details as the new member they're trying to add.</p> <p>I set this up so that if a member exists, the method throws an exception into which, I've built the details for the existing members having the same details as those provided. If no member exists with the given details, the method returns a success code instead.</p> <p>The addition of existing members in the error response allows me to display the existing member details on the page where the user can manipulate or use an existing member record rather than creating a new one which would be duplicating the existing member record.</p> <p>I have doubts as to whether not relying on exception handling is a sensible way to do this or even if there's a better way to do this altogether.</p> <p>Is there any objective reason (performance, readability, etc.) why relying on exception handling like this wouldn't be the ideal way to do this?</p> <pre><code>public IActionResult OnGetCheckMemberAsync(Member member) { // If a member exists with the specified name or email address, throw an error returning all matching members. try { var members = from m in context.Members where m.Email == Member.Email || m.IdNumber == Member.IdNumber select m; if (members.Any()) { throw new MemberExistsException(&quot;Unable to add member: member(s) with provided details already exists.&quot;, members); } return new OkResult(); } catch (MemberExistsException ex) { var result = new JsonResult(new { Exception = ex, Members = ex.ExistingMembers }); return BadRequest(result); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:17:04.927", "Id": "534401", "Score": "2", "body": "Generic best practices are outside the scope of this site. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T13:17:15.980", "Id": "534402", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T17:54:36.077", "Id": "534435", "Score": "1", "body": "here is a good start : https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/exception-throwing?redirectedfrom=MSDN" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T09:24:11.820", "Id": "270571", "Score": "-2", "Tags": [ "c#", "error-handling", "asp.net-core" ], "Title": "Is relying on exception handling a good way to ensure that the app's work is done correctly?" }
270571
<p>I have the following vue component which all works fine</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-html lang-html prettyprint-override"><code>&lt;template&gt; &lt;div class="sales-agreements"&gt; &lt;nav class="sales-agreements__navigation"&gt; &lt;ul class="sales-agreements__navigation-list"&gt; &lt;li class="sales-agreements__navigation-item"&gt; &lt;router-link :to="{ path: '/' }" class="sales-agreements__navigation-link"&gt;All&lt;/router-link&gt; &lt;/li&gt; &lt;li class="sales-agreements__navigation-item"&gt; &lt;router-link :to="{ path: '/', query: { salesType: 'mortars' } }" class="sales-agreements__navigation-link"&gt;Mortars&lt;/router-link&gt; &lt;/li&gt; &lt;li class="sales-agreements__navigation-item"&gt; &lt;router-link :to="{ path: '/', query: { salesType: 'bricks' } }" class="sales-agreements__navigation-link"&gt;Bricks&lt;/router-link&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;div class="sales-agreements__header"&gt; &lt;div class="sales-agreements__header-box sales-agreements__header-box--welcome"&gt; Welcome &lt;/div&gt; &lt;h1 class="sales-agreements__header-box sales-agreements__header-box--title"&gt; {{ title }} &lt;/h1&gt; &lt;/div&gt; &lt;div class="sales-agreements__results"&gt; &lt;h2 class="sales-agreements__results-title"&gt;{{ subTitle }} sales agreements&lt;/h2&gt; &lt;div v-if="salesAgreementItems.length"&gt; &lt;div v-for="salesAgreementItem in filteredSalesAgreementItems" :key="salesAgreementItem.id" class="sales-agreements__item"&gt; &lt;div class="sales-agreements__item-details"&gt; &lt;div class="sales-agreements__item-id"&gt;&lt;strong&gt;{{ salesAgreementItem.id }}&lt;/strong&gt;&lt;/div&gt; &lt;div class="sales-agreements__item-icon-holder"&gt; &lt;bricks-icon v-if="salesAgreementItem.department === 'bricks'" :icon-class="'sales-agreements__item-icon'"&gt;&lt;/bricks-icon&gt; &lt;mortars-icon v-if="salesAgreementItem.department === 'mortars'" :icon-class="'sales-agreements__item-icon'"&gt;&lt;/mortars-icon&gt; &lt;/div&gt; &lt;div class="sales-agreements__item-address"&gt; &lt;span v-if="salesAgreementItem.deliveryStreet"&gt;{{ salesAgreementItem.deliveryStreet }}&lt;br&gt;&lt;/span&gt; &lt;span v-if="salesAgreementItem.deliveryCity"&gt;{{ salesAgreementItem.deliveryCity }}&lt;br&gt;&lt;/span&gt; &lt;span v-if="salesAgreementItem.deliveryPostcode"&gt;{{ salesAgreementItem.deliveryPostcode }}&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div v-else&gt; &lt;p&gt;&lt;strong&gt;Sorry, there are currently no sales agreements to view.&lt;/strong&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import BricksIcon from '../icons/bricks-icon.vue'; import MortarsIcon from '../icons/mortars-icon.vue'; import './sales-agreements.scss'; export default { name: 'SalesAgreements', components: { BricksIcon, MortarsIcon, }, props: { salesAgreementItems: { default() { return []; }, type: Array, }, }, computed: { filteredSalesAgreementItems() { switch (this.$route.query.salesType) { case 'bricks': return this.salesAgreementItems.filter(obj =&gt; obj.department === 'bricks'); case 'mortars': return this.salesAgreementItems.filter(obj =&gt; obj.department === 'mortars'); default: return this.salesAgreementItems; } }, subTitle() { switch (this.$route.query.salesType) { case 'bricks': return 'Bricks'; case 'mortars': return 'Mortars'; default: return 'All'; } }, title() { switch (this.$route.query.salesType) { case 'bricks': return 'Bricks'; case 'mortars': return 'Mortars'; default: return 'Bricks &amp; Mortars'; } }, }, }; &lt;/script&gt;</code></pre> </div> </div> </p> <p>But as you can see, the computed properties repeats the same <code>switch</code> - is there a way to change all three properties in one switch statement so if I add further properties or switch cases, I do not have to do it multiple times?</p>
[]
[ { "body": "<p>Computed properties can return objects, which seems useful for you.</p>\n<pre><code>computed: {\n filteredItems() {\n switch (this.$route.query.salesType) {\n case 'bricks':\n return {\n filteredSalesAgreementItems: this.salesAgreementItems.filter(obj =&gt; obj.department === 'bricks'),\n subTitle: 'Bricks',\n title: 'Bricks'\n }\n case 'mortars':\n return {\n filteredSalesAgreementItems: this.salesAgreementItems.filter(obj =&gt; obj.department === 'mortars'),\n subTitle: 'Mortars',\n title: 'Mortars'\n }\n default:\n return {\n filteredSalesAgreementItems: this.salesAgreementItems,\n subTitle: 'All',\n title: 'Bricks &amp; Mortars'\n }\n }\n },\n</code></pre>\n<p>You can then refer to the values using <code>filteredItems.filteredSalesAgreementItems</code>, <code>filteredItems.subTitle</code> and <code>filteredItems.title</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T15:55:52.663", "Id": "534426", "Score": "0", "body": "Can't believe I didn't think of returning an object! Much better than using the `@click` Thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T15:28:11.363", "Id": "270582", "ParentId": "270575", "Score": "2" } }, { "body": "<p>One option is to ensure that the sales type is in (or not in) a white list of types using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\"><code>Array.prototype.includes()</code></a> - for example:</p>\n<pre><code>filteredSalesAgreementItems() {\n if (!['bricks', 'mortars'].includes(this.$route.query.salesType)) {\n return this.salesAgreementItems;\n }\n return this.salesAgreementItems.filter(obj =&gt; obj.department === this.$route.query.salesType);\n}\nsubTitle() {\n if (!['bricks', 'mortars'].includes(this.$route.query.salesType)) {\n return 'All';\n }\n const type = this.$route.query.salesType;\n return type.charAt(0).toUpperCase() + type.subString(1);\n},\ntitle() {\n if (!['bricks', 'mortars'].includes(this.$route.query.salesType)) {\n return 'Bricks &amp; Mortars';\n }\n const type = this.$route.query.salesType;\n return type.charAt(0).toUpperCase() + type.subString(1);\n},\n</code></pre>\n<p>The last return values of the latter two computed properties could be stored in a method - e.g. <code>toTitleCase()</code>.</p>\n<pre><code>if (!String.prototype.toTitleCase) {\n String.prototype.toTitleCase = function() {\n return this.charAt(0).toUpperCase() + this.subString(1);\n }\n}\n</code></pre>\n<p>So then that can be used to simplify those last two computed properties - e.g.:</p>\n<pre><code>return this.$route.query.salesType.toTitleCase();\n</code></pre>\n<p>And the list of sales types could be declared before the component - e.g.</p>\n<pre><code>const SALES_TYPES = Object.freeze(['bricks', 'mortars']);\n</code></pre>\n<p>Then that list can be referenced within the computed properties.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T16:33:25.753", "Id": "270584", "ParentId": "270575", "Score": "0" } } ]
{ "AcceptedAnswerId": "270582", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T11:46:03.007", "Id": "270575", "Score": "2", "Tags": [ "javascript", "ecmascript-6", "vue.js" ], "Title": "group computed properties in vue component" }
270575
<p>I have a long switch statement and it would be great if someone know how to make it cleaner.</p> <p>Code is available on Github: <a href="https://github.com/Rabbit-Company/Passky-Server/blob/main/php/index.php" rel="nofollow noreferrer">https://github.com/Rabbit-Company/Passky-Server/blob/main/php/index.php</a></p> <p>And for those who don't want to visit Github here is the code:</p> <pre><code> switch($_GET['action']){ case &quot;getInfo&quot;: if(Database::userSentToManyRequests('getInfo')){ echo Display::json(429); return; } echo Database::getInfo(); break; case &quot;getToken&quot;: if(Database::userSentToManyRequests('getToken')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || !isset($_POST['otp'])){ echo Display::json(403); return; } echo Database::getToken($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], $_POST['otp']); break; case &quot;createAccount&quot;: if(Database::userSentToManyRequests('createAccount')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || !isset($_POST['email'])){ echo Display::json(403); return; } echo Database::createAccount($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], $_POST['email']); break; case &quot;getPasswords&quot;: if(Database::userSentToManyRequests('getPasswords')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])){ echo Display::json(403); return; } echo Database::getPasswords($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); break; case &quot;savePassword&quot;: if(Database::userSentToManyRequests('savePassword')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || !isset($_POST['website']) || !isset($_POST['username']) || !isset($_POST['password']) || !isset($_POST['message'])){ echo Display::json(403); return; } echo Database::savePassword($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], $_POST['website'], $_POST['username'], $_POST['password'], $_POST['message']); break; case &quot;importPasswords&quot;: if(Database::userSentToManyRequests('importPasswords')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || file_get_contents('php://input') == null){ echo Display::json(403); return; } echo Database::importPasswords($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], file_get_contents('php://input')); break; case &quot;editPassword&quot;: if(Database::userSentToManyRequests('editPassword')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || !isset($_POST['password_id']) || !isset($_POST['website']) || !isset($_POST['username']) || !isset($_POST['password']) || !isset($_POST['message'])){ echo Display::json(403); return; } echo Database::editPassword($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], $_POST['password_id'], $_POST['website'], $_POST['username'], $_POST['password'], $_POST['message']); break; case &quot;deletePassword&quot;: if(Database::userSentToManyRequests('deletePassword')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || !isset($_POST['password_id'])){ echo Display::json(403); return; } echo Database::deletePassword($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], $_POST['password_id']); break; case &quot;deleteAccount&quot;: if(Database::userSentToManyRequests('deleteAccount')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])){ echo Display::json(403); return; } echo Database::deleteAccount($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); break; case &quot;forgotUsername&quot;: if(Database::userSentToManyRequests('forgotUsername')){ echo Display::json(429); return; } if(!isset($_POST['email'])){ echo Display::json(403); return; } echo Database::forgotUsername($_POST['email']); break; case &quot;enable2fa&quot;: if(Database::userSentToManyRequests('enable2fa')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])){ echo Display::json(403); return; } echo Database::enable2Fa($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); break; case &quot;disable2fa&quot;: if(Database::userSentToManyRequests('disable2fa')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])){ echo Display::json(403); return; } echo Database::disable2Fa($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); break; case &quot;addYubiKey&quot;: if(Database::userSentToManyRequests('addYubiKey')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || !isset($_POST['id'])){ echo Display::json(403); return; } echo Database::addYubiKey($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], $_POST['id']); break; case &quot;removeYubiKey&quot;: if(Database::userSentToManyRequests('removeYubiKey')){ echo Display::json(429); return; } if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || !isset($_POST['id'])){ echo Display::json(403); return; } echo Database::removeYubiKey($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'], $_POST['id']); break; default: echo Display::json(401); break; } </code></pre> <p>As you can see in every switch statement function userSentToManyRequests appear in every case in a switch with the same error code, but different parameter. This is easy fixable with another function. But how would I shorten the rest (Check if all parameters in POST was supplied for each action and to provide them in the right function)</p>
[]
[ { "body": "<p>I'm quite surprised that you placed the <code>userSentToManyRequests()</code> function in every case. If you do that then you can just start with it before the <code>switch ()</code>.</p>\n<p>To get rid of the <code>switch</code> you can use an array containing the names of the arguments for each action function. I've done it for the first four cases, but it is easy to do them all:</p>\n<pre><code>$argumentNames = ['getInfo' =&gt; [],\n 'getToken' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW', 'otp'],\n 'createAccount' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW', 'email'],\n 'getPasswords' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW']];\n\n$action = $_GET['action'] ?? 'No action given';\n$errorNo = 0;\nif (!in_array($action, array_keys($argumentNames))) {\n $errorNo = 401; // action does not exist\n} elseif (Database::userSentToManyRequests($action)) {\n $errorNo = 429; // too many requests were sent\n} else {\n $arguments = [];\n foreach ($argumentNames[$action] as $argumentName) {\n if (isset($_GET[$argumentName])) {\n $arguments[] = $_GET[$argumentName];\n } else {\n $errorNo = 403; // action argument does not exist\n break;\n }\n }\n if ($errorNo == 0) call_user_func_array($action, $arguments);\n}\nif ($errorNo &gt; 0) echo Display::json($errorNo);\n</code></pre>\n<p>As you can see there's no more repeated code here. I also only report any errors once.</p>\n<p>The trick here is that you need to know that <a href=\"https://www.php.net/call_user_func_array\" rel=\"nofollow noreferrer\">call_user_func_array()</a> exists.</p>\n<p><strong>Important note:</strong> Code is untested!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T16:37:27.687", "Id": "534430", "Score": "0", "body": "Improved the code slightly. It now also detects correctly when no action is supplied and I corrected the argument of `userSentToManyRequests()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T17:08:40.387", "Id": "534431", "Score": "0", "body": "Thanks, I will test that today or tomorrow." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T14:56:58.887", "Id": "270581", "ParentId": "270578", "Score": "3" } }, { "body": "<p>As Kiko pointed out, there are many repeated blocks to check if the user has sent too many requests for the given action - e.g.</p>\n<blockquote>\n<pre><code>if(Database::userSentToManyRequests('getToken')){\n echo Display::json(429);\n return;\n}\n</code></pre>\n</blockquote>\n<p>This violates the <a href=\"http://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><em><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself</em> principle </a>. That block can be moved out of the <code>switch</code> statement - e.g.</p>\n<pre><code>$action = $_GET['action'];\n//optionally ensure action is within whitelist of allowed actions\nif($action &amp;&amp; Database::userSentToManyRequests($action)){\n echo Display::json(429);\n return;\n}\n</code></pre>\n<p>There are many blocks like this</p>\n<blockquote>\n<pre><code> if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])){\n echo Display::json(403);\n return;\n }\n</code></pre>\n</blockquote>\n<p>And in some cases it also checks if a POST parameter is missing. The check to ensure that the user is authenticated could be abstracted to a separate function - e.g.</p>\n<pre><code>function ensureUserAuthed() {\n if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])){\n echo Display::json(403);\n exit;\n }\n}\n</code></pre>\n<p>And if a POST parameter is missing, it would perhaps be appropriate to return a different response code - e.g. <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400\" rel=\"nofollow noreferrer\">400</a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422\" rel=\"nofollow noreferrer\">422</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T18:01:39.167", "Id": "270587", "ParentId": "270578", "Score": "3" } }, { "body": "<p>Thank you both for helping me out. I have upvoted both of your answers.</p>\n<p>This is what I have made and it works great so far, I would still need to test every API call just to be sure.</p>\n<pre><code>if(empty($_GET['action'])){\n echo Display::json(400);\n return;\n}\n\n$argumentNames = [\n 'getInfo' =&gt; [],\n 'getToken' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW', 'otp'],\n 'createAccount' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW', 'email'],\n 'getPasswords' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW'],\n 'savePassword' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW', 'website', 'username', 'password', 'message'],\n 'importPasswords' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW', 'php://input'],\n 'editPassword' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW', 'password_id', 'website', 'username', 'password', 'message'],\n 'deletePassword' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW', 'password_id'],\n 'deleteAccount' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW'],\n 'forgotUsername' =&gt; ['email'],\n 'enable2fa' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW'],\n 'disable2fa' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW'],\n 'addYubiKey' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW', 'id'],\n 'removeYubiKey' =&gt; ['PHP_AUTH_USER', 'PHP_AUTH_PW', 'id']\n];\n\n$action = $_GET['action'] ?? 'No action given';\n\nif (!in_array($action, array_keys($argumentNames))){\n echo Display::json(401);\n return;\n}\n\nif (Database::userSentToManyRequests($action)) {\n echo Display::json(429);\n return;\n}\n\n$arguments = [];\n$errorNo = 0;\n\nforeach ($argumentNames[$action] as $argumentName) {\n if($argumentName == 'PHP_AUTH_USER' || $argumentName == 'PHP_AUTH_PW'){\n if(isset($_SERVER[$argumentName])){\n $arguments[] = $_SERVER[$argumentName];\n }else{\n $errorNo = 403;\n break;\n }\n }elseif($argumentName == 'php://input'){\n if(file_get_contents('php://input') != null){\n $arguments[] = file_get_contents('php://input');\n }else{\n $errorNo = 403;\n break;\n }\n }else{\n if(isset($_POST[$argumentName])){\n $arguments[] = $_POST[$argumentName];\n }else{\n $errorNo = 403;\n break;\n }\n }\n}\n\nif ($errorNo == 0){\n echo call_user_func_array(__NAMESPACE__ . '\\Database::' . $action, $arguments);\n}else{\n echo Display::json($errorNo);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:31:17.170", "Id": "534446", "Score": "0", "body": "Welcome to Code Review! While OPs are [encouraged to answer their own questions](https://codereview.stackexchange.com/help/self-answer) bear in mind that [\"_Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted._\"](https://codereview.stackexchange.com/help/how-to-answer)... Perhaps asking a follow-up question would be more appropriate. When doing that it is common to include a link to this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T06:51:38.760", "Id": "534504", "Score": "0", "body": "Thanks. So I should delete the answer and mark KOKO Software's answer as accepted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T00:56:19.637", "Id": "534602", "Score": "0", "body": "You could delete the answer or if you changed anything other than what we suggested then you could add a description of those changes, including what improvement that has over the original. [\"Accepting an answer is not mandatory; do not feel compelled to accept the first answer you receive. Wait until you receive an answer that answers your question well.\"](https://codereview.stackexchange.com/help/someone-answers)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T18:44:35.797", "Id": "270588", "ParentId": "270578", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T12:47:52.687", "Id": "270578", "Score": "4", "Tags": [ "php" ], "Title": "Passky Password Manager router with authentication and validation guards" }
270578
<p>This is a command line application which displays the text of an EPUB one sentence at a time.</p> <p>I am going to make it more robust, including:</p> <ul> <li>make the segmentation more accurate, because it currently groups together unrelated text sometimes</li> <li>make it faster, so that the segmentation occurs a first time, then the segments are saved on the filesystem</li> <li>add in more reading capabilities, like a progress meter and the ability to take notes on each sentence</li> </ul> <p>However, for now, I'm really just interested in feedback about optimizing the code I have. Is there any more elegant design pattern?</p> <p>Thanks very much.</p> <pre><code># Note: this code works, but it's slow to start because Spacy's nlp runs for a while before the curses display launches. # This is a Python program which takes the name of an EPUB from the command line, extracts the plaintext content from the EPUB, then segments it with Spacy, then displays each sentence one at a time on-screen. # The controls are &quot;n&quot; for next sentence, &quot;b&quot; for last sentence, and &quot;q&quot; to quit the application. import sys import spacy import epub2txt import curses def main(stdscr): # Get the name of the EPUB textname = sys.argv[1] # Get the plaintext out of the EPUB text = epub2txt.epub2txt(textname) # Segment the text with Spacy. nlp = spacy.load('en_core_web_sm') doc = nlp(text) lines = list(doc.sents) # loop through the sentences with index: i = 0 while i &lt; len(lines): stdscr.clear() stdscr.addstr(str(lines[i])) stdscr.refresh() c = stdscr.getch() if c == ord('q'): break elif c == ord('b'): if i &gt; 0: i -= 1 elif c == ord('n'): if i &lt; len(lines) - 1: i += 1 curses.wrapper(main) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T14:52:40.337", "Id": "270580", "Score": "0", "Tags": [ "python", "curses" ], "Title": "Command-line sentence-by-sentence EPUB reader in Python" }
270580
<p>I'm learning Java in a MOOC right now and this is my solution for exercise grade statistics.</p> <p>This is the exercise:</p> <blockquote> <p>In this exercise we create a program for printing statistics for points in course. The program receives points (integers from zero to one hundred) as input, based on which it prints statistics about grades. Reading of input stops when the user enters the number -1. Numbers that are not within the interval [0-100] should not be taken into account when calculating the statistics.</p> <h1>PART 1 Point averages</h1> <p>Write a program that reads integers representing course point totals from the user. Numbers between [0-100] are acceptable and the number -1 ends the reading of input. Other numbers are erroneous input, which should be ignored. When the user enters the number -1, the program should print the average of the point totals that were input.</p> <h1>PART 2 Point average for points giving a passing grade</h1> <p>Extend the program, such that it in addition to giving the point average of all totals also provides the point average for points giving a passing grade.</p> <p>A passing grade is achieved by getting a minimum of 50 course points. You may assume that the user always provides at least one integer between [0-100]. If there are no numbers giving a passing grade, the program should print a line &quot;-&quot; where the average would be.</p> <h1>PART 3 Pass percentage</h1> <p>Extend the program from the previous part, such that it also print the pass percentage. The pass percentage is calculated using the formula 100 * passing / participants.</p> <h1>PART 4 Grade distribution</h1> <p>Extend the program, such that it also prints the grade distribution.Each point total is converted to a grade based on the above table. If a point total isn't within [0-100], it should be ignored.</p> <p>The grade distribution is printed out as stars. E.g. if there is one point total giving the grade 5, then it should print the row 5: *. If there are no point totals giving a particular grade, then no stars should be printed for it. In the sample below this is true for e.g. the grade 4.</p> </blockquote> <p>This is my solution:</p> <p>Main.java:</p> <pre><code>import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Write your program here -- consider breaking the program into // multiple classes. UserInterface ui = new UserInterface(scanner); ui.start(); } } </code></pre> <p>PointsStatistics.java:</p> <pre><code>import java.util.ArrayList; public class PointsStatistics { private ArrayList&lt;Integer&gt; allpoints; private ArrayList&lt;Integer&gt; passingpoints; public PointsStatistics() { this.allpoints = new ArrayList&lt;&gt;(); this.passingpoints = new ArrayList&lt;&gt;(); } public void add(int points) { if (points &gt; 0 &amp;&amp; points &gt;= 50 &amp;&amp; points &lt;= 100) { this.passingpoints.add(points); } if (points &gt; 0 &amp;&amp; points &lt;= 100) { this.allpoints.add(points); } } public double pointsAverage() { double sum = 0.0; for (Integer points : this.allpoints) { sum += points; } return sum / this.allpoints.size(); } public double possingPointsAverage() { double sum = 0.0; for (Integer points : this.passingpoints) { sum += points; } return sum / this.passingpoints.size(); } public double passingPercentage() { double percentage = (this.passingpoints.size() * 1.0) / this.allpoints.size(); return percentage * 100; } public void gradeDistribution() { ArrayList&lt;Integer&gt; grades = new ArrayList&lt;&gt;(); for (Integer points : this.allpoints) { if (points &lt; 50) { grades.add(0); } else if (points &lt; 60) { grades.add(1); } else if (points &lt; 70) { grades.add(2); } else if (points &lt; 80) { grades.add(3); } else if (points &lt; 90) { grades.add(4); } else if (points &lt;= 100) { grades.add(5); } } for (int i = 5; i &gt;= 0; i--) { System.out.print(i + &quot;: &quot;); for(Integer grade : grades) { if (grade == i) { System.out.print(&quot;*&quot;); } } System.out.println(&quot;&quot;); } } } </code></pre> <p>UserInterface.java</p> <pre><code>import java.util.Scanner; public class UserInterface { private PointsStatistics points; private Scanner scanner; public UserInterface(Scanner scanner) { this.points = new PointsStatistics(); this.scanner = scanner; } public void start() { System.out.println(&quot;Enter point totals, -1 stops: &quot;); while(true) { int enterPoints = Integer.valueOf(scanner.nextLine()); if( enterPoints == -1) { break; } this.points.add(enterPoints); } System.out.println(&quot;Point average (all): &quot; + this.points.pointsAverage()); System.out.println(&quot;Points average (passing): &quot; + this.points.possingPointsAverage()); System.out.println(&quot;Pass percentage: &quot; + this.points.passingPercentage()); points.gradeDistribution(); } } </code></pre> <p>So what do you think? It works, but is it an optimal solution? Thank-you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T17:15:45.977", "Id": "534432", "Score": "2", "body": "I've edited the title of your post. The *Code Review* site requires the title of the post describe _what the code does_. Titles reading like \"What do you think about ...\" or \"How can I improve on ...\", are not useful as every post on *Code Review* is already implicitly a request for feedback on code." } ]
[ { "body": "<h2>Package Name</h2>\n<p>Java code should be placed into a package with a name that avoids collisions with other developers. The best practice is to use the reverse-reading of some domain/account/email that you own, e.g.</p>\n<pre><code>package com.stackexchange.codereview.srxxx.grading;\n</code></pre>\n<h2>Naming Conventions</h2>\n<p>Thumbs up for following the typical Java naming conventions.</p>\n<h2>Names</h2>\n<p>Take great care when introducing variable names, to make them as self-explanatory as possible.</p>\n<p>One improvement: In <code>passingPercentage()</code>, you have a variable named <code>percentage</code>, but it's not in the 0..100 range you'd associate with that word, instead its between 0 and 1. So, I'd call it a ratio instead of a percentage.</p>\n<p>This might sound like nitpicking, but believe me, it's the most important skill when working either in a team, or alone on a long-lived software project.</p>\n<h2>Separate Computation and User Interface</h2>\n<p>You mostly follow the separation of concerns between computation (class <code>PointsStatistics</code>) und user interface (class <code>UserInterface</code>).</p>\n<p>Only for <code>gradeDistribution()</code>, you do <code>System.out.print()</code> inside <code>PointsStatistics</code>. You should change the method to return the list of grades (<code>grades</code> variable) and do the printing loop from the <code>UserInterface</code> class.</p>\n<h2>Document your Classes and Methods</h2>\n<p>Write documentation comments (Javadoc-style) for public classes and methods, documenting what their task is (not how they fulfill it).</p>\n<p>For good Javadoc examples, have a look at the Java library classes, and you surely use the HTML-generated documentation results on web pages like <a href=\"https://docs.oracle.com/javase/8/docs/api/\" rel=\"nofollow noreferrer\">the Java8 Platform Spec</a>. In 20+ years of Java development, I rarely ever had to look into the Java source code, the Javadocs explained all the pre-existing Java classes and methods well enough.</p>\n<h2>Declare Variables with Most Generic Types</h2>\n<p>You should change</p>\n<pre><code>ArrayList&lt;Integer&gt; grades = new ArrayList&lt;&gt;();\n</code></pre>\n<p>to become</p>\n<pre><code>List&lt;Integer&gt; grades = new ArrayList&lt;&gt;();\n</code></pre>\n<p>The general rule is to declare a variable with the most generic type (or interface) that offers the methods and behaviour you need, and initialize it with the concrete class you (currently) want to use.</p>\n<p>Why? Either believe me that it really is best practice, or read along the following lengthy explanation.</p>\n<p>All of your code will work with any type of <code>List</code>, maybe a <code>LinkedList</code> or an array wrapped as a <code>List</code> (using <code>Arrays.asList()</code>). Maybe, later you find a super-cool new <code>List</code> implementation, you want to exchange the <code>ArrayList</code> with that class. Then you just exchange the initialization part to now read</p>\n<pre><code>List&lt;Integer&gt; grades = new SuperCoolList&lt;&gt;();\n</code></pre>\n<p>and everything works the same, just way cooler.</p>\n<p>You may ask, why not do it for both the initialization and the declaration as well:</p>\n<pre><code>SuperCoolList&lt;Integer&gt; grades = new SuperCoolList&lt;&gt;();\n</code></pre>\n<p>The risk is that with the initial declaration <code>ArrayList&lt;Integer&gt; grades</code> nothing stopped you from calling e.g. <code>grades.trimToSize()</code>, which is not part of the <code>List</code> interface but specific to <code>ArrayList</code>. There are two possible situations:</p>\n<ul>\n<li>Probably, <code>SuperCoolList</code> will not have such a method, resulting in a compile error. You see the error, invest some time to invent some replacement for the method call, or find that you can't use the <code>SuperCoolList</code> and return to <code>ArrayList</code>.</li>\n<li>Much worse, the <code>SuperCoolList</code> might have such a method, but doing something different. Then the program will misbehave without you getting any hint by the compiler.</li>\n</ul>\n<p>With</p>\n<pre><code>List&lt;Integer&gt; grades = new ArrayList&lt;&gt;();\n</code></pre>\n<p>this will not happen. Every method you call on the <code>grades</code> variable will be present in every kind of <code>List</code> implementation, and behave the same. You can't accidentally use the <code>grades.trimToSize()</code> method as this isn't part of the <code>List</code> interface. This way, the freedom to later change to a different <code>List</code> implementation is guaranteed by the compiler.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T17:58:38.873", "Id": "270586", "ParentId": "270585", "Score": "3" } }, { "body": "<h1>Bug</h1>\n<p>Your &quot;Part 2&quot; needs work. Specifically, the requirement is</p>\n<blockquote>\n<p>If there are no numbers giving a passing grade, the program should print a line &quot;-&quot; where the average would be.&quot;</p>\n</blockquote>\n<p>Your program crashes if no passing grade is given.</p>\n<h1>Redundant Tests</h1>\n<p>You are testing <code>points &gt; 0</code> and <code>points &lt;= 100</code> twice:</p>\n<pre><code> if (points &gt; 0 &amp;&amp; points &gt;= 50 &amp;&amp; points &lt;= 100) {\n this.passingpoints.add(points);\n }\n if (points &gt; 0 &amp;&amp; points &lt;= 100) {\n this.allpoints.add(points);\n }\n</code></pre>\n<p>You should reorganize this to test the valid range once.</p>\n<pre><code> if (points &gt; 0 &amp;&amp; points &lt;= 100) {\n if (points &gt;= 50) {\n this.passingpoints.add(points);\n }\n this.allpoints.add(points);\n }\n</code></pre>\n<h1>Bug</h1>\n<blockquote>\n<p>The program receives points (integers from zero to one hundred) as input, based on which it prints statistics about grades.</p>\n</blockquote>\n<p>Your <code>points &gt; 0</code> tests result in not including any zero-score points in the statistics. You probably should use <code>points &gt;= 0</code>.</p>\n<h1>Spelling</h1>\n<p><code>possingPointsAverage()</code> should probably be <code>passingPointsAverage()</code></p>\n<h1>Type conversions</h1>\n<h2>int to double</h2>\n<p>The <code>* 1.0</code> in the following is just to ensure the division is not performed as integer division.</p>\n<pre><code> double percentage = (this.passingpoints.size() * 1.0) / this.allpoints.size();\n</code></pre>\n<p>Barring compiler heroics, the passing point size must first be promoted to a <code>double</code> before the <code>double * double</code> multiplication can be performed:</p>\n<pre><code> double percentage = ((double)this.passingpoints.size() * 1.0) / this.allpoints.size();\n ^^^^^^^^\n</code></pre>\n<p>At this point, the multiplication by <code>1.0</code> is just busy-work which should be optimized away.</p>\n<pre><code> double percentage = (double)this.passingpoints.size() / this.allpoints.size();\n</code></pre>\n<p>Any compiler worth its salt will <em>probably</em> do this optimization for you, but there are limits. And in this case, the awkward <code>* 1.0</code> can be eliminated without inserting the cast by simply combining the operation with the next line, which multiplied the result by 100 to convert the ratio to a percentage.</p>\n<pre><code> double percentage = 100.0 * this.passingpoints.size() / this.allpoints.size();\n return percentage;\n</code></pre>\n<h2>Unboxing</h2>\n<pre><code> for (Integer points : this.allpoints) {\n if (points &lt; 50) {\n grades.add(0);\n } else if (points &lt; 60) {\n grades.add(1);\n } else if (points &lt; 70) {\n grades.add(2);\n } else if (points &lt; 80) {\n grades.add(3);\n } else if (points &lt; 90) {\n grades.add(4);\n } else if (points &lt;= 100) {\n grades.add(5);\n }\n }\n</code></pre>\n<p>In this loop <code>points</code> is an <code>Integer</code>, which is a &quot;boxed primitive&quot;. To use it, the value must be unboxed to an <code>int</code>, by implicitly calling <code>points.intValue()</code> where it is used in integer context. I see 6 places where this happens: <code>points &lt; 50</code>, <code>points &lt; 60</code>, <code>points &lt; 70</code>, <code>points &lt; 80</code>, <code>points &lt; 90</code>, <code>points &lt;= 100</code>.</p>\n<p>Again, any compiler worth its salt <em>should</em> optimize that for you, but it would be simpler just to unbox the result to an <code>int</code> once ... in the for statement:</p>\n<pre><code> for (int points : this.allpoints) {\n ^^^\n</code></pre>\n<h1>Is it optimal?</h1>\n<p>No.</p>\n<pre><code> for (int i = 5; i &gt;= 0; i--) {\n System.out.print(i + &quot;: &quot;); \n for(Integer grade : grades) {\n if (grade == i) {\n System.out.print(&quot;*&quot;);\n</code></pre>\n<p>If you have one hundred points scores, you will create a duplicate <code>grades</code> list which will have one hundred entries, each with either a <code>0</code>, <code>1</code>, <code>2</code>, <code>3</code>, <code>4</code>, or <code>5</code>. You then loop through the list of one hundred entries 6 times, once for each grade level. That executes the <code>if (grade == i)</code> statement <strong>six hundred times</strong>!</p>\n<p>Instead, if you used something more like:</p>\n<pre><code> public void gradeDistribution() {\n int grades[] = new int[] {0, 0, 0, 0, 0, 0};\n for (int points : this.allpoints)\n if (points &lt; 50)\n grades[0]++;\n else if (points &lt; 60)\n grades[1]++;\n else if (points &lt; 70)\n grades[2]++;\n else if (points &lt; 80)\n grades[3]++;\n else if (points &lt; 90)\n grades[4]++;\n else if (points &lt;= 100)\n grades[5]++;\n\n ...\n</code></pre>\n<p>Now, instead of a hundred grade values, you have only 6 values representing the count of each grade value. This should be easier to work with.</p>\n<h1>This</h1>\n<p>You almost never need to use <code>this.</code> inside methods. It just adds verbosity, and creates confusion when you accidentally forget to use it.</p>\n<pre><code> System.out.println(&quot;Point average (all): &quot; + this.points.pointsAverage());\n System.out.println(&quot;Points average (passing): &quot; + this.points.possingPointsAverage());\n System.out.println(&quot;Pass percentage: &quot; + this.points.passingPercentage());\n points.gradeDistribution();\n</code></pre>\n<p>What is the difference between <code>this.points</code> in the first three lines, and <code>points</code> in the last??? There isn't any, yet it looks different! The reader is left wondering &quot;Is it intentional? Is there a reason for the difference I'm missing???&quot; They have to look back and check if there is some variable or parameter shadowing the member name.</p>\n<p>(There are times where you might need to use <code>this.</code>, such as in a constructor or a setter function, you might pass in a parameter with the same name as a member, and have to use a statement like <code>this.name = name;</code>. In general, it is safer to use a slightly different name, such as adding an underscore to the parameter name and writing <code>name = _name;</code>)</p>\n<h1>Names</h1>\n<p>Avoid naming variables with jammed together names like <code>allpoints</code> and <code>passingpoints</code>. They get hard to read. Use underscores (<code>all_points</code>) or bumpy words (<code>allPoints</code>) to give the reader a chance because figuringoutwhereonewordendsandthenextbeginscanbehard.</p>\n<h1>Exception handling</h1>\n<p>If the user enters a grade of <code>49.5</code> or <code>end</code>, the program will crash with a <code>NumberFormatException</code>. Use <code>try ... catch</code> where user input occurs to prevent accidental/unnecessary crashes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T05:48:08.610", "Id": "534492", "Score": "0", "body": "Since you brought out boxed primitive types, it is worth mentioning that the main reason for using boxed types is to convey to the reader the possibility of a null-reference. So in this case the main reason for using a primitive int in the loop would be to signal the lack of need to handle a null value in the if-statements, rather than performance optimization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T07:09:55.067", "Id": "534505", "Score": "0", "body": "@TorbenPutkonen In this case, the reason for using boxed types is because until [Project Valhalla](https://openjdk.java.net/projects/valhalla/) is implemented, specifically [JEP 218: Generics over Primitive Types](https://openjdk.java.net/jeps/218), `ArrayList<int>` is not valid." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:39:38.823", "Id": "534525", "Score": "0", "body": "That is an obvious restriction on generics that do not need to be repeated. I am talking about the loop variable specifically and fields in general. The reason one would use a boxed primitive type in a variable is to convey the possibility of null value." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T23:06:50.133", "Id": "270600", "ParentId": "270585", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T16:52:14.407", "Id": "270585", "Score": "1", "Tags": [ "java" ], "Title": "Grade Statistics" }
270585
<p>I want to find if all of a list of substrings exist in a string, in the correct order (with or without spaces between them), it seems to be a good use for regex.</p> <p>I think I need to build a regex filter of <code>&quot;a.*b.*c&quot;</code> and use search to find that anywhere in my string.</p> <p>Are there any other approaches I could consider or built in functions that might do this for me?</p> <pre><code>from re import search def are_substrings_in_text(substrings,text): return search(&quot;&quot;.join([s+&quot;.*&quot; for s in substrings]),text) is not None print(are_substrings_in_text([&quot;a&quot;,&quot;b&quot;,&quot;c&quot;],&quot;abacus&quot;)) # &gt;True print(are_substrings_in_text([&quot;a&quot;,&quot;c&quot;,&quot;b&quot;],&quot;abacus&quot;)) # &gt;False print(are_substrings_in_text([&quot;a&quot;,&quot;c&quot;,&quot;z&quot;],&quot;abacus&quot;)) # &gt;False </code></pre>
[]
[ { "body": "<p>The problem with your current approach is that it can give incorrect results\nor raise an exception if any of the substrings contain characters that\nhave special meaning in Python regular expressions.</p>\n<pre><code>are_substrings_in_text(['a', '.', 's'], 'abacus')) # Returns True\nare_substrings_in_text(['a', '+', 's'], 'abacus')) # Raises exception\n</code></pre>\n<p>The solution is to escape such characters so that they are handled as\nliteral substrings. This illustration also makes a few cosmetic adjustments\nto simplify things for readability:</p>\n<pre><code>from re import search, escape\n\ndef are_substrings_in_text(substrings, text):\n pattern = '.*'.join(escape(s) for s in substrings)\n return bool(search(pattern, text))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T23:21:27.913", "Id": "534475", "Score": "2", "body": "Any reason you're not using `'.*'.join(escape(s) for s in substrings)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T23:51:12.867", "Id": "534482", "Score": "1", "body": "@AJNeufeld I blame my aging mind." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:32:56.553", "Id": "270593", "ParentId": "270589", "Score": "4" } }, { "body": "<p>It isn't necessary to use regular expressions (the re module), use the <code>str.index()</code> method. For the examples given, <code>re.search</code> takes 3x longer.</p>\n<pre><code>def are_substrings_in_text_index(substrings, text):\n start = 0\n try:\n for substring in substrings:\n start = text.index(substring, start) + len(substring)\n \n return True\n \n except ValueError:\n return False\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T13:58:56.163", "Id": "534540", "Score": "0", "body": "Good point on the performance, thanks! It seems to vary depending on the relationship between the number of substrings and the length of the text; I guess in a real scenario one would model it with realistic data to see the best approach, If it was really time critical. I also noticed that \"if substring not in text\" is significantly faster than either; and regex REALLY struggles with near-misses. So a filter pass to see if at least each character exists in the text will speed up finding non-matches massively too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T06:00:20.493", "Id": "270605", "ParentId": "270589", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T18:51:19.507", "Id": "270589", "Score": "0", "Tags": [ "python", "regex" ], "Title": "Python function for finding if all substrings exist in a string in sequence" }
270589
<p>This is the code I came up with for the Rust pig latin exercise.</p> <p>I am looking for suggestions on how to make it more idiomatic.</p> <p>I think working with iterators instead of chars and Strings would be a step in the right direction?</p> <p>I was unable to figure out how to use <code>.map</code> to reach the same result. I would have liked to iterate over a <code>SplitWhiteSpace</code> and apply the manipulations to each slices in one pass instead of using a <code>for loop</code>.</p> <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=67eac763bfe5640b5bf16d54a0e958ec" rel="nofollow noreferrer">Rust playground link</a></p> <pre><code>fn main() { let phrase = &quot;Test sentence for pig latin f नर र स्का स्कास्का &quot;.to_lowercase(); let split = phrase.split_whitespace(); let mut pigifyed: String = String::new(); for word in split { let mut chars = word.chars(); let firstchar = chars.next().unwrap(); if chars.next() == None { pigifyed = format!(&quot;{} {}ay&quot;, pigifyed, firstchar) } else if is_vowel(&amp;firstchar) { pigifyed = format!(&quot;{} {}-hay&quot;, pigifyed, word); } else { let end = &amp;word[firstchar.len_utf8()..]; pigifyed = format!(&quot;{} {}-{}ay&quot;, pigifyed, end, firstchar); } } println!(&quot;{}&quot;, pigifyed) } fn is_vowel(char: &amp;char) -&gt; bool { let vowels = ['a', 'e', 'i', 'o', 'u']; vowels.contains(char) } </code></pre> <p><em>Output:</em></p> <p><code>est-tay entence-say or-fay ig-pay atin-lay fay -ay र-नay रay ्का-सay ्कास्का-सay ay</code></p>
[]
[ { "body": "<p>I can't see how you got stuck. You just do like you said: use <code>map</code> instead of Strings, then collect into a Vec, and finally join into one String.</p>\n<p>Here is the code.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn main() {\n let phrase = &quot;Test sentence for pig latin f नर र स्का स्कास्का &quot;.to_lowercase();\n let split = phrase.split_whitespace();\n\n let pigifyed = split.map(|word| {\n let mut chars = word.chars();\n let firstchar = chars.next().unwrap();\n\n if chars.next() == None {\n format!(&quot;{}ay&quot;, firstchar)\n } else if is_vowel(&amp;firstchar) {\n format!(&quot;{}-hay&quot;, word)\n } else {\n let end = &amp;word[firstchar.len_utf8()..];\n format!(&quot;{}-{}ay&quot;, end, firstchar)\n }\n }).collect::&lt;Vec&lt;String&gt;&gt;().join(&quot; &quot;);\n println!(&quot;{}&quot;, pigifyed)\n}\n\nfn is_vowel(char: &amp;char) -&gt; bool {\n let vowels = ['a', 'e', 'i', 'o', 'u'];\n vowels.contains(char)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T17:57:06.503", "Id": "534581", "Score": "0", "body": "Thanks for the demonstration on how to collect and join. \nI'll fiddle more with iterators to get comfortable with manipulating them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T08:40:47.103", "Id": "270606", "ParentId": "270590", "Score": "0" } } ]
{ "AcceptedAnswerId": "270606", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T18:53:51.200", "Id": "270590", "Score": "1", "Tags": [ "beginner", "rust", "pig-latin" ], "Title": "Rust Pig Latin Translator - Idiomatic suggestions" }
270590
<p>I recently faced this following question in a Java coding round, needless to say I did not get a callback. So I want to know where I am going wrong in my solution and also what can be done to improve it.</p> <p><strong>The Problem statement was as follows:</strong></p> <blockquote> <p>Create a java program, with two components, a supplier and consumer.</p> <p>Supplier’s responsibility is to provide ‘random integer values’ in ‘random time intervals’ to consumer.</p> <p>Consumer is responsible to receive data provided by supplier in the same order and add it to a binary tree. When all the data is passed and processed, consumer should print the data of binary tree in visually tree format.</p> <p>Supplier’s ‘random time interval’ should be dynamically calculated which can be between 1 and 5 second(s). A total of 10 randomly generated integer elements can be passed on to the consumer.</p> <p>Maximum number of thread instances which can be initialized in the solution is three.</p> </blockquote> <p>You can ignore the part about adding it to a binary tree and printing it. <strong>I am more interested in the multithreaded implementation of producer/consumer.</strong></p> <p>The Solution that I submitted was as follows:</p> <pre><code>import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicInteger; public class InternalQueue { private static final int MAX_QUEUE_SIZE = 10; private final BlockingQueue&lt;Integer&gt; queue = new ArrayBlockingQueue&lt;&gt;(MAX_QUEUE_SIZE); private final AtomicInteger itemsProduced = new AtomicInteger(0); private final AtomicInteger itemsConsumed = new AtomicInteger(0); public boolean put(int n) { if(itemsProduced.incrementAndGet() &gt; MAX_QUEUE_SIZE) return false; System.out.println(Thread.currentThread().getName() + &quot; trying to put &quot; + n); return queue.offer(n); } public Optional&lt;Integer&gt; get() throws InterruptedException { if(itemsConsumed.incrementAndGet() &gt; MAX_QUEUE_SIZE) return Optional.empty(); Integer n = queue.take(); System.out.println(Thread.currentThread().getName() + &quot; consumed &quot; + n); return Optional.of(n); } } </code></pre> <p>I went with a queue data structure where all the elements would be held until a consumer was ready to consume it. (Somewhat how MQ systems operate)</p> <p>Then the producer and consumers:</p> <pre><code>import java.util.concurrent.CountDownLatch; public class Consumer implements Runnable{ private InternalQueue queue; private BTree bTree; private CountDownLatch latch; public Consumer(InternalQueue queue, BTree bTree, CountDownLatch latch) { this.queue = queue; this.bTree = bTree; this.latch = latch; } @Override public void run() { while (true) { Optional&lt;Integer&gt; num; try { num = queue.get(); } catch (InterruptedException e) { e.printStackTrace(); latch.countDown(); break; } if(num.isEmpty()) { latch.countDown(); break; } int n = num.get(); System.out.println(Thread.currentThread().getName() + &quot; pushing to BTREE &quot; + n); bTree.insert(n); } } } public class Producer implements Runnable{ private InternalQueue queue; private CountDownLatch latch; public Producer(InternalQueue queue, CountDownLatch latch) { this.queue = queue; this.latch = latch; } @Override public void run(){ while (true) { int num = ThreadLocalRandom.current().nextInt(); boolean added = queue.put(num); if(!added) { latch.countDown(); break; } int delay = ThreadLocalRandom.current().nextInt(1, 5+1); try { Thread.sleep(delay * 1000L); } catch (InterruptedException e) { e.printStackTrace(); latch.countDown(); break; } } } } </code></pre> <p>Please ignore the B-Tree part.</p> <p>And lastly the <code>void main(String args[])</code> of the program:</p> <pre><code>public class Runner { private static final int THREAD_POOL_SIZE = 3; public static void main(String[] args) throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(THREAD_POOL_SIZE); InternalQueue queue = new InternalQueue(); BTree bTree = new BTree(); int num_threads = 3; CountDownLatch latch = new CountDownLatch(num_threads); Producer producer1 = new Producer(queue,latch); Producer producer3 = new Producer(queue,latch); Consumer consumer1 = new Consumer(queue, bTree,latch); Consumer consumer2 = new Consumer(queue, bTree,latch); service.execute(producer1); service.execute(consumer2); // service.execute(producer3); service.execute(consumer1); latch.await(); bTree.printTree(); service.shutdown(); } } </code></pre> <p>So a couple of questions:</p> <ol> <li>Is this solution thread-safe and correct ? I used <code>AtomicInteger</code> to guard against when the producer has produced over the limit and another <code>AtomicInteger</code> so guard against queue underflow. <strong>Is it ok ?</strong> Or is there something better or wrong ?</li> <li>Was it correct to use a <code>CountDownLatch</code> ? Or was it overkill ?</li> <li><code>BlockingQueue</code> needed or not ? I used it because I was not sure if any concurrency problems would be there if I hadn't used a thread-safe Collection from the library.</li> </ol> <p>Any feedback or suggestions ?</p> <p>Thanks.</p>
[]
[ { "body": "<p>As you requested I am going to ignore B-Tree and display stuff.</p>\n<p>First off after reading problem description it is not obvious for me how exactly should the solution look like:</p>\n<ul>\n<li><code>random integer values</code> - does plural form of <code>values</code> suggests that producer should be able to produce more than one value <strong>at a time</strong> or just that it is able to produce many of them over many iterations?</li>\n<li><code>A total of 10 randomly generated integer elements can be passed on to the consumer.</code> - what kind of limit is this, exactly? Is it supposed to be whole problem constraint (like producer should only produce 10 values)? Is it consumer limit (so that consumer rejects more than 10 values)? Is it producer limit (so that producer shouldn't produce more than 10 values? at a time? in the whole program lifecycle?)</li>\n</ul>\n<p>Before coding anything I'd start with trying to clarify problem description (who knows may that be part of interview process for that company?).</p>\n<p>Correctness in terms of the problem description:</p>\n<ul>\n<li><p>Rule stated in the description: <code>Maximum number of thread instances which can be initialized in the solution is three</code> seems to be broken as program will initialize at least (ignoring jvm details) 4 threads during its runtime (1) main thread and (2)(3)(4) thread pool threads. This can be easily fixed as it seems that only one producer and one consumer are needed here (according to the problem description).</p>\n</li>\n<li><p><code>BlockingQueue</code> - in a version with only one producer and one consumer there is no <em>shared mutable state</em> (only one thing modifies and one reads) so the only aspect that we have to really worry about is read-during-write thread safety (so if collection implementation does not have some possible internal state during the write that would cause reads to fail) and <code>BlockingQueue</code> seems to satisfy this condition (it is thread-safe according to reads) possibly you could also use simple <code>LinkedList</code> with manual synchronization during writes (see e.g. <code>linkLast(E e)</code> implementation - it has mentioned internal state that <em>during</em> write may lead to inconsistent reads).</p>\n</li>\n</ul>\n<p>In terms of the code itself:</p>\n<ol>\n<li>Consider writing tests for it - in multi thread cases its always an adventure and would require adjusting the code design to be testable</li>\n<li>Currently both producer and consumer can modify the queue - as both have access to method <code>put</code> - if we don't want consumer to produce I'd express this intention in the code design... Consider if the consumer and producer <em>need</em> to know how exactly data is transferred (it kinda depends on a problem description not being clear in this regard, sadly) - possibly all that producer needs is <code>Comsumer&lt;Integer&gt;</code> and all what producer needs is <code>Supplier&lt;Integer&gt;</code> instead of whole queue.</li>\n<li>Are you sure you need whole queue? Maybe consumer and producer can communicate using just shared <code>AtomicInteger</code> (possibly via interfaces mentioned in previous point)? (again it heavily depends on the unclear problem description)</li>\n<li>Just from reading the code I am not entirely sure what <code>CountDownLatch</code> actually does - it goes to 0 after <code>countDown()</code> in either producer or consumer - so like 1 produce 1 consume and 1 more produce is enough which will cause a tree to be printed and main thread to be shut down, right? Tests would be mighty useful here - I assume this is not intended behavior. If it was intended as a mean of signalling to the main thread that consumer has finished processing all data (and, at the same time, decouple it from expected number of elements? then why passing it to producer?) I would reconsider the approach.</li>\n</ol>\n<p>There are also smaller things about the code that could be improved but I think that its design should be reconsidered first.</p>\n<p>PS. after reviewing the code for a bit I think that description is not that vague as I initially thought - I think that my initial confusion was caused by my understanding being different than the one represented in the given code. I'd assume that intended understanding was: Producer should produce 10 values, one at a time, in random time periods. After those 10 (all) values were processed data should be visualized in form of B-tree. (which should simplify the solution).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T12:00:15.180", "Id": "270614", "ParentId": "270595", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T19:47:38.097", "Id": "270595", "Score": "1", "Tags": [ "java", "multithreading", "producer-consumer" ], "Title": "Producer/Consumer Multi-Thread implementation - Is the solution correct?" }
270595
<p>I know this is probably more complicated than it needs to be, however, I would really appreciate some help. I'm trying to create a trigger in MySQL that will update the value in the Costs table when a value is inserted into the Assignments table. HOWEVER, it can't just be that value, it has to be the product of the inserted value and a related value in the Employees table. Example below:</p> <p><em>Assignments</em>: employeeID, projectID, hoursAssigned, PK (employeeID, projectID) FK(projectID) FK(employeeID)</p> <p><em>Employees</em>: employeeID, employeeName, hourlyWage, PK (employeeID)</p> <p><em>Costs</em>: costID, projectID, budget, laborCosts, PK (costID) FK (projectID)</p> <p><em>NOTE: Costs has a 1-1 relationship with the Project table, where projectID comes from.</em></p> <p>When the value <code>hoursAssigned</code> is inserted into Assignments, the product of <code>Assignments.hoursAssigned * Employees.hourlyWage</code> is updated into the Costs table as <code>laborCosts</code>. However I'm trying to not just update it to laborCosts but add it to whatever currently exists in laborCosts, if it's null I'm coalescing it to 0.</p> <p>Here's my code below.</p> <pre><code># Trigger to update Costs from insert on Assignments delimiter // CREATE TRIGGER tgr_insert_assnm AFTER INSERT ON Assignments FOR EACH ROW BEGIN UPDATE Costs c SET c.Labor_Costs = (IFNULL(c.Labor_Costs, 0) + (NEW.Hours_Assigned * (SELECT Hourly_Wage FROM Employees WHERE Employee_ID = NEW.Employee_ID))) WHERE c.Project_ID = NEW.Project_ID; END;// delimiter ; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T20:18:16.037", "Id": "270597", "Score": "0", "Tags": [ "sql", "mysql", "error-handling", "database" ], "Title": "Create trigger that updates Table3 from an insert into Table1 that multiplied by a value in Table 2 in MySQL" }
270597
<p>Just solved <a href="https://projecteuler.net/problem=2" rel="nofollow noreferrer">Euler Project Problem 2</a> using JavaScript and I would like to know how I could improve my code. I do think it looks good, but you never know.</p> <h3>Problem Statement</h3> <blockquote> <p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p> <pre><code>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... </code></pre> <p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</p> </blockquote> <pre><code>function fibonacci() { var a = 0, b = 1, count = 0; for(var sum = 0; sum &lt; 4000000;){ sum = a + b; a = b; b = sum; if(sum % 2 == 0){ count += sum; } } return count; } console.log(fibonacci()); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T23:03:30.930", "Id": "534473", "Score": "0", "body": "Are you sure you're getting the correct result? You start with different numbers and your ending isn't spot on, although the latter doesn't seem to influence the outcome." } ]
[ { "body": "<p>With a bit of fiddling I come to this code:</p>\n<pre><code>function fibonacci() {\n let s = t = 0, a = 1, b = 2;\n do {\n s = a + b;\n a = b;\n b = s;\n t += s &amp; 1 ? 0 : s;\n } while (s &lt;= 4000000);\n return t;\n}\n\nconsole.log(fibonacci());\n</code></pre>\n<p>It is pretty much the same as yours with a few difference:</p>\n<ul>\n<li>I start with <code>a = 1, b = 2</code> as per instructions, but this means my result is 4613730 and not 4613732.</li>\n<li><code>let</code> will do for the variables, because they are only used in the block they are in, but since that is the same as the function <code>var</code> is fine too.</li>\n<li>I also follow the instructions where it says to: <em>&quot;not exceed four million&quot;</em>, this includes four million.</li>\n<li>I prefer the clean look of the <code>do { ... } while</code> loop. This also means I don't have to initialized the sum.</li>\n<li>There's nothing wrong with your <code>(sum % 2 == 0)</code> check, but mine is visibly shorter. Normally I don't care about that and would prefer yours because is easier to read.</li>\n</ul>\n<p>I think the real art is to do this with less operations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T23:45:40.090", "Id": "534481", "Score": "0", "body": "Would you mind explaining to me how to read the ``t += s & 1 ? 0 : s;`` line?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T00:27:45.970", "Id": "534483", "Score": "1", "body": "@fabinfabinfabin Sorry, yes that's a bit esoteric. It's easier to read when written as: `t += (s & 1) ? 0 : s;`. First the `s & 1` bit, see the answer here: [How to determine if a number is odd in JavaScript](https://stackoverflow.com/questions/5016313/how-to-determine-if-a-number-is-odd-in-javascript). The other bit, `... ? ... : ...`, is using a [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator), basically a short way of writing \"if .... then .... else ....\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T18:41:14.530", "Id": "534585", "Score": "0", "body": "Minor nitpick - you probably want to declare your \"s\" variable, so it's not global. \"let/const s = a + b\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T19:00:48.917", "Id": "534588", "Score": "0", "body": "@ScottyJamison Yes, that's a good point, I'll edit my code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T23:12:08.340", "Id": "270601", "ParentId": "270598", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T22:04:09.940", "Id": "270598", "Score": "1", "Tags": [ "javascript", "programming-challenge" ], "Title": "Euler Project Problem 2 JavaScript" }
270598
<p>I'm trying to improve the following <a href="https://github.com/Marfusios/binance-client-websocket" rel="nofollow noreferrer">Binance Web Socket API wrapper</a>. I like it because it uses <code>System.Reactive</code> and it takes advantage of the <a href="https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md#general-wss-information" rel="nofollow noreferrer">combined web socket streams</a>. With the combined stream, you could subscribe to multiple streams and use only one socket/TCP connection. Here is a working example.</p> <p>Since it's using the combined web socket stream, all JSON objects are being handled by the same message event and the deserialization must know how to differentiate the objects. The old code achieves that abstraction by using <code>JObject</code> and by looking at the <code>Stream</code> property which is displaying the actual stream name. <a href="https://github.com/Marfusios/binance-client-websocket/blob/44c99467a64ee926dff7174cbdb9e3a2c3e33b6a/src/Binance.Client.Websocket/Responses/AggregateTrades/AggregatedTradeResponse.cs#L13" rel="nofollow noreferrer">Reference to the old code</a>. Speaking of it, that's the reason I'm creating that question. I want to replace the old <code>Newtonsoft.Json</code> code with <code>System.Text.Json</code>, because of the performance.</p> <h2>Snippet</h2> <p>The old code which uses <code>Newtonsoft.Json</code> can be found <a href="https://github.com/Marfusios/binance-client-websocket/blob/44c99467a64ee926dff7174cbdb9e3a2c3e33b6a/src/Binance.Client.Websocket/Responses/AggregateTrades/AggregatedTradeResponse.cs#L13" rel="nofollow noreferrer">here</a>.</p> <p>Here are my changes and I'm pretty sure you will have something to add. For example, I'm not handling JsonDocument's disposal.</p> <pre class="lang-cs prettyprint-override"><code>public class TickerResponse : ResponseBase&lt;Ticker&gt; { internal static bool TryHandle(JsonDocument response, ISubject&lt;TickerResponse?&gt; subject) { var stream = response.RootElement.GetProperty(&quot;stream&quot;).GetString() ?? string.Empty; if (!stream.ToLower().EndsWith(&quot;@ticker&quot;)) return false; var parsed = response.ToObject&lt;TickerResponse&gt;(); subject.OnNext(parsed); return true; } } </code></pre> <pre class="lang-cs prettyprint-override"><code>public sealed class BinanceWebSocketClient : IDisposable { private readonly IBinanceCommunicator _communicator; private readonly IDisposable _messageReceivedSubscription; public BinanceWebSocketClient(IBinanceCommunicator communicator) { _communicator = communicator ?? throw new ArgumentNullException(nameof(communicator)); _messageReceivedSubscription = _communicator.MessageReceived.Subscribe(HandleMessage); } /// &lt;summary&gt; /// Provided message streams. /// &lt;/summary&gt; public BinanceClientStreams Streams { get; } = new(); /// &lt;summary&gt; /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// &lt;/summary&gt; public void Dispose() { _messageReceivedSubscription.Dispose(); } /// &lt;summary&gt; /// Combine url with subscribed streams /// &lt;/summary&gt; private Uri PrepareSubscriptions(Uri baseUrl, params SubscriptionBase[] subscriptions) { Guard.Against.Null(baseUrl, nameof(baseUrl)); Guard.Against.Null(subscriptions, nameof(subscriptions), &quot;Please provide at least one subscription&quot;); var streams = subscriptions.Select(x =&gt; x.StreamName).ToArray(); var urlPart = string.Join(&quot;/&quot;, streams); var urlPartFull = $&quot;/stream?streams={urlPart}&quot;; var currentUrl = baseUrl.ToString().Trim(); if (currentUrl.Contains(&quot;stream?&quot;)) // do nothing, already configured return baseUrl; var newUrl = new Uri($&quot;{currentUrl.TrimEnd('/')}{urlPartFull}&quot;); return newUrl; } /// &lt;summary&gt; /// Used for the combined stream. /// &lt;/summary&gt; /// &lt;param name=&quot;subscriptions&quot;&gt;&lt;/param&gt; public void AddSubscription(params SubscriptionBase[] subscriptions) { Guard.Against.Null(subscriptions, nameof(subscriptions), &quot;Please provide at least one subscription&quot;); var newUrl = PrepareSubscriptions(_communicator.Url, subscriptions); _communicator.Url = newUrl; } private void HandleMessage(ResponseMessage message) { Guard.Against.Null(message, nameof(message)); try { bool handled; var messageSafe = (message.Text ?? string.Empty).Trim(); if (messageSafe.StartsWith(&quot;{&quot;)) { handled = HandleObjectMessage(messageSafe); if (handled) return; } handled = HandleRawMessage(messageSafe); if (handled) return; //Log.Warn(L($&quot;Unhandled response: '{messageSafe}'&quot;)); } catch (Exception e) { //Log.Error(e, L(&quot;Exception while receiving message&quot;)); } } private bool HandleRawMessage(string msg) { // Add raw handlers return PongResponse.TryHandle(msg, Streams.PongSubject); } private bool HandleObjectMessage(string msg) { var response = JsonDocument.Parse(msg); // TODO: This is IDisposable // Add object handlers return AggregateTradeResponse.TryHandle(response, Streams.TradeBinSubject) || TradeResponse.TryHandle(response, Streams.TradesSubject) || MiniTickerResponse.TryHandle(response, Streams.MiniTickerSubject) || BookTickerResponse.TryHandle(response, Streams.BookTickerSubject) || KlineResponse.TryHandle(response, Streams.KlineSubject); //OrderBookPartialResponse.TryHandle(response, Streams.OrderBookPartialSubject) || //OrderBookDiffResponse.TryHandle(response, Streams.OrderBookDiffSubject) || //FundingResponse.TryHandle(response, Streams.FundingSubject) } } </code></pre> <pre class="lang-cs prettyprint-override"><code>/// &lt;summary&gt; /// Binance preconfigured JSON serializer. /// &lt;/summary&gt; public static class BinanceJsonSerializer { /// &lt;summary&gt; /// JSON settings. /// &lt;/summary&gt; public static readonly JsonSerializerOptions Options = new() { ReferenceHandler = ReferenceHandler.IgnoreCycles, NumberHandling = JsonNumberHandling.AllowReadingFromString }; /// &lt;summary&gt; /// Parses the text representing a single JSON value into a &lt;typeparamref name=&quot;TValue&quot; /&gt;. /// &lt;/summary&gt; /// &lt;typeparam name=&quot;TValue&quot;&gt;&lt;/typeparam&gt; /// &lt;param name=&quot;json&quot;&gt;JSON text to parse.&lt;/param&gt; /// &lt;returns&gt;A &lt;typeparamref name=&quot;TValue&quot; /&gt; representation of the JSON value.&lt;/returns&gt; public static TValue? FromJson&lt;TValue&gt;(this string json) { Guard.Against.NullOrWhiteSpace(json, nameof(json)); return JsonSerializer.Deserialize&lt;TValue&gt;(json, Options); } /// &lt;summary&gt; /// Converts the provided value into a &lt;see cref=&quot;string&quot; /&gt;. /// &lt;/summary&gt; /// &lt;typeparam name=&quot;TValue&quot;&gt;&lt;/typeparam&gt; /// &lt;param name=&quot;value&quot;&gt;The value to convert.&lt;/param&gt; /// &lt;returns&gt;A &lt;see cref=&quot;string&quot; /&gt; representation of the value.&lt;/returns&gt; public static string ToJson&lt;TValue&gt;(this TValue value) { return JsonSerializer.Serialize(value, Options); } /// &lt;summary&gt; /// Parses &lt;see cref=&quot;JsonElement&quot; /&gt; into a &lt;typeparamref name=&quot;TValue&quot; /&gt;. /// &lt;/summary&gt; /// &lt;typeparam name=&quot;TValue&quot;&gt;&lt;/typeparam&gt; /// &lt;param name=&quot;element&quot;&gt;JSON element to parse.&lt;/param&gt; /// &lt;returns&gt;A &lt;typeparamref name=&quot;TValue&quot; /&gt; representation of the JSON value.&lt;/returns&gt; public static TValue? ToObject&lt;TValue&gt;(this JsonElement element) { var json = element.GetRawText(); return JsonSerializer.Deserialize&lt;TValue&gt;(json, Options); } /// &lt;summary&gt; /// Parses &lt;see cref=&quot;JsonDocument&quot; /&gt; into a &lt;typeparamref name=&quot;TValue&quot; /&gt;. /// &lt;/summary&gt; /// &lt;typeparam name=&quot;TValue&quot;&gt;&lt;/typeparam&gt; /// &lt;param name=&quot;document&quot;&gt;JSON document to parse.&lt;/param&gt; /// &lt;returns&gt;A &lt;typeparamref name=&quot;TValue&quot; /&gt; representation of the JSON value.&lt;/returns&gt; public static TValue? ToObject&lt;TValue&gt;(this JsonDocument document) { var json = document.RootElement.GetRawText(); return JsonSerializer.Deserialize&lt;TValue&gt;(json, Options); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-01T22:29:44.533", "Id": "270599", "Score": "1", "Tags": [ "c#", "json", ".net-core" ], "Title": "Achieving same abstraction by replacing JObject's implementation with System.Text.Json alternative" }
270599
<p>I am trying to solve a <a href="https://leetcode.com/problems/implement-strstr/" rel="nofollow noreferrer">needle in haystack</a> using <a href="https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm" rel="nofollow noreferrer">Rabin-Karp algorithm</a>, but for large inputs my code takes way too long time. Here is the part which apparently is too slow:</p> <pre><code>char_map = dict(zip(list(&quot;abcdefghijklmnopqrstuvwxyz&quot;), list(range(1, 29)))) def hash_function(s): hash = 0 n = len(s) for i, ch in enumerate(s): hash += char_map[ch] * 10**(n-i-1) return hash </code></pre> <p>Since this function is O(n), I do not understand why it is being so slow (I only call this function twice in my solution).</p> <p>For comparison, I solved the problem using a very naive method, which also uses a O(n) time.</p> <pre><code>def strStr(self, haystack: str, needle: str) -&gt; int: if len(needle) &gt; len(haystack): return -1 if not needle: return 0 for i, ch in enumerate(haystack): if ch == needle[0]: if i+len(needle) &lt;= len(haystack) and needle == haystack[i:i+len(needle)]: return i return -1 </code></pre> <p>But this one managed to go through the same large input without any issues. What am I doing incorrectly?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T03:16:29.337", "Id": "534488", "Score": "2", "body": "How large does `n` get? Thinking about the implications of this: `10**(n-i-1)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T03:17:26.433", "Id": "534489", "Score": "3", "body": "`hash` will be at most \\$10^{5 \\times 10^4} = 2^{166096} = 2^{2595 * 64 + 16}\\$. So you'll be adding 2.6k ints (assuming the underlying ints are 64bit) together 50k times. I don't think Python's ints are designed for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T04:49:53.463", "Id": "534491", "Score": "2", "body": "Micro review: `range(1, 29)` should be `range(1, 27)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T06:41:01.893", "Id": "534503", "Score": "1", "body": "To be efficient, the hash function used in the Rabin-Karp algorithm needs to be a rolling hash. Otherwise, the algorithm takes O(n * m), where `n` and `m` are the lengths of the needle and the haystack. Your hash doesn't appear to be a rolling hash." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T07:52:55.723", "Id": "534507", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T08:18:28.720", "Id": "534508", "Score": "1", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T02:47:06.980", "Id": "270604", "Score": "0", "Tags": [ "python", "performance", "programming-challenge" ], "Title": "String search using Rabin-Karp algorithm" }
270604
<p>On web pages, obviously we cannot serve 4000x4000px photos and just let CSS do the resizing: it would be <strong>too slow for end users and too bandwidth-consuming for the server</strong>.</p> <p>So it's important to rescale photos to the desired size that will be <em>actually used</em> on the website. For this reason I usually resized the image with a tool like Photoshop to, say 800px width. But then later you always have the case <em>&quot;I would finally have preferred 10000px instead!</em> and then ... you have to export the JPG <em>again</em>, re-upload, etc. Annoying!</p> <p>Instead here is an automated solution in which you upload the top-quality version (never served to end users because too big), and the tool automatically resizes on-demand.</p> <p>Here is a code that:</p> <ul> <li>serves <code>myphoto.jpg</code> if present in current folder</li> <li>serves <code>myphoto!500.jpg</code> if present in current folder</li> <li>creates <code>myphoto!500.jpg</code> by rescaling <code>myphoto.jpg</code> with a width of 500px if it is not done yet. So as it will be saved/cached to a file, next requests will be fast because the server will just serve the pre-cooked file</li> </ul> <p><strong>.htaccess</strong></p> <pre><code>RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php [QSA,L] </code></pre> <p><strong>index.php</strong></p> <pre><code>&lt;?php $req = urldecode(basename($_SERVER['REQUEST_URI'])); list($f, $size) = explode('!', $req); list($size, $ext) = explode('.', $size); $size = intval($size); if (($size &gt; 2000) || ($size % 50 != 0)) die(); $f .= '.' . $ext; list($width, $height) = getimagesize($f); $src = imagecreatefromstring(file_get_contents($f)); $dst = imagescale($src, $size); imagejpeg($dst, $req); ?&gt; </code></pre> <p><strong>Question for code review: is there something to improve in terms of security?</strong></p> <p>Note: To avoid that someone requests <code>myimage!1.jpg</code>, <code>myimage!2.jpg</code>, ..., <code>myimage!1999.jpg</code>, <code>myimage!2000.jpg</code> in loop, filling the disk for nothing, the code only accepts size as integer mutiples of 50. At most 50 100 150 ... 1900 1950 2000 will be written, i.e. 40 versions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T19:25:27.513", "Id": "534591", "Score": "0", "body": "I added the `.htaccess` tag, because without understanding what that does you cannot understand the PHP code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T05:44:50.093", "Id": "534611", "Score": "1", "body": "Am I incorrect in reading that you would like help adding features to this script? I mean, it is not currently filtering/sanitizing/validating files the way you desire. We are not meant to bake new functionality in your supplied code as far as I know. When you know how many elements your explode should return, a limit parameter is a good idea. My mind went to `sscanf()` when I saw that you wanted an int val from the middle of the string." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T09:58:11.343", "Id": "270607", "Score": "1", "Tags": [ "php", "image", ".htaccess" ], "Title": "Serve rescaled jpg images on demand with myphoto!500.jpg syntax (here 500px-width rescaled)" }
270607
<p>I wrote a method that lets me retry RestSharp requests when a specific exception is thrown.<br /> Here's the code for that method:</p> <pre><code>private async Task&lt;T_Out&gt; RunRequestWithRetry&lt;T_In, T_Out&gt;(Func&lt;SignatureAccount, T_In, T_Out&gt; request, SignatureAccount signatureAccount, T_In requestBody) where T_Out : Task { try { var result = request.Invoke(signatureAccount, requestBody) as Task; await result; return result as T_Out; } catch (AMAApiException&lt;ErrorResult&gt; apiEx) { if (apiEx.ErrorType != AMAErrorType.TokenNeedsRefresh) throw apiEx; // Refresh Tokens var signatureAccountService = new SignatureAccountService(MvcApplication.Config); var newSignatureAccount = await signatureAccountService.UpdateTokens(signatureAccount); if (newSignatureAccount == null) throw apiEx; UpdateSignatureAccount = true; StorageService.SignatureAccount.SaveState(newSignatureAccount); return request.Invoke(newSignatureAccount, requestBody); } } </code></pre> <p>This works well enough since all the requests that'll be passing through this method have the same signature and all of them will return a <code>Task</code>.</p> <p>My only issue with this code is that I need to call <code>await</code> 2 when I call it, for example:</p> <pre><code>var credentialsListResponse = await await RunRequestWithRetry(GetCredentialsList, process.SignatureAccount, credentialsListBody); </code></pre> <p>I tried to return only the <code>T_Out</code> since I specified it to be of type <code>Task</code> but visual studio does not like that... So I had to wrap the return with a Task, but this makes my method return <code>Task&lt;Task&lt;Type&gt;&gt;</code>.</p> <p>Is there a way to make this more elegant, maybe remove one of the await calls.</p>
[]
[ { "body": "<p>Here are few suggestions :</p>\n<p>First, make a loop</p>\n<ul>\n<li>the readability is improved as you will see only <code>request.Invoke(signatureAccount, requestBody)</code> call in one place.</li>\n<li>you will get rid of the nested Task</li>\n<li>it will be more simple if your customer decide to ask 3 retries or more.</li>\n</ul>\n<p>Second, <code>RunRequestWithRetry</code> is fullfilling too much roles. It should focus only on retrying a request as its name suggest. Refreshing tokens have no place here. A trick could be passing a &quot;CleanupOnException&quot; task as argument that the caller should provide.</p>\n<p>Finally, if you can use some nuget packages, there is a very serious and popular one (top 7 non-microsoft nuget packages) which do exactly what you want in an elegant manner: <strong><a href=\"https://github.com/App-vNext/Polly\" rel=\"nofollow noreferrer\">Polly</a></strong>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T15:57:05.623", "Id": "534557", "Score": "0", "body": "Thank you for your sugestion, I dont really require do define a number of retries, I only need to retry once in case the token has expired, thats why the code to refresh the token is there, but I could it refresh the tokens in a separate method, anyways I managed to find a solution for the problem I was having." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T14:38:29.160", "Id": "270618", "ParentId": "270608", "Score": "3" } }, { "body": "<p>I found out what was wrong with my logic, it was quite a simple fix that solves the double await problem, I just needed to make the signature of the method Func&lt;SignatureAccount, T_In, Task&lt;T_Out&gt;&gt; this way the T_Out will be the correct type and I can return Task&lt;T_Out&gt;.</p>\n<p>I also took the advise by @Perfect28 and extracted the refreshToken logic to a new method called UpdateTokensAndRetry, this works for me since I only need to retry once after refreshing the tokens, since I only want to refresh when the tokens exipe.</p>\n<p>Here's the code sample with the solution:</p>\n<pre><code>private async Task&lt;T_Out&gt; RunRequestWithRetry&lt;T_In, T_Out&gt;(Func&lt;SignatureAccount, T_In, Task&lt;T_Out&gt;&gt; request, SignatureAccount signatureAccount, T_In requestBody)\n{\n try\n {\n return await request.Invoke(signatureAccount, requestBody);\n }\n catch (AMAApiException&lt;ErrorResult&gt; apiEx)\n {\n if (apiEx.ErrorType != AMAErrorType.TokenNeedsRefresh)\n throw apiEx;\n\n return await UpdateTokensAndRetry(request, signatureAccount, requestBody, apiEx);\n }\n}\n\nprivate async Task&lt;T_Out&gt; UpdateTokensAndRetry&lt;T_In, T_Out, T_Ex&gt;(Func&lt;SignatureAccount, T_In, Task&lt;T_Out&gt;&gt; request, SignatureAccount signatureAccount, T_In requestBody, T_Ex apiEx) where T_Ex : Exception\n{\n // Refresh Tokens\n var signatureAccountService = new SignatureAccountService(MvcApplication.Config);\n var newSignatureAccount = await signatureAccountService.UpdateTokens(signatureAccount);\n if (newSignatureAccount == null)\n throw apiEx;\n\n UpdateSignatureAccount = true;\n StorageService.SignatureAccount.SaveState(newSignatureAccount);\n return await request.Invoke(newSignatureAccount, requestBody);\n}\n</code></pre>\n<p>And now I can call the method like this:</p>\n<pre><code>var signHashesResponse = await RunRequestWithRetry(GetSignedHashes, process.SignatureAccount, signHashesRequest);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:17:23.007", "Id": "534564", "Score": "1", "body": "This answer is okay, but it might be better to delete it and ask a follow up question with a link pointing back to this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:42:31.400", "Id": "534570", "Score": "0", "body": "I'm sorry, I dont quite understand what you are trying to tell me, what follow up question should I make? I don't get why I should delete it?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:04:50.850", "Id": "270621", "ParentId": "270608", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T10:43:06.447", "Id": "270608", "Score": "0", "Tags": [ "c#", "generics", "async-await" ], "Title": "Retrying a RestRequest" }
270608
<p>This is a popular <a href="https://leetcode.com/problems/minimum-window-substring/" rel="nofollow noreferrer">question on LeetCode</a>:</p> <blockquote> <h3>76. Minimum Window Substring</h3> <p>Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string &quot;&quot;.</p> <p>The testcases will be generated such that the answer is unique.</p> <p>A substring is a contiguous sequence of characters within the string.</p> <p><strong>Example:</strong><br /> Input: s = &quot;ADOBECODEBANC&quot;, t = &quot;ABC&quot;<br /> Output: &quot;BANC&quot;<br /> Explanation: The minimum window substring &quot;BANC&quot; includes 'A', 'B', and 'C' from string t.</p> </blockquote> <p>I converted the <a href="https://leetcode.com/problems/minimum-window-substring/solution/" rel="nofollow noreferrer">java solution provided by LeetCode</a> to Swift since this is the language I am practicing in. Here is my code below:</p> <pre><code>func minWindowSlidingWindow(_ s: String, _ t: String) -&gt; String { if s == t { return s } var uniqueCharacterHashTable: [Character: Int] = [:] for character in t { if let countOfChar = uniqueCharacterHashTable[character] { uniqueCharacterHashTable[character] = countOfChar + 1 continue } uniqueCharacterHashTable[character] = 1 } let uniqueCharactersRequired = uniqueCharacterHashTable.keys.count var uniqueCharactersFormed = 0 var currentWindowCharacterHashTable: [Character: Int] = [:] var minSequenceSize = Int.max var minimumSequenceStart = 0 var minimumSequenceEnd = 0 var currentStartIndexInt = 0 var currentEndIndexInt = 0 while currentEndIndexInt &lt; s.count { let endIndex = s.index(s.startIndex, offsetBy: currentEndIndexInt) var currentCharacter = s[endIndex] if var characterCount = currentWindowCharacterHashTable[currentCharacter] { characterCount += 1 currentWindowCharacterHashTable[currentCharacter] = characterCount } else { currentWindowCharacterHashTable[currentCharacter] = 1 } if let _ = uniqueCharacterHashTable[currentCharacter], currentWindowCharacterHashTable[currentCharacter] == uniqueCharacterHashTable[currentCharacter] { uniqueCharactersFormed += 1 } while currentStartIndexInt &lt;= currentEndIndexInt &amp;&amp; uniqueCharactersFormed == uniqueCharactersRequired { let startIndex = s.index(s.startIndex, offsetBy: currentStartIndexInt) currentCharacter = s[startIndex] if minSequenceSize == Int.max || currentEndIndexInt - currentStartIndexInt + 1 &lt; minSequenceSize { minSequenceSize = currentEndIndexInt - currentStartIndexInt + 1 minimumSequenceStart = currentStartIndexInt minimumSequenceEnd = currentEndIndexInt } if let characterCountInWindow = currentWindowCharacterHashTable[currentCharacter] { currentWindowCharacterHashTable[currentCharacter] = characterCountInWindow - 1 } if let _ = uniqueCharacterHashTable[currentCharacter], let currentCharOriginalCount = uniqueCharacterHashTable[currentCharacter], let charInWindowCount = currentWindowCharacterHashTable[currentCharacter], currentCharOriginalCount &gt; charInWindowCount { uniqueCharactersFormed -= 1 } currentStartIndexInt += 1 } currentEndIndexInt += 1 } if minSequenceSize == Int.max { return &quot;&quot; } let startIndex = s.index(s.startIndex, offsetBy: minimumSequenceStart) let endIndex = s.index(s.startIndex, offsetBy: minimumSequenceEnd) return String(s[startIndex ... endIndex]) } </code></pre> <p>This works for the basic test cases and gives the desired output (as far as I know from about 10 test cases) but as the string size gets huge <a href="https://www.writeurl.com/text/p5apmxcatzvllpml3iz0/pb9tvcpq0v95227psk0l" rel="nofollow noreferrer">like 100,000 for example</a> - it gets super slow even though I use the same data structures (I think) as suggested in the Java solution.</p> <p>Can anyone point me as to where the bottleneck in this code lies and how could I optimize this further.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:41:24.950", "Id": "534526", "Score": "0", "body": "Seems like the paste is not yet approved, I have updated with a sample using another tool .. hope this works at your end." } ]
[ { "body": "<p>The main bottleneck is how characters of a string are accessed. A Swift <code>String</code> is a collection of <code>Character</code>s, and a <code>Character</code> represents a single extended grapheme cluster, which can be one or more Unicode scalars. That makes counting and index operations like</p>\n<pre><code>s.count\ns.index(s.startIndex, offsetBy: currentEndIndexInt)\ns.index(s.startIndex, offsetBy: currentStartIndexInt)\n</code></pre>\n<p>slow. Instead of repeatedly converting integers to string indices it is better to work with string indices directly. For example,</p>\n<pre><code>var currentEndIndexInt = 0\nwhile currentEndIndexInt &lt; s.count {\n let endIndex = s.index(s.startIndex, offsetBy: currentEndIndexInt)\n let currentCharacter = s[endIndex]\n // ...\n currentEndIndexInt += 1\n}\n</code></pre>\n<p>can be replaced by</p>\n<pre><code>var currentEndIndex = s.startIndex\nwhile currentEndIndex != s.endIndex {\n let currentCharacter = s[currentEndIndex]\n // ...\n s.formIndex(after: &amp;currentEndIndex)\n}\n</code></pre>\n<p>or even</p>\n<pre><code>for currentEndIndex in s.indices {\n var currentCharacter = s[currentEndIndex]\n // ...\n}\n</code></pre>\n<p>Other simplifications: Counting the number of occurrences of the characters in a string</p>\n<pre><code>var uniqueCharacterHashTable: [Character: Int] = [:]\nfor character in t {\n if let countOfChar = uniqueCharacterHashTable[character] {\n uniqueCharacterHashTable[character] = countOfChar + 1\n continue\n }\n uniqueCharacterHashTable[character] = 1\n}\n</code></pre>\n<p>can be done more concisely with <code>reduce(into:_:)</code> and dictionary subscripts with a default value:</p>\n<pre><code>let uniqueCharacterHashTable = t.reduce(into: [:]) {\n $0[$1, default: 0] += 1\n}\n</code></pre>\n<p>In the same spirit can</p>\n<pre><code>if var characterCount = currentWindowCharacterHashTable[currentCharacter] {\n characterCount += 1\n currentWindowCharacterHashTable[currentCharacter] = characterCount \n} else {\n currentWindowCharacterHashTable[currentCharacter] = 1 \n}\n</code></pre>\n<p>be shortened to</p>\n<pre><code>currentWindowCharacterHashTable[currentCharacter, default: 0] += 1\n</code></pre>\n<p>The <code>let _ = ...</code> test in</p>\n<pre><code>if let _ = uniqueCharacterHashTable[currentCharacter],\n currentWindowCharacterHashTable[currentCharacter] == uniqueCharacterHashTable[currentCharacter] { ... }\n</code></pre>\n<p>is not necessary because <code>nil</code> does always compare “not equal” to a non-nil value. The test for <code>Int.max</code> in</p>\n<pre><code>if minSequenceSize == Int.max || endIndexInt - currentStartIndexInt + 1 &lt; minSequenceSize { ... }\n</code></pre>\n<p>is not necessary. Finally the <code>let _ = ...</code> test in</p>\n<pre><code> if let _ = uniqueCharacterHashTable[currentCharacter],\n let currentCharOriginalCount = uniqueCharacterHashTable[currentCharacter],\n let charInWindowCount = currentWindowCharacterHashTable[currentCharacter],\n currentCharOriginalCount &gt; charInWindowCount { ... }\n</code></pre>\n<p>is not needed because the next line already does the optional assignment.</p>\n<p>Putting it all together, the code looks like this:</p>\n<pre><code>func minWindowSlidingWindow(_ s: String, _ t: String) -&gt; String {\n\n if s == t {\n return s\n }\n \n let uniqueCharacterHashTable = t.reduce(into: [:]) {\n $0[$1, default: 0] += 1\n }\n \n let uniqueCharactersRequired = uniqueCharacterHashTable.keys.count\n var uniqueCharactersFormed = 0\n \n var currentWindowCharacterHashTable: [Character: Int] = [:]\n \n var minSequenceSize = Int.max\n var minSequenceStart = s.startIndex\n var minSequenceEnd = s.startIndex\n\n var currentStartIndex = s.startIndex\n var currentWindowLength = 1\n \n for currentEndIndex in s.indices {\n var currentCharacter = s[currentEndIndex]\n currentWindowCharacterHashTable[currentCharacter, default: 0] += 1\n if currentWindowCharacterHashTable[currentCharacter] == uniqueCharacterHashTable[currentCharacter] {\n uniqueCharactersFormed += 1\n }\n \n while currentStartIndex &lt;= currentEndIndex &amp;&amp; uniqueCharactersFormed == uniqueCharactersRequired {\n currentCharacter = s[currentStartIndex]\n \n if currentWindowLength &lt; minSequenceSize {\n minSequenceSize = currentWindowLength\n minSequenceStart = currentStartIndex\n minSequenceEnd = currentEndIndex\n }\n if let characterCountInWindow = currentWindowCharacterHashTable[currentCharacter] {\n currentWindowCharacterHashTable[currentCharacter] = characterCountInWindow - 1\n }\n if let currentCharOriginalCount = uniqueCharacterHashTable[currentCharacter],\n let charInWindowCount = currentWindowCharacterHashTable[currentCharacter],\n currentCharOriginalCount &gt; charInWindowCount {\n uniqueCharactersFormed -= 1\n }\n s.formIndex(after: &amp;currentStartIndex)\n currentWindowLength -= 1\n }\n currentWindowLength += 1\n }\n \n if minSequenceSize == Int.max {\n return &quot;&quot;\n }\n \n return String(s[minSequenceStart...minSequenceEnd])\n}\n</code></pre>\n<p>Instead of dummy default values</p>\n<pre><code>var minSequenceStart = s.startIndex\nvar minSequenceEnd = s.startIndex\n</code></pre>\n<p>one can also use optionals, which are only assigned a value once a valid window is found.</p>\n<p>Otherwise your code is written clearly. I would perhaps use slightly shorter variables names at some places, but that is a matter of taste.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:07:40.877", "Id": "534519", "Score": "1", "body": "If anyone wonders why the answer was written only minutes after the question is posted: The question was originally posted on Stack Overflow, so I was prepared :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:52:43.663", "Id": "534530", "Score": "0", "body": "Thanks a lot @Martin R .. the improvements are something I would not have though on my own especially the bit about using string indices directly rather than converting the int indices to string indices - got to learn something new today. Submitting with these changes is accepted on LeetCode. Thank you !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T12:13:45.557", "Id": "534532", "Score": "0", "body": "You are welcome. Working with string indices directly works quite well here because the characters are accessed sequentially from start to end. Another option is to convert the string to an array of characters once `let sArray = Array(s)` because array indexing is fast and done with integer indices. That needs extra memory, but can be useful if you need random access to the characters of a string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T12:25:55.967", "Id": "534533", "Score": "0", "body": "@ShawnFrank: I just realized that I had answered a similar question before. Have a look at https://codereview.stackexchange.com/q/233978/35991 for some tips to make the code even Swiftier :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T15:14:07.420", "Id": "534546", "Score": "0", "body": "Your other answer was really helpful as well. I am practicing for interviews so I keep my code a little less swifty sometimes as I tend to get confused sometimes. Finally, your suggestion for Array(s) is great as it was something I was unaware of. Really useful and thank you for taking your time to help me today .. much appreciated Martin." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:06:28.527", "Id": "270611", "ParentId": "270609", "Score": "1" } } ]
{ "AcceptedAnswerId": "270611", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T10:58:24.130", "Id": "270609", "Score": "1", "Tags": [ "programming-challenge", "time-limit-exceeded", "swift" ], "Title": "Minimum Window Substring in Swift exceeds LeetCode runtime check" }
270609
<p>I am doing the Advent of Code challenge to learn Rust (obviously there may be spoilers if you still want to do the challenge).</p> <p>The instructions are too long to include verbatim so I will <a href="https://adventofcode.com/2021/day/1" rel="nofollow noreferrer">link them</a> and give a summary for the two parts.</p> <p>In part 1, the programme must compare a user-provided list of integers and count every time the number is bigger than the previous one. The output is the total number of increases.</p> <p>In part 2, the programme is modified to compare the sum of the last three numbers with the previous sum.</p> <p>I am particularly interested in how I can write more idiomatic Rust. Whenever I ran into an error, I just hacked at it until it stopped complaining but I'm sure there's a better way. Some tips that I'm looking for (but not limited to) are:</p> <ul> <li>When to use mutators and when not to.</li> <li>How to handle errors better.</li> <li>Boiler-plate code removal and style tips</li> </ul> <p>Please include an example of the right way to do something. I can tell that I've taken more liberties than I need to with certain parts but I don't know what a better way looks like. So just telling me that something is wrong might not help.</p> <h1>Part 1</h1> <pre class="lang-rust prettyprint-override"><code>use std::fs::File; use std::io::{BufRead, BufReader}; use std::env; fn main() { let mut count: u16 = 0; let mut last: u16 = 0; let args: Vec&lt;String&gt; = env::args().collect(); let filename = args.get(1).unwrap_or_else(|| panic!(&quot;Please provide file name&quot;)); let file = File::open(filename).unwrap_or_else(|_| panic!(&quot;Couldn't open file {}&quot;, filename)); let reader = BufReader::new(file); for (index, line) in reader.lines().enumerate() { let line = line.unwrap(); if line.trim().is_empty() {continue;} if last &lt; line.parse().unwrap() &amp;&amp; index != 0 { count += 1; println!(&quot;{} (increased)&quot;, line); } else { println!(&quot;{}&quot;, line); } last = line.parse().unwrap(); } println!(&quot;Increase count: {}&quot;, count); } </code></pre> <h1>Part 2</h1> <pre class="lang-rust prettyprint-override"><code>use std::fs::File; use std::io::{BufRead, BufReader}; use std::env; fn main() { let mut count: u16 = 0; let mut curr:Vec&lt;u16&gt; = Vec::new(); let mut last:Vec&lt;u16&gt; = Vec::new(); //-------- let args: Vec&lt;String&gt; = env::args().collect(); let filename = args.get(1).unwrap_or_else(|| panic!(&quot;Please provide file name&quot;)); let file = File::open(filename).unwrap_or_else(|_| panic!(&quot;Couldn't open file {}&quot;, filename)); let reader = BufReader::new(file); //-------- for (index, line) in reader.lines().enumerate() { let line = line.unwrap(); if line.trim().is_empty() {continue;} last = curr.to_vec(); curr.push(line.parse().unwrap()); if curr.len() &gt; 3 { curr.remove(0); } let curr_sum:u16 = curr.iter().sum(); let last_sum:u16 = last.iter().sum(); if last_sum &lt; curr_sum &amp;&amp; index &gt;= 3 { count += 1; println!(&quot;{} (increased)&quot;, line); } else { println!(&quot;{}&quot;, line); } } println!(&quot;Curr: {:?}&quot;, curr); println!(&quot;Last: {:?}&quot;, last); println!(&quot;Increase count: {}&quot;, count); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T12:58:57.363", "Id": "534537", "Score": "0", "body": "Please summarise the _objective_ in the question title and description, so that the question has value even when the linked resource is not accessible. Thanks!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:04:31.637", "Id": "270610", "Score": "2", "Tags": [ "programming-challenge", "rust" ], "Title": "Advent of Code 2021: day 1" }
270610
<p>I have the following code, like a git command line system with various supported parameters and commands. But as can be seen, it involves a lot of if-else conditions which<br> It doesn't seem that clean and is error-prone. Could there be a way to restructure it using some design pattern<br><br></p> <pre><code>public static void main(String... args) { String firstParam; try { firstParam = args[0]; } catch (ArrayIndexOutOfBoundsException e) { System.out.println(&quot;Please enter a command.&quot;); return; } String secondParam = null; String thirdParam = null; String fourthParam = null; if (args.length &gt; 1) { secondParam = args[1]; } if (args.length &gt; 2) { thirdParam = args[2]; } if (args.length &gt; 3) { fourthParam = args[3]; } git git = new git(); if (firstParam.equals(&quot;init&quot;)) { git.init(); } else if (!git.getWorkingdirectory().exists()) { System.out.println(&quot;not initialized&quot;); } else if (firstParam.equals(&quot;status&quot;)) { git.status(); } else if (firstParam.equals(&quot;log&quot;)) { git.log(); } else if (firstParam.equals(&quot;global-log&quot;)) { git.globalLog(); } else if (secondParam == null) { System.out.println(&quot;Incorreerands.&quot;); } else if (firstParam.equals(&quot;add&quot;)) { git.add(secondParam); } else if (firstParam.equals(&quot;rm&quot;)) { </code></pre> <br> <p><strong>Reasoning:</strong> <br> The first thing that comes to my mind is making a class out of each command. That's probably called command pattern. So there will be a class corresponding to - add, rm, status, log, etc.. all the supported arguments to the git command. I am planning to include around 13 such git commands to be specified as a command-line option. That will be like 13 classes.<br> Not sure if that is a good approach, or could there be any other approach?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T12:57:29.400", "Id": "534535", "Score": "4", "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-12-02T15:40:20.757", "Id": "534551", "Score": "1", "body": "A git wrapper. Why do you need this? (depending on the context, my answer might be different) ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T15:44:32.710", "Id": "534555", "Score": "0", "body": "@JohannesKlug It was an assignment. I have done the coding just using it to learn to code well and include design patterns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:13:02.107", "Id": "534562", "Score": "2", "body": "Is there more code in `main`? If so, would you please post it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:14:40.463", "Id": "534563", "Score": "0", "body": "@pacmaninbw Nopes that's all just 2-3 more if statement of the same kind" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T20:06:11.233", "Id": "534593", "Score": "0", "body": "(With posts in \"markdown\", you don't need `<br/>`: Follow the post editing help and append two spaces to line you want a break after.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T16:04:42.650", "Id": "534660", "Score": "0", "body": "You're extracting `thirdParam` and `fourthParam`, but you don't seem to use them anywhere." } ]
[ { "body": "<p>I was half inclined not to answer. As others said this question could be improved to better fit the forum.</p>\n<p>However there's enough here IMHO to warrant an answer.</p>\n<p>Firstly, don't worry about patterns at this point. There's more fundamental issues to look at.</p>\n<p>Names like <code>firstparam</code> etc are unhelpful - you could almost as well call them <code>x</code> <code>y</code> and <code>z</code>. The first parameter is the name of the git command or subcommand (I'm not sure of nomenclature for git) so name the variable accordingly.</p>\n<p>You don't need most of the parameters before you've decided what operation you're performing, so don't get them till then.</p>\n<p>Move your different operations to separate methods, for a start - one for init, one for log and so on. If you move the checking for initialization to a method (throwing RuntimeException for errors, perhaps) and use it where necessary you can have a uniform pattern for processing subcommands, which is often clearer.</p>\n<p>You could replace your <code>if ... else if ...</code> structure with a <code>switch</code> in modern Java, which would be neater, but neater still (in my view) is to abstract the commands out into some objects for executing them.</p>\n<p>My example does this, and to make it easy to map from subcommands to the the object that will execute them I use a Java enum - <code>GitOperation</code>. All GitOperations need to implement the abstract method <code>execute</code> which takes a <code>Git</code> object as its first parameter and the array of command-line arguments as its second.</p>\n<p>There's a static method in the enum to fetch a GitOperation by its name (I use a sequential search as the set of operations is fairly small, if it were larger, I'd build a Map as part of the enum static initialization).</p>\n<p>I've used a dummy <code>Git</code> object just to make my code compile. Naturally this is untested, but it may be an interesting perspective on the exercise.</p>\n<pre><code>import java.io.File;\n\npublic class GitLike {\n\n /**\n * Dummy class full of stubbed methods\n */\n public static class Git {\n\n public void init() {}\n\n public File getWorkingdirectory() {\n return new File(&quot;.&quot;);\n }\n\n public void status() {}\n\n public void log() {}\n\n public void globalLog() {}\n\n public void add(String fileName) {}\n\n public void rm(String fileName) {}\n }\n\n private enum GitOperation {\n INIT(&quot;init&quot;) {\n @Override\n protected void execute(Git git, String[] args) {\n git.init();\n }\n }, //\n STATUS(&quot;status&quot;) {\n @Override\n protected void execute(Git git, String[] args) {\n requireGitInitialized(git);\n git.status();\n }\n }, //\n LOG(&quot;log&quot;) {\n @Override\n protected void execute(Git git, String[] args) {\n requireGitInitialized(git);\n git.log();\n }\n }, //\n GLOBALLOG(&quot;global-log&quot;) {\n @Override\n protected void execute(Git git, String[] args) {\n requireGitInitialized(git);\n git.globalLog();\n }\n }, //\n ADD(&quot;add&quot;) {\n @Override\n protected void execute(Git git, String[] args) {\n requireGitInitialized(git);\n String fileName = getArg(args, 1);\n git.add(fileName);\n }\n }, //\n RM(&quot;rm&quot;) {\n @Override\n protected void execute(Git git, String[] args) {\n requireGitInitialized(git);\n String fileName = getArg(args, 1);\n git.rm(fileName);\n }\n };\n\n private static void requireGitInitialized(Git git) {\n if (!git.getWorkingdirectory().exists()) {\n throw new RuntimeException(&quot;not initialized&quot;);\n }\n }\n\n private static String getArg(String[] args, int argNumber) {\n if (args.length &lt; (argNumber + 1)) {\n throw new IllegalArgumentException(&quot;Argument &quot; + argNumber + &quot; is required&quot;);\n }\n return args[argNumber];\n }\n\n private String subCommandName;\n\n private GitOperation(String subCommandName) {\n this.subCommandName = subCommandName;\n }\n\n protected abstract void execute(Git git, String[] args);\n\n public static GitOperation bySubCommandName(String subCommandName) {\n for (GitOperation operation : values()) {\n if (operation.subCommandName.equalsIgnoreCase(subCommandName)) {\n return operation;\n }\n }\n return null;\n }\n }\n\n public static void main(String... args) {\n String subCommand;\n try {\n subCommand = args[0];\n }\n catch (ArrayIndexOutOfBoundsException e) {\n System.out.println(&quot;Please enter a command.&quot;);\n return;\n }\n\n Git git = new Git();\n\n GitOperation operation = GitOperation.bySubCommandName(subCommand);\n if (operation != null) {\n operation.execute(git, args);\n }\n else {\n throw new IllegalArgumentException(&quot;Git subcommand '&quot; + subCommand + &quot;' was not recognized&quot;);\n }\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:32:06.933", "Id": "270622", "ParentId": "270612", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:19:26.803", "Id": "270612", "Score": "-2", "Tags": [ "java", "design-patterns" ], "Title": "Refactoring existing code with some design pattern" }
270612
<p>I'm trying to write idiomatic and fast Rust code by solving AoC challenges this year! :-)</p> <p><a href="https://adventofcode.com/2021/day/2" rel="nofollow noreferrer">Link to AoC Day 2 problem</a></p> <p>The input format in this problem is a list of lines each containing one string token (one of <code>forward/down/up</code>) and one integer, separated by whitespace. The number of lines is not known in advance. Example:</p> <pre><code>forward 5 down 5 forward 8 up 3 down 8 forward 2 </code></pre> <p>This is my Rust code for taking input:</p> <pre class="lang-rust prettyprint-override"><code>use std::{ fs::File, io::{BufRead, BufReader, Result as io_result}, }; enum Action { F, D, U, } fn read_inputs() -&gt; io_result&lt;Vec&lt;(Action, u32)&gt;&gt; { let input_file = File::open(&quot;inputs/2.txt&quot;)?; let file_reader = BufReader::new(input_file); let inputs = file_reader .lines() .map(|line| { let line_res = line.unwrap(); let mut res = line_res.split(&quot; &quot;); let (action, value) = (res.next().unwrap(), res.next().unwrap()); return { ( { if action == &quot;forward&quot; { Action::F } else { if action == &quot;down&quot; { Action::D } else { Action::U } } }, value.parse().unwrap(), ) }; }) .collect::&lt;Vec&lt;(Action, u32)&gt;&gt;(); return Ok(inputs); } </code></pre> <p>I'm unsure about my code for a number of reasons:</p> <ol> <li>Four unwraps in a single closure. If we could reduce the unwraps on <code>res.next()</code>, perhaps by specifying the line is guaranteed to contain a tuple of two tokens, it would be great.</li> <li>The nesting depth of the ternary if-else is exceedingly high, not sure how to better it though.</li> <li>Perhaps if this was a very large file, would using <code>.lines()</code> still be reasonable or could we make this code faster? (preferably relying on Rust's zero cost abstractions)</li> </ol> <p>Looking forward to advise on this code along these points and any other point as you deem fit.</p> <hr /> <p>The part of my code which solves the actual problem, I'm pretty happy with that honestly because I got to use a <code>match</code> clause :-) Still if there's anything that could be improved here, in terms of idiomatic or faster Rust, please do advise!</p> <pre><code>fn part1(inputs: &amp;Vec&lt;(Action, u32)&gt;) -&gt; u32 { let (mut horizontal, mut depth): (u32, u32) = (0, 0); for (action, movement) in inputs { match action { Action::F =&gt; { horizontal += movement; } Action::D =&gt; { depth += movement; } Action::U =&gt; { depth -= movement; } } } return horizontal * depth; } fn main() { let inputs = read_inputs().expect(&quot;Input read correctly&quot;); let answer = part1(&amp;inputs); println!(&quot;Answer: {}&quot;, answer) } </code></pre>
[]
[ { "body": "<ol>\n<li>Let's address this</li>\n<li>Let's address this too</li>\n<li>I looked up the definition of <code>io::Lines</code>, its overhead is one heap allocation per line, so the cost is small but real. <code>buf.read_line</code> with a reused <code>String</code> would be slightly faster.</li>\n</ol>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code> let inputs = file_reader\n .lines()\n .map(|line| {\n let line_res = line.unwrap();\n // what if the line is empty?\n let mut res = line_res.split(&quot; &quot;);\n // multiple unwraps, kill 'em all with one match in functional style\n let (action, value) = (res.next().unwrap(), res.next().unwrap());\n return {\n (\n {\n // let's factor out this logic, makes sense to put it in another self-contained function\n // because it's a piece of logic related only to Action\n if action == &quot;forward&quot; {\n Action::F\n } else {\n if action == &quot;down&quot; {\n Action::D\n } else {\n Action::U\n }\n }\n },\n value.parse().unwrap(),\n )\n };\n })\n</code></pre>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>// kill all unwraps. Check three items for good measure.\nmatch (res.next(), res.next(), res.next()) { /* ... */ }\n</code></pre>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code>// factored out our action parsing logic\nimpl FromStr for Action {\n type Err = ();\n\n fn from_str(input: &amp;str) -&gt; Result&lt;Action, Self::Err&gt; {\n match input {\n &quot;forward&quot; =&gt; Ok(Action::F),\n &quot;down&quot; =&gt; Ok(Action::D),\n &quot;up&quot; =&gt; Ok(Action::U),\n _ =&gt; Err(()),\n }\n }\n}\n</code></pre>\n<pre class=\"lang-rust prettyprint-override\"><code>// new import\nuse std::{\n /* ... */\n str::FromStr,\n};\n</code></pre>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code> // ignore empty line\n // helps with empty lines and files ending with newline\n if line_res.is_empty() { return None; }\n</code></pre>\n<pre class=\"lang-rust prettyprint-override\"><code> // changing our `map` into `filter_map` for ignoring empty lines\n .lines()\n .filter_map(|line| {\n</code></pre>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code> // let's match on correct input and fail otherwise\n match (res.next(), res.next(), res.next()) {\n // meaningful line\n (Some(action), Some(movement), None) =&gt; { ... }\n // incorrect input\n _ =&gt; panic!(&quot;incorrect input line: '{}'&quot;, line_res),\n }\n</code></pre>\n<hr />\n<pre class=\"lang-rust prettyprint-override\"><code> // prepare our functions up front in functional style\n // parsing\n let parse_action = Action::from_str;\n let parse_movement = |movement: &amp;str| movement.parse();\n</code></pre>\n<pre class=\"lang-rust prettyprint-override\"><code> // processing\n match (res.next().map(parse_action), res.next().map(parse_movement), res.next()) {\n // meaningful line\n (Some(Ok(action)), Some(Ok(movement)), None) =&gt; {\n Some((action, movement))\n }\n // incorrect input\n _ =&gt; panic!(&quot;incorrect input line: '{}'&quot;, line_res),\n }\n</code></pre>\n<h2>Full code</h2>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::{\n fs::File,\n io::{BufRead, BufReader, Result as io_result},\n str::FromStr,\n};\n\nenum Action {\n F,\n D,\n U,\n}\n\nimpl FromStr for Action {\n type Err = ();\n\n fn from_str(input: &amp;str) -&gt; Result&lt;Action, Self::Err&gt; {\n match input {\n &quot;forward&quot; =&gt; Ok(Action::F),\n &quot;down&quot; =&gt; Ok(Action::D),\n &quot;up&quot; =&gt; Ok(Action::U),\n _ =&gt; Err(()),\n }\n }\n}\n\nfn read_inputs() -&gt; io_result&lt;Vec&lt;(Action, u32)&gt;&gt; {\n let input_file = File::open(&quot;inputs/2.txt&quot;)?;\n let file_reader = BufReader::new(input_file);\n let inputs = file_reader\n .lines()\n .filter_map(|line| {\n let line_res = line.ok()?;\n // empty line\n if line_res.is_empty() { return None; }\n let mut res = line_res.split(&quot; &quot;);\n // parsing\n let parse_action = Action::from_str;\n let parse_movement = |movement: &amp;str| movement.parse();\n // processing\n match (res.next().map(parse_action), res.next().map(parse_movement), res.next()) {\n // meaningful line\n (Some(Ok(action)), Some(Ok(movement)), None) =&gt; {\n Some((action, movement))\n }\n // incorrect input\n _ =&gt; panic!(&quot;incorrect input line: '{}'&quot;, line_res),\n }\n })\n .collect::&lt;Vec&lt;(Action, u32)&gt;&gt;();\n return Ok(inputs);\n}\n\nfn part1(inputs: &amp;Vec&lt;(Action, u32)&gt;) -&gt; u32 {\n let (mut horizontal, mut depth): (u32, u32) = (0, 0);\n\n for (action, movement) in inputs {\n match action {\n Action::F =&gt; {\n horizontal += movement;\n }\n Action::D =&gt; {\n depth += movement;\n }\n Action::U =&gt; {\n depth -= movement;\n }\n }\n }\n\n return horizontal * depth;\n}\n\nfn main() {\n let inputs = read_inputs().expect(&quot;Input read correctly&quot;);\n let answer = part1(&amp;inputs);\n println!(&quot;Answer: {}&quot;, answer)\n}\n</code></pre>\n<h2>Full solution with parse-display crate</h2>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::{\n fs::File,\n io::{BufRead, BufReader, Result as io_result},\n // str::FromStr,\n};\n\nuse parse_display::{Display, FromStr};\n\n#[derive(Display, FromStr)]\n#[display(&quot;{action} {movement}&quot;)]\nstruct Step {\n action: Action,\n movement: u32,\n}\n\n#[derive(Display, FromStr)]\nenum Action {\n #[display(&quot;forward&quot;)]\n F,\n #[display(&quot;down&quot;)]\n D,\n #[display(&quot;up&quot;)]\n U,\n}\n\nfn read_inputs() -&gt; io_result&lt;Vec&lt;Step&gt;&gt; {\n let input_file = File::open(&quot;inputs/2.txt&quot;)?;\n let file_reader = BufReader::new(input_file);\n let inputs = file_reader\n .lines()\n .filter_map(|line| {\n let line_res = line.ok()?;\n // empty line\n if line_res.is_empty() { return None; }\n let res: Step = line_res.parse().expect(&quot;incorrect input line&quot;);\n Some(res)\n })\n .collect::&lt;Vec&lt;Step&gt;&gt;();\n return Ok(inputs);\n}\n\nfn part1(inputs: &amp;Vec&lt;Step&gt;) -&gt; u32 {\n let (mut horizontal, mut depth): (u32, u32) = (0, 0);\n\n for step in inputs {\n match step.action {\n Action::F =&gt; {\n horizontal += step.movement;\n }\n Action::D =&gt; {\n depth += step.movement;\n }\n Action::U =&gt; {\n depth -= step.movement;\n }\n }\n }\n\n return horizontal * depth;\n}\n\nfn main() {\n let inputs = read_inputs().expect(&quot;Input read correctly&quot;);\n let answer = part1(&amp;inputs);\n println!(&quot;Answer: {}&quot;, answer)\n}\n</code></pre>\n<h2>Conclusion</h2>\n<ul>\n<li>Idiomatic, terse and fast Rust is often functional. Get to know functional style.</li>\n<li>know your crates</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T06:13:36.770", "Id": "270643", "ParentId": "270613", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T11:46:57.423", "Id": "270613", "Score": "2", "Tags": [ "programming-challenge", "rust" ], "Title": "Reading input in idiomatic Rust for Advent of Code Day 2" }
270613
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a>, <a href="https://codereview.stackexchange.com/a/253853/231235">A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++</a>, <a href="https://codereview.stackexchange.com/q/257757/231235">A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/269376/231235">A recursive_depth function for calculating depth of nested types implementation in C++</a>. Considering that the previous <code>std::for_each</code> version <code>recursive_transform</code> doesn’t ensure deterministic behavior, the individual <code>result</code>s could be emplaced into the <code>output</code> container in an arbitrary order because of the multiple factors. Therefore, another version <code>recursive_transform</code> template function which is order guaranteed and <code>unwrap_level</code> controlled has been proposed in this post.</p> <p><strong>The experimental implementation</strong></p> <ul> <li><p>Order guaranteed <code>recursive_transform</code> template function implementation:</p> <pre><code>// recursive_invoke_result_t implementation template&lt;std::size_t, typename, typename&gt; struct recursive_invoke_result { }; template&lt;typename T, typename F&gt; struct recursive_invoke_result&lt;0, F, T&gt; { using type = std::invoke_result_t&lt;F, T&gt;; }; template&lt;std::size_t unwrap_level, typename F, template&lt;typename...&gt; typename Container, typename... Ts&gt; requires (std::ranges::input_range&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; requires { typename recursive_invoke_result&lt;unwrap_level - 1, F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type; }) struct recursive_invoke_result&lt;unwrap_level, F, Container&lt;Ts...&gt;&gt; { using type = Container&lt;typename recursive_invoke_result&lt;unwrap_level - 1, F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type&gt;; }; template&lt;std::size_t unwrap_level, typename F, typename T&gt; using recursive_invoke_result_t = typename recursive_invoke_result&lt;unwrap_level, F, T&gt;::type; // recursive_variadic_invoke_result_t implementation template&lt;std::size_t, typename, typename, typename...&gt; struct recursive_variadic_invoke_result { }; template&lt;typename F, class...Ts1, template&lt;class...&gt;class Container1, typename... Ts&gt; struct recursive_variadic_invoke_result&lt;1, F, Container1&lt;Ts1...&gt;, Ts...&gt; { using type = Container1&lt;std::invoke_result_t&lt;F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;...&gt;&gt;; }; template&lt;std::size_t unwrap_level, typename F, class...Ts1, template&lt;class...&gt;class Container1, typename... Ts&gt; requires ( std::ranges::input_range&lt;Container1&lt;Ts1...&gt;&gt; &amp;&amp; requires { typename recursive_variadic_invoke_result&lt; unwrap_level - 1, F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;...&gt;::type; }) // The rest arguments are ranges struct recursive_variadic_invoke_result&lt;unwrap_level, F, Container1&lt;Ts1...&gt;, Ts...&gt; { using type = Container1&lt; typename recursive_variadic_invoke_result&lt; unwrap_level - 1, F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;... &gt;::type&gt;; }; template&lt;std::size_t unwrap_level, typename F, typename T1, typename... Ts&gt; using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result&lt;unwrap_level, F, T1, Ts...&gt;::type; template&lt;typename OutputIt, typename NAryOperation, typename InputIt, typename... InputIts&gt; OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) { while (first != last) { *d_first++ = op(*first++, (*rest++)...); } return d_first; } // recursive_transform for the multiple parameters cases (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, class F, class Arg1, class... Args&gt; constexpr auto recursive_transform(const F&amp; f, const Arg1&amp; arg1, const Args&amp;... args) { if constexpr (unwrap_level &gt; 0) { static_assert(unwrap_level &lt;= recursive_depth&lt;Arg1&gt;(), &quot;unwrap level higher than recursion depth of input&quot;); recursive_variadic_invoke_result_t&lt;unwrap_level, F, Arg1, Args...&gt; output{}; transform( std::inserter(output, std::ranges::end(output)), [&amp;f](auto&amp;&amp; element1, auto&amp;&amp;... elements) { return recursive_transform&lt;unwrap_level - 1&gt;(f, element1, elements...); }, std::ranges::cbegin(arg1), std::ranges::cend(arg1), std::ranges::cbegin(args)... ); return output; } else { return f(arg1, args...); } } // recursive_transform implementation (the version with unwrap_level, with execution policy) template&lt;std::size_t unwrap_level = 1, class ExPo, class T, class F&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) constexpr auto recursive_transform(ExPo execution_policy, const F&amp; f, const T&amp; input) { if constexpr (unwrap_level &gt; 0) { static_assert(unwrap_level &lt;= recursive_depth&lt;T&gt;(), &quot;unwrap level higher than recursion depth of input&quot;); recursive_invoke_result_t&lt;unwrap_level, F, T&gt; output{}; output.resize(input.size()); std::mutex mutex; std::transform(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output), [&amp;](auto&amp;&amp; element) { std::lock_guard lock(mutex); return recursive_transform&lt;unwrap_level - 1&gt;(execution_policy, f, element); }); return output; } else { return f(input); } } </code></pre> </li> </ul> <p><strong>Full Testing Code</strong></p> <p>The full testing code:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;concepts&gt; #include &lt;execution&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;ranges&gt; #include &lt;string&gt; #include &lt;vector&gt; // recursive_depth function implementation template&lt;typename T&gt; constexpr std::size_t recursive_depth() { return 0; } template&lt;std::ranges::input_range Range&gt; constexpr std::size_t recursive_depth() { return recursive_depth&lt;std::ranges::range_value_t&lt;Range&gt;&gt;() + 1; } // recursive_invoke_result_t implementation template&lt;std::size_t, typename, typename&gt; struct recursive_invoke_result { }; template&lt;typename T, typename F&gt; struct recursive_invoke_result&lt;0, F, T&gt; { using type = std::invoke_result_t&lt;F, T&gt;; }; template&lt;std::size_t unwrap_level, typename F, template&lt;typename...&gt; typename Container, typename... Ts&gt; requires (std::ranges::input_range&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; requires { typename recursive_invoke_result&lt;unwrap_level - 1, F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type; }) struct recursive_invoke_result&lt;unwrap_level, F, Container&lt;Ts...&gt;&gt; { using type = Container&lt;typename recursive_invoke_result&lt;unwrap_level - 1, F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type&gt;; }; template&lt;std::size_t unwrap_level, typename F, typename T&gt; using recursive_invoke_result_t = typename recursive_invoke_result&lt;unwrap_level, F, T&gt;::type; // recursive_variadic_invoke_result_t implementation template&lt;std::size_t, typename, typename, typename...&gt; struct recursive_variadic_invoke_result { }; template&lt;typename F, class...Ts1, template&lt;class...&gt;class Container1, typename... Ts&gt; struct recursive_variadic_invoke_result&lt;1, F, Container1&lt;Ts1...&gt;, Ts...&gt; { using type = Container1&lt;std::invoke_result_t&lt;F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;...&gt;&gt;; }; template&lt;std::size_t unwrap_level, typename F, class...Ts1, template&lt;class...&gt;class Container1, typename... Ts&gt; requires ( std::ranges::input_range&lt;Container1&lt;Ts1...&gt;&gt; &amp;&amp; requires { typename recursive_variadic_invoke_result&lt; unwrap_level - 1, F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;...&gt;::type; }) // The rest arguments are ranges struct recursive_variadic_invoke_result&lt;unwrap_level, F, Container1&lt;Ts1...&gt;, Ts...&gt; { using type = Container1&lt; typename recursive_variadic_invoke_result&lt; unwrap_level - 1, F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;... &gt;::type&gt;; }; template&lt;std::size_t unwrap_level, typename F, typename T1, typename... Ts&gt; using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result&lt;unwrap_level, F, T1, Ts...&gt;::type; template&lt;typename OutputIt, typename NAryOperation, typename InputIt, typename... InputIts&gt; OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) { while (first != last) { *d_first++ = op(*first++, (*rest++)...); } return d_first; } // recursive_transform for the multiple parameters cases (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, class F, class Arg1, class... Args&gt; constexpr auto recursive_transform(const F&amp; f, const Arg1&amp; arg1, const Args&amp;... args) { if constexpr (unwrap_level &gt; 0) { static_assert(unwrap_level &lt;= recursive_depth&lt;Arg1&gt;(), &quot;unwrap level higher than recursion depth of input&quot;); recursive_variadic_invoke_result_t&lt;unwrap_level, F, Arg1, Args...&gt; output{}; transform( std::inserter(output, std::ranges::end(output)), [&amp;f](auto&amp;&amp; element1, auto&amp;&amp;... elements) { return recursive_transform&lt;unwrap_level - 1&gt;(f, element1, elements...); }, std::ranges::cbegin(arg1), std::ranges::cend(arg1), std::ranges::cbegin(args)... ); return output; } else { return f(arg1, args...); } } // recursive_transform implementation (the version with unwrap_level, with execution policy) template&lt;std::size_t unwrap_level = 1, class ExPo, class T, class F&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) constexpr auto recursive_transform(ExPo execution_policy, const F&amp; f, const T&amp; input) { if constexpr (unwrap_level &gt; 0) { static_assert(unwrap_level &lt;= recursive_depth&lt;T&gt;(), &quot;unwrap level higher than recursion depth of input&quot;); recursive_invoke_result_t&lt;unwrap_level, F, T&gt; output{}; output.resize(input.size()); std::mutex mutex; std::transform(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output), [&amp;](auto&amp;&amp; element) { std::lock_guard lock(mutex); return recursive_transform&lt;unwrap_level - 1&gt;(execution_policy, f, element); }); return output; } else { return f(input); } } template&lt;std::size_t dim, class T&gt; constexpr auto n_dim_vector_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_vector_generator&lt;dim - 1&gt;(input, times); std::vector&lt;decltype(element)&gt; output(times, element); return output; } } void recursiveTransformTest(); int main() { recursiveTransformTest(); return 0; } void recursiveTransformTest() { for (std::size_t N = 1; N &lt; 10; N++) { std::size_t N1 = N, N2 = N, N3 = N; auto test_vector = n_dim_vector_generator&lt;3&gt;(0, 10); for (std::size_t z = 1; z &lt;= N3; z++) { for (std::size_t y = 1; y &lt;= N2; y++) { for (std::size_t x = 1; x &lt;= N1; x++) { test_vector.at(z - 1).at(y - 1).at(x - 1) = x * 100 + y * 10 + z; } } } auto expected = recursive_transform&lt;3&gt;([](auto&amp;&amp; element) {return element + 1; }, test_vector); auto actual = recursive_transform&lt;3&gt;(std::execution::par, [](auto&amp;&amp; element) {return element + 1; }, test_vector); std::cout &lt;&lt; &quot;N = &quot; &lt;&lt; N &lt;&lt; &quot;: &quot; &lt;&lt; std::to_string(actual == expected) &lt;&lt; '\n'; } } </code></pre> <p>The output of the testing code above:</p> <pre><code>N = 1: 1 N = 2: 1 N = 3: 1 N = 4: 1 N = 5: 1 N = 6: 1 N = 7: 1 N = 8: 1 N = 9: 1 </code></pre> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a>,</p> <p><a href="https://codereview.stackexchange.com/a/253853/231235">A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++</a>,</p> <p><a href="https://codereview.stackexchange.com/q/257757/231235">A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/269376/231235">A recursive_depth function for calculating depth of nested types implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am attempting to propose a order guaranteed, <code>unwrap_level</code> controlled <code>recursive_transform</code> template function implementation with execution policy.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T12:09:06.043", "Id": "270615", "Score": "3", "Tags": [ "c++", "recursion", "template", "concurrency", "c++20" ], "Title": "Order guaranteed recursive_transform template function implementation with execution policy in C++" }
270615
<p>I need help refactoring the following code using something simpler: <br></p> <pre><code> HashMap&lt;String, Blob&gt; blobmap = new HashMap&lt;&gt;(); blobmap.putAll(brLast.getParentTracked()); for (Blob blob : blobmap.values()) { Blob t; try { t = brCommit.getBlobHashMap().get(blob.getFileName()); } catch (NullPointerException e) { t = null; } if (t == null &amp;&amp; blob.getDirectory().isFile()) { blob.getDirectory().delete(); } } </code></pre> <p>Is there a way to shorten the code?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T15:04:24.530", "Id": "270619", "Score": "0", "Tags": [ "java" ], "Title": "converting iteration of maps to streams" }
270619
<p>When fridays_135 is called, a list of dates between the start date and end date is produces by date_range. That list is then narrowed down to just the Friday dates and then grouped by month by fridays_by_month. Finally, fridays_135 loops through those groups of months, extracts the 0th, 2nd, and 4th element in that list, and then appends them to the fri_135 list to produce a list of dates corresponding to the 1st, 3rd, and 5th Friday of ever month within the original date range, ordered by year and then by month.</p> <pre><code>from datetime import date, timedelta start_date = date(2021, 1, 1) end_date = date(2025, 12, 31) ''' Returns a list of dates between two dates (inclusive)''' def date_range(start = start_date, end = end_date): delta = end - start dates = [start + timedelta(days=i) for i in range(delta.days + 1)] return dates ''' Returns a list of lists containing the Friday dates for each month in a given range''' def fridays_by_month(): year = range(1, 13) years = range(start_date.year, end_date.year + 1) date_range_fris = [date for date in date_range() if date.strftime('%a') == &quot;Fri&quot;] range_fris = [] for yr in years: for month in year: month_fris = [] for date in date_range_fris: if date.strftime('%m') == str(f'{month:02}') and date.year == yr: month_fris.append(date) range_fris.append(month_fris) month_fris = [] return range_fris '''Returns a list of first, third, and fifth Fridays of each month in a given range of years, as a string, ordered by year and then by month''' def fridays_135(): fri_ordinals = [0, 2, 4] month_fris = fridays_by_month() fri_135 = [] for month in month_fris: for index, date in enumerate(month): if index in fri_ordinals: fri_135.append(str(date)) return fri_135 print(fridays_135()) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T09:21:49.910", "Id": "534619", "Score": "0", "body": "You shouldn't use comments to describe your function, but [docstrings](https://www.python.org/dev/peps/pep-0257/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T19:08:55.710", "Id": "534628", "Score": "0", "body": "I have rolled back Rev 5 → 3. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T22:18:36.907", "Id": "534635", "Score": "0", "body": "For `start_date = date(2021, 1, 8)`, the first date you produce is `'2021-01-08'`. Is that actually correct? That's the month's second Friday..." } ]
[ { "body": "<p>Here are a few pointers on how your code can be improved:</p>\n<h1>Style</h1>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> recommends surrounding top-level functions by two blank lines. This improves readability somewhat.</p>\n<p>Also, docstrings are supposed to come after the function signature, not before, as specified in <a href=\"https://www.python.org/dev/peps/pep-0257\" rel=\"noreferrer\">PEP257</a>. This is required for the docstring to be handled by Docutils and such software.</p>\n<p>Other than that, your style and layout is good.</p>\n<h1>Globals</h1>\n<p>You handle the start and end date with global variables. This is bad practice for a number of reason, including code readability (the code flow is harder to follow if you have to find global declarations, especially if your code gets longer), reusability, maintainability (it's hard to keep track which part of the code act on constants).</p>\n<p>You should pass these values as function arguments</p>\n<h1>Name shadowing</h1>\n<p><code>date</code> is a class name that you explicitly import, yet you overwrite it in some places, such as <code>date_range_fris = [date for date in date_range() [...]]</code>.</p>\n<p>Although there is not much damage as the scope is limited, I find this confusing to read. You should pick a different variable name.</p>\n<h1>Casting values to string</h1>\n<p>When checking if a given day is a friday, you compare the string representation of the date to a hard-coded string.</p>\n<p>This is wasteful as it requires extra work to get the string from a date and to compare strings.</p>\n<p>It would be better to use the <code>weekday()</code> method of <code>date</code> instances, which returns an integer. To keep a high readability, compare the value with a name constant.</p>\n<pre class=\"lang-py prettyprint-override\"><code>FRIDAY = 4\n\n# [...]\n\n date_range_fris = [d for d in date_range() if d.weekday() == FRIDAY]\n</code></pre>\n<p>Same remark for month comparison.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T17:17:42.113", "Id": "270623", "ParentId": "270620", "Score": "5" } }, { "body": "<p>You are organizing your code in functions, which is good; however, you aren't\ntaking full advantage of their benefits because most of your functions operate\non the basis of global variables rather than function arguments. A simple\ndata-oriented program like this has no need at all for global variables. In\nsuch a context, every function should take input arguments and return the\ncorresponding output data. That's a key principle of effective software\nengineering, and you should embrace it fully whenever practical.</p>\n<p>You have a useful utility in <code>date_range()</code>. One can adjust it a bit to remove\nits hard-coded attachment to global variables and to convert it to a generator\nfunction (not required, but something that makes some sense given the other\nfunctions I have in mind; I think on my first draft of this answer\nI misunderstood your purpose).</p>\n<pre><code>from datetime import timedelta, date\n\ndef date_range(start, end):\n for i in range((end - start).days + 1):\n yield start + timedelta(days = i)\n</code></pre>\n<p>From that foundation, one can select the Fridays:</p>\n<pre><code>def fridays_in_range(start, end):\n for d in date_range(start, end):\n if d.weekday() == 4:\n yield d\n</code></pre>\n<p>And then it's easy to do the grouping and selecting via some handy\nutilities from <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\">itertools</a>.</p>\n<pre><code>from operator import attrgetter\nfrom itertools import groupby, islice\n\ndef fridays_135(start, end):\n for k, group in groupby(fridays_in_range(start, end), attrgetter('month')):\n for f in islice(group, 0, None, 2):\n yield f\n</code></pre>\n<p>One could write all of that in a single function, I suppose, perhaps even in\nfewer lines of code. But I think I prefer this approach because it focuses the\nmind on building simple, useful functions – one on top of the other.\nNotice also that in this particular case, the code contains\nvery little of our own algorithmic machinations: the grubby details\n(even selecting 1st, 3rd, and 5th Fridays) are farmed out to various parts of the Python standard library.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T17:36:05.463", "Id": "534578", "Score": "0", "body": "Wow, I really am over complicating it! Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T18:00:04.283", "Id": "534582", "Score": "1", "body": "`date_range` imo should be a generator :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T18:32:00.550", "Id": "534584", "Score": "0", "body": "@FMc When you say that my method for finding Fridays is overly complex, do you mean that one line of code or the entire fridays_by_month function? The bulk of the work done in that function is the grouping of the dates into months that can then be checked for positional status." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T23:46:04.620", "Id": "534599", "Score": "0", "body": "@StephenWilliams I think I misunderstood your question before. I augmented my response." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T17:24:16.260", "Id": "270624", "ParentId": "270620", "Score": "4" } }, { "body": "<p>It seems rather inefficient to generate every date, then filter out non-Fridays, then filter out ones that arent't the first, third, or fifth Friday. Calculate directly them instead.</p>\n<p>Find the first Friday in the range:</p>\n<pre><code>friday = start + timedelta((FRIDAY - start.weekday())%7)\n</code></pre>\n<p>Move forward a week if it's not the 1st, 3rd, or 5th Friday:</p>\n<pre><code>ONE_WEEK = timedelta(weeks=1)\n\nweek = (friday.day - 1)//7 + 1\nif week not in (1,3,5):\n friday += ONE_WEEK\n</code></pre>\n<p>While <code>friday</code> is still in the data range, yield the date. If it's the 1st or 3d Friday, add one week, otherwise add two weeks (day 22 is the start of the 4th week):</p>\n<pre><code>TWO_WEEKS = timedelta(weeks=2)\n\nwhile friday &lt; end:\n yield friday\n \n if friday.day &lt; 22:\n friday += TWO_WEEKS\n else:\n friday += ONE_WEEK\n</code></pre>\n<p>Putting it all together:</p>\n<pre><code># date.weekday() returns 0 for Monday, so 4 = Friday\nFRIDAY = 4\n\nONE_WEEK = timedelta(weeks=1)\nTWO_WEEKS = timedelta(weeks=2)\n\ndef gen_friday_135(start, end):\n friday = start + timedelta((FRIDAY - start.weekday())%7)\n \n week = (friday.day - 1)//7 + 1\n if week not in (1,3,5):\n friday += ONE_WEEK\n\n while friday &lt; end:\n yield friday\n \n if friday.day &lt; 22:\n friday += TWO_WEEKS\n else:\n friday += ONE_WEEK\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T22:17:58.293", "Id": "534596", "Score": "0", "body": "Wow, almost all of my code is is unnecessary!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T18:15:50.843", "Id": "534625", "Score": "0", "body": "What is the purpose of the minus 1 in the week variable? I tried the generator with and without that minus 1, and it produced the same list in both cases" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T23:39:50.363", "Id": "534640", "Score": "1", "body": "@StephenWilliams, `friday.day` returns integers in the range 1-31. The minus one converts it so the range starts at zero so the // operator gives the correct week number. Without it, the formula would calculate the 7th as being in the second week." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T02:56:20.860", "Id": "534647", "Score": "0", "body": "That makes sense to me. I'm still wondering why its removal didn't affect the list, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T04:24:42.123", "Id": "534648", "Score": "1", "body": "@StephenWilliams, without the -1 `gen_friday_135(start=date(2021, 5, 2),\n end=date(2021, 5, 30))` will yield the 5/14 and 5/28 (the 2nd and 4th Fridays) instead of 5/7 and 5/21 (the 1st and 3rd Fridays)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T20:00:08.687", "Id": "270628", "ParentId": "270620", "Score": "9" } } ]
{ "AcceptedAnswerId": "270628", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T16:01:04.153", "Id": "270620", "Score": "3", "Tags": [ "python", "python-3.x", "datetime" ], "Title": "Produce a list of every 1st, 3rd, and 5th Friday of each month in a date range" }
270620
<p>I had to write a custom function to load a yaml file from the current working directory. The function itself works and my intention was to write it in a pure fashion but my senior colleague told me that the way I wrote this function is utterly bad and I have to rewrite it.</p> <p>Which commandment in Python did I violate? Can anyone tell me what I did wrong here and how a &quot;professional&quot; solution would look like?</p> <pre><code>from typing import Dict import yaml from yaml import SafeLoader from pathlib import Path import os def read_yaml_from_cwd(file: str) -&gt; Dict: &quot;&quot;&quot;[reads a yaml file from current working directory] Parameters ---------- file : str [.yaml or .yml file] Returns ------- Dict [Dictionary] &quot;&quot;&quot; path = os.path.join(Path.cwd().resolve(), file) if os.path.isfile(path): with open(path) as f: content = yaml.load(f, Loader=SafeLoader) return content else: return None content = read_yaml_from_cwd(&quot;test.yaml&quot;) print(content) </code></pre>
[]
[ { "body": "<p>Which commandment did you violate? Using <code>os.path</code> and <code>pathlib</code> in the same breath! <code>pathlib</code> is an object-oriented replacement to <code>os.path</code>.</p>\n<pre><code> path = os.path.join(Path.cwd().resolve(), file)\n if os.path.isfile(path):\n with open(path) as f:\n</code></pre>\n<p>could be written as:</p>\n<pre><code> path = Path.cwd().joinpath(file)\n if path.is_file():\n with path.open() as f:\n</code></pre>\n<p>or since you're starting at the current directory, simply:</p>\n<pre><code> path = Path(file)\n if path.is_file():\n with path.open() as f:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T19:00:03.640", "Id": "534587", "Score": "0", "body": "I am using `ruamel yaml` in my own project, so I might be missremembering the details. I thought one could simply do `content = yaml.load(path, Loader=SafeLoader)` directly on the path without having to explicitly open it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T19:05:33.057", "Id": "534589", "Score": "0", "body": "@N3buchadnezzar That may be true; I haven't used `yaml` at all. My answer focused on the mashup between `os.path` and `pathlib`, stopping just before the `yaml.load(...)` line for that very reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T19:06:06.347", "Id": "534590", "Score": "0", "body": "thank you, very helpful!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T18:55:31.570", "Id": "270626", "ParentId": "270625", "Score": "3" } } ]
{ "AcceptedAnswerId": "270626", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T18:13:04.213", "Id": "270625", "Score": "2", "Tags": [ "python", "python-3.x", "file-system" ], "Title": "Read file from current path in Python" }
270625
<p>I've tried optimising my program by removing invalid values for possible spaces instead of searching from 1-9, and by choosing values with the lowest number of empty spaces in its row and column, but these are marginal improvements and sometimes slow it down.</p> <p>I've heard of constraint satisfaction being used to optimise it and I'm not sure if that's what I've already done or something else entirely. I've attached my final function that solves the sudoku and my full code below. Any help would be greatly appreciated, thanks.</p> <pre><code>def sudoku_solver(sudoku): nextEmpty = lowestZero(sudoku) if nextEmpty == None: print(sudoku) return True for i in possible_values(sudoku,row,column): if validityCheck(sudoku,i,row,column)==True: sudoku[row][column]=i if sudoku_solver(sudoku)==True: return True sudoku[row][column]=0 return False </code></pre> <p>And this is my full code</p> <pre><code>import numpy as np def row(sudoku,row): return sudoku[row] def column(sudoku,column): columnList = [] for i in range(0,9): columnList.append((sudoku[i])[column]) return columnList def square(sudoku,row,column): if row in [0,1,2]: row = 0 elif row in [3,4,5]: row = 3 elif row in [6,7,8]: row = 6 if column in [0,1,2]: column = 0 elif column in [3,4,5]: column = 3 elif column in [6,7,8]: column = 6 squareList = [] for i in range(0,3): for j in range(0,3): squareList.append(sudoku[row+i][column+j]) return squareList def validityCheck(sudoku,number,rowNum,columnNum): rowList = row(sudoku,rowNum) columnList = column(sudoku,columnNum) squareList = square(sudoku,rowNum,columnNum) if (number in rowList): return False if (number in columnList): return False if (number in squareList): return False else: return True def find_next_empty(sudoku): for i in range(0,9): for j in range(0,9): if sudoku[i][j]==0: return[i,j] def solvedSudoku(sudoku): isSolved = True for i in range(0,9): for j in range(0,9): if sudoku[i][j]==0: isSolved = False return isSolved def noValidInp(sudoku): noneValid = False emptyVals = findEmpty(sudoku) for i in emptyVals: for j in range(0,9): if validityCheck(sudoku,j,i[0],i[1]) == True: noneValid = True if noneValid == False: return True else: return False def invalidSudoku(sudoku): for i in range(0,9): for j in range(0,9): num=sudoku[i][j] sudoku[i][j]=0 if num!=0: if validityCheck(sudoku,num,i,j)==False: return False else: sudoku[i][j]=num return True def possible_values(sudoku,rowInp,columnInp): inputList=[] rowList = row(sudoku,rowInp) columnList = column(sudoku,columnInp) squareList = square(sudoku,rowInp,columnInp) for i in range(1,10): if i not in rowList: inputList.append(i) return inputList def zeroList(sudokuInp): list=[] for row in range(0,9): for column in range(0,9): if sudokuInp[row][column]==0: list.append([(row),(column)]) return list def nOfZeros(sudoku,rowInp,columnInp): zeroCount=0 rowList=row(sudoku,rowInp) columnList=column(sudoku,columnInp) squareList=square(sudoku,rowInp,columnInp) for i in rowList: if i==0: zeroCount+=1 for j in columnList: if j==0: zeroCount+=1 return zeroCount-2 def lowestZero(sudoku): list=zeroList(sudoku) if list==[]: return None currentLowest=[0,0,81] for i in list: zeroNum=nOfZeros(sudoku,i[0],i[1]) if zeroNum&lt;currentLowest[2]: currentLowest=[i[0],i[1],zeroNum] return currentLowest def sudoku_solver_ting(sudoku): nextEmpty = lowestZero(sudoku) if nextEmpty == None or nextEmpty==[]: return True for i in possible_values(sudoku,nextEmpty[0],nextEmpty[1]): row=nextEmpty[0] column=nextEmpty[1] if validityCheck(sudoku,i,row,column)==True: sudoku[row][column]=i if sudoku_solver_ting(sudoku)==True: return True sudoku[row][column]=0 return False def sudoku_solver(sudokuInp): if invalidSudoku(sudokuInp)==False: for i in range(0,9): for j in range(0,9): sudokuInp[i][j]=-1 return sudokuInp if sudoku_solver_ting(sudokuInp)==True: if solvedSudoku(sudokuInp)==False: for i in range(0,9): for j in range(0,9): sudokuInp[i][j]=-1 return sudokuInp else: for i in range(0,9): for j in range(0,9): sudokuInp[i][j]=-1. return sudokuInp <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T02:50:53.370", "Id": "534607", "Score": "0", "body": "Haven't looked at your code at all, but Peter Norvig's is often worth [studying](https://norvig.com/sudoku.html)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T19:48:14.067", "Id": "270627", "Score": "1", "Tags": [ "python", "recursion", "sudoku", "backtracking" ], "Title": "How can I optimise my recursive backtracking sudoku algorithm?" }
270627
<p>I am trying to write a simple rock paper scissors game in pycharm using classes and pygame. So far, I have not incorporated pygame yet. My idea is to import images that change in regards to the user's choice and the computer's random choice.</p> <p>This is what I have so far:</p> <pre><code>import random class RockPaperScissors: def __init__(self): self.wins = 0 self.losses = 0 self.ties = 0 self.options = {'rock': 0, 'paper': 1, 'scissors': 2} def random_choice(self): return random.choice(list(self.options.keys())) def check(self, player, machine): result = (player - machine) % 3 if result == 0: self.ties += 1 print(&quot;It is a tie!&quot;) elif result == 1: self.wins += 1 print(&quot;You win!&quot;) elif result == 2: self.losses += 1 print(&quot;The machine wins! Do you wish to play again?&quot;) def score(self): print(f&quot;You have {self.wins} wins, {self.losses} losses, and &quot; f&quot;{self.ties} ties.&quot;) def play(self): while True: user = input(&quot;What would you like to choose? (The choices are ROCK,PAPER,SCISSORS): &quot;).lower() if user not in self.options.keys(): print(&quot;Invalid input, try again!&quot;) else: machine_choice = self.random_choice() print(f&quot;You've picked {user}, and the computer picked {machine_choice}.&quot;) self.check(self.options[user], self.options[machine_choice]) def re_do(self): retry = input('Do you wish to play again? (y/n): ').lower() if retry == 'n': exit() elif retry == 'y': self.play() else: print(&quot;Invalid input&quot;) if __name__ == &quot;__main__&quot;: game = RockPaperScissors() while True: game.play() game.score() game.re_do() </code></pre> <p>In the future, I would like to convert this to use <code>pygame</code>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T21:18:07.060", "Id": "534594", "Score": "0", "body": "Could you double check your indentation? If you highlight everything and click `{}`, that should get you started. Otherwise, your last few lines aren't rendering correctly." } ]
[ { "body": "<h1>Good things</h1>\n<p>You mostly follow PEP8 styling conventions, making your code quite readable. The only exception I see is an extra blank line at the beginning of the <code>score</code> and <code>play</code> methods.</p>\n<p>Also, it is good thinking to wrap your game state into a class for future integration into a more complex project. It is also a good use of a main guard at the end.</p>\n<p>However, there are things that need to be improved to reach your end goal.</p>\n<h1>Things to improve</h1>\n<h2>Game loop logic</h2>\n<p>Your game loop logic fails completely: execution loops forever inside the <code>play()</code> method, and thus the <code>game.score()</code> and <code>game.re_do()</code> are never called. The game never ends and the total score is never diplayed.</p>\n<p>You should remove one of the infinite loop, and handle it properly.</p>\n<p>I would have a <code>run(self)</code> instance method that goes something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class RockPaperScissors\n\n # some stuff\n\n def run(self):\n play_again = True\n while play_again:\n player_move = get_player_input()\n machine_move = get_machine_input()\n winner = get_winner(player_move, machine_move)\n show_message(winner, score)\n play_again = get_yes_no_input()\n\n\nif __name__ == &quot;__main__&quot;:\n game = RockPaperScissors()\n game.run()\n</code></pre>\n<p>It still has some issues I'll address later (for later integration in a PyGame project), but at it should behave as expected potential issues can be worked on one at a time, in each of the method called.</p>\n<h2>Separation of concern</h2>\n<p>Although you tried to separate logic (by implementing a game class) from display, you failed and mix both all over the code.</p>\n<p>For example, the <code>check()</code> method should return the winner instead of displaying a message. Further down the line, if you want to implement a GUI with PyGame, you can handle a function return, or query the state of member variables, but a <code>print</code> output will be no use.</p>\n<p>Same goes from getting input. Eventually, inputs will be supplied by a PyGame instance through widgets or something. You should put all console-related actions (<code>print</code> and <code>input</code>) in separate methods that you should be able to override, depending on how you want to use the game class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T10:51:28.027", "Id": "270645", "ParentId": "270630", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T20:52:34.433", "Id": "270630", "Score": "1", "Tags": [ "python", "beginner", "rock-paper-scissors" ], "Title": "Simple Rock Paper Scissors game in Python" }
270630
<p>This Bash program parses day, month, year and month and year from arguments:</p> <pre><code>#!/usr/bin/env bash for arg do day= month= year= case $arg in */*/*|*-*-*) read -r year month day &lt;&lt;&lt; &quot;$(date '+%Y %m %d' -d &quot;$arg&quot;)&quot; ;; ????/??|????/?) IFS='/' read -r -a arr &lt;&lt;&lt; &quot;$arg&quot; month=${arr[1]} year=${arr[0]} ;; ????-??|????-?) IFS='-' read -r -a arr &lt;&lt;&lt; &quot;$arg&quot; month=${arr[1]} year=${arr[0]} ;; ??/????|?/????) IFS='/' read -r -a arr &lt;&lt;&lt; &quot;$arg&quot; month=${arr[0]} year=${arr[1]} ;; ??-????|?-????) IFS='-' read -r -a arr &lt;&lt;&lt; &quot;$arg&quot; month=${arr[0]} year=${arr[1]} ;; esac echo &quot;year: $year / month: $month / day: $day&quot; done </code></pre> <p>Usage:</p> <pre class="lang-none prettyprint-override"><code>./parse.sh 2021-03 2021-03-14 3/14/19 11/2019 2020/12 year: 2021 / month: 03 / day: year: 2021 / month: 03 / day: 14 year: 2019 / month: 03 / day: 14 year: 2019 / month: 11 / day: year: 2020 / month: 12 / day: </code></pre> <p>It seems overly-verbose to me. Can I write it more succinctly?</p>
[]
[ { "body": "<p>How about</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>for arg do\n day= month= year=\n\n case $arg in\n */*/* | *-*-*)\n read -r year month day &lt; &lt;(date '+%Y %m %d' -d &quot;$arg&quot;)\n ;;\n ????[-/]?? | ????[-/]?)\n IFS='-/' read -r year month &lt;&lt;&lt; &quot;$arg&quot;\n ;;\n ??[-/]???? | ?[-/]????)\n IFS='-/' read -r month year &lt;&lt;&lt; &quot;$arg&quot;\n ;;\n esac\n\n echo &quot;year: $year / month: $month / day: $day&quot;\ndone\n</code></pre>\n<ul>\n<li>remove pointless read into array</li>\n<li>IFS can be more than one character</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T22:14:29.383", "Id": "534595", "Score": "0", "body": "I was trying to combine the expressions, but failed. Thanks for the help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T00:13:44.590", "Id": "534600", "Score": "1", "body": "Luckily glenn can express things that most others find very challenging. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T21:54:24.793", "Id": "270632", "ParentId": "270631", "Score": "5" } } ]
{ "AcceptedAnswerId": "270632", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T21:39:23.610", "Id": "270631", "Score": "1", "Tags": [ "parsing", "datetime", "bash" ], "Title": "Parse a selection of date formats" }
270631
<p>I'm fairly new to Python and am exploring how to fix functions and make code 'more effective and readable'. As a first step, I would want to try to make shorter snippets of code here - for example by dividing it into more functions.</p> <p>I would also appreciate further improvements regarding possible errors I might stumble upon.</p> <p>No need for imports.</p> <p>The code is supposed to take values from a batch on a x- and y-position in the unit circle.<br /> Example input:</p> <pre class="lang-none prettyprint-override"><code>1, 0.1, 0.1, 10 1, 0.2, 0.2, 15 2, 1.2, 1.2, 20 2, 0.5, 0.5, 25 </code></pre> <p>Several values can be used in a batch. If x² + y² &gt; 1, it will not take that value into account when calculating the average of a batch. If no values in a batch are used, no average is calculated (avoiding division by zero).</p> <pre><code>def a(): while True: data = dict() # Or data = {} try: filename = input('Which data file? ') with open(filename, 'r') as h: for line in h: try: four_vals = line.split(',') batch = four_vals[0] if not batch in data: data[batch] = [] data[batch] += [ (float(four_vals[1]), float(four_vals[2]), float(four_vals[3]))] except ValueError: print('Some data are not integers in batch',batch,&quot;, line&quot;, line,&quot;\nThose values are not taken into account\n&quot; ) except IOError: print('No such file or directory was found, the written file can not be opened.'&quot;\n&quot;'Look through misspellings or that the written file is actually in the pathway.') continue return data def b(): data = a() data = dict(sorted(data.items())) return data def c(): data = b() for batch, sample in data.items(): try: #len(sample) &gt; 0: n = 0 # antal prov startar på 0 x_sum = 0 # summan startar på 0 for (x, y, val) in sample: circle = x ** 2 + y ** 2 if circle &lt;= 1: x_sum += val n += 1 else: print(batch,&quot;\t&quot;,&quot;Outside of the unit circle,&quot;, circle,&quot;&gt;1&quot;) average = x_sum / n print(batch, &quot;\t&quot;, average) except ZeroDivisionError: print(batch, &quot;\tNo data&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T02:34:54.767", "Id": "534606", "Score": "2", "body": "Some clarification of the input file format would be good; I can derive it from the code, but it's not at all obvious." } ]
[ { "body": "<h2>Some good stuff:</h2>\n<ul>\n<li>You're using error-specific <code>except</code> clauses.</li>\n<li>You're using <code>where</code> blocks.</li>\n</ul>\n<h2>Items you can improve:</h2>\n<ul>\n<li><p>Use a <code>main</code> method. See <a href=\"https://www.guru99.com/learn-python-main-function-with-examples-understand-main.html\" rel=\"nofollow noreferrer\">here</a> for an example; in particular Example 2.</p>\n</li>\n<li><p>Don't nest function <em>definitions</em> unnecessarily. Instead of calling <code>c</code>, which calls <code>b</code> which calls <code>a</code>, pass their return values to each other:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n c(b(a()))\n</code></pre>\n</li>\n<li><p>Give your functions better names. Give-or-take the cost of verbosity, a function's name should tell you clearly what it does. When in doubt, give everything a clear whole-word name.</p>\n</li>\n<li><p>What's the point of <code>b</code>? If sorting the batches is important, leave a comment that explains why.</p>\n</li>\n<li><p>Consider learning <a href=\"https://www.geeksforgeeks.org/comprehensions-in-python/\" rel=\"nofollow noreferrer\">comprehensions</a>.</p>\n</li>\n<li><p>Until you learn <code>class</code>es and <code>dataclass</code>es (or <code>NamedTuple</code>s), you can just use tuples to represent sequences of known length. This encodes your assumptions in the structure of the code.</p>\n</li>\n<li><p>Not that I like mutating values, but <code>list</code> has an <code>append</code> method; you don't have to say <code>+=[item]</code>. (It's more efficient too.)<br />\nMore broadly, it's always a good investment to read the <a href=\"https://docs.python.org/3/library/stdtypes.html\" rel=\"nofollow noreferrer\">official docs</a> for whatever tools you're using.</p>\n</li>\n<li><p>Separate your user-input loop from your file-parsing process. This will probably require you to nest one function definition inside another:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def a():\n while True:\n try:\n filename = input('Which data file? ') \n with open(filename, 'r') as h:\n return parse_file(h)\n except IOError: \n print('No such file or directory was found, the written file can not be opened.'&quot;\\n&quot;'Look through misspellings or that the written file is actually in the pathway.')\n\ndef parse_line(line):\n batch, x, y, val = line.split(',') # may raise if there's not the right number!\n return batch, tuple(float(i) # should these all be floats? should batch be a string?\n for i in (x, y, val))\n\ndef parse_file(open_handle):\n data = {}\n for line in open_handle:\n try:\n batch, triple = parse_line(line)\n data.setdefault(batch, []).append(triple)\n except ValueError: \n print('Some data are not integers in batch',batch,&quot;, line&quot;, line,&quot;\\nThose values are not taken into account\\n&quot; ) \n return data\n</code></pre>\n</li>\n<li><p>Try to have all your validation in one place:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def parse_line(line):\n b_, x_, y_, v_ = line.split(',')\n batch, x, y, val = strip(b_), float(x_), float(y_), int(v_)\n if (x**2) + (y**2) &lt;= 1:\n return batch, (x, y, val)\n else:\n raise ValueError(&quot;How can you get the correct message to print out?&quot;)\n</code></pre>\n</li>\n<li><p>If you do all your validation early, do you still need the <code>try... except ZeroDivisionError</code>? I have mixed feelings. On the one hand, it looks like it will no longer be able to happen. On the other, I don't want to encourage you to remove a failsafe.</p>\n</li>\n<li><p>Right now <code>c</code> has so many layers of indentation, maybe you should break out a separate function for handling a single batch. On the other hand, you can reduce the complexity by using more off-the-shelf stuff:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def c(data):\n for batch, samples in data.items():\n n = len(samples)\n if n:\n total = sum(val for (x, y, val) in samples)\n average = total / n \n print(batch, &quot;\\t&quot;, average)\n</code></pre>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T03:40:05.137", "Id": "270638", "ParentId": "270633", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T22:06:49.527", "Id": "270633", "Score": "4", "Tags": [ "python", "performance", "error-handling", "mathematics" ], "Title": "Find the mean magnitude of values inside unit circle" }
270633
<p>To start I'd like say that I'm a beginner writing my first Next.js app though I feel this question is more React related. I'm building an app where an user can add/edit stored food, recipes etc. which means I use a lot of submit form handlers. In every handler I:</p> <ol> <li><p>Check if inputs are correct (I also do that directly in form)</p> </li> <li><p>Manage the data</p> </li> <li><p>Fetch to backend(Firebase)</p> </li> <li><p>Dispatch an action to Redux</p> </li> </ol> <p>How can I achieve better architecture in this form handler?</p> <p>The problem is that I feel like these handlers are too complicated and too &quot;ugly&quot;. Could someone help me with what could I do better here ? I am thinking about exporting some functionality to custom hook or create some dynamic function but I have no idea how to do that here since all these handlers between adding/editing/removing food are so different (they are managing data much differently).</p> <p>Below example form handler for editing food (the most &quot;ugly&quot; one)</p> <pre><code>const submitEditFoodHandler = async (e) =&gt; { try { e.preventDefault(); if ( editFoodName.current.value.trim().length &lt; 1 || editFoodType.current.value === &quot;DEFAULT&quot; || +editFoodQuantity.current.value &lt; 0 || editFoodQuantity.current.value.trim().length &lt; 1 ) { alert(ALERT_FOOD_EMPTY); return; } else if (!editFoodWeight.current.value.match(WEIGHT_REGEX)) { alert(ALERT_WEIGHT_FORMAT); return; } const foodObj = { username: foundUser.username, id: props.row.id, foodId: foundUser.foodId, name: editFoodName.current.value, type: editFoodType.current.value, quantity: editFoodQuantity.current.value, weight: editFoodWeight.current.value, expDate: editFoodExpDate.current.value, key: props.row.key, }; const foodCopy = [...foundUser.food]; const foundUserFoodIndex = foodCopy.findIndex( (ele) =&gt; +ele.id === +props.row.id ); foodCopy[foundUserFoodIndex] = { name: editFoodName.current.value, type: editFoodType.current.value, quantity: editFoodQuantity.current.value, weight: editFoodWeight.current.value, expDate: editFoodExpDate.current.value, id: props.row.id, key: props.row.key, }; const payload = { username: foundUser.username, recipesId: foundUser.recipesId, foodId: foundUser.foodId, totalWeight: foundUser.totalWeight - getNumberFromStr(props.row.weight) + getNumberFromStr(editFoodWeight.current.value), totalQuantity: foundUser.totalQuantity - props.row.quantity + +editFoodQuantity.current.value, food: foodCopy, recipes: foundUser.recipes, }; const docRef = doc(db, &quot;users&quot;, foundUser.id); await setDoc(docRef, payload); dispatch(fridgeActions.editFood(foodObj)); editFoodName.current.value = &quot;&quot;; editFoodType.current.value = &quot;&quot;; editFoodQuantity.current.value = &quot;&quot;; editFoodWeight.current.value = &quot;&quot;; editFoodExpDate.current.value = &quot;&quot;; props.setShowEditFoodModal(false); } catch (err) { alert(ALERT_OTHER); console.error(err); }}; </code></pre> <p>Thank you in advance for any suggestions</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T08:24:52.827", "Id": "534617", "Score": "2", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-02T22:28:08.737", "Id": "270634", "Score": "0", "Tags": [ "javascript", "beginner", "algorithm", "react.js", "redux" ], "Title": "Cookbook app in next.js" }
270634
<p>I'm trying to create multiple rows in my db with an array. This array has multiple objects of products chosen by the client.</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>createInvoice: async function (req,res) {//OK var params = req.body; var user = req.user.data; var promesErrors = []; var sub_total = 0; var total = 0; console.log(params); if(user){ //generate payment if(params.payment){ //generate total sub total etc params.products.forEach( product =&gt; { sub_total = sub_total + (product.product_quantity * product.price); }); //total total = (sub_total * params.payment.iva/100) + sub_total; var payment = await Payment.create({ payment_type: params.payment.payment_type, iva: params.payment.iva, sub_total: sub_total, total: total, status: false, }).catch(err =&gt; {return res.status(403).send({err:err})}); if(payment){ for await(let product of params.products){ const productpayment = await Product_Payment.create( { product_name: product.name, product_qty: product.product_quantity, product_id: product.id, } ).catch(err =&gt; { return res.status(403).send({err:err}) }); if(productpayment){ await payment.addProduct_Payment( productpayment, { through: { customer_id: params.customer_id } } ).catch(err =&gt; { promesErrors.push(productpayment.id); }); } } //if any error found delete the rows created if(promesErrors.length &gt; 1){ for await(let errorId of promesErrors){ await Product_Payment.destroy({ where: { id: errorId } }); } } }else res.status(500).send({message:'error creando la factura'}); }else return res.status(403).send({message:'faltan datos de payment'}); }else return res.status(403).send({message:'you are not logged in'}); }, }</code></pre> </div> </div> </p> <p>I need your opinions from the section where the <code>for await</code> is. Should I use that or may I use the <code>Promise.all</code>?</p> <p>I would be thankful if any of you have any advice on how to make my code more efficient. My code works perfectly but I have doubts if I am using the <code>for await</code> correctly.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T03:11:59.833", "Id": "534608", "Score": "2", "body": "Please pick a title that describes the function of the program." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T07:29:39.743", "Id": "534616", "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)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T00:10:30.080", "Id": "270635", "Score": "0", "Tags": [ "javascript", "performance", "node.js" ], "Title": "Improving multiple row creation query in JavaScript" }
270635
<p>Well I was solving Problem 3 from Project Euler, but I just found out that my code is really bad, it would take so much time to finish processing the code and I honestly do not know how to optimize it.</p> <h1>Problem Statement</h1> <blockquote> <p>The prime factors of 13195 are 5, 7, 13 and 29. <br /> What is the largest prime factor of the number 600851475143 ?</p> </blockquote> <h1>My Code:</h1> <pre><code>function isPrime(x){ if(x % 2 == 0 &amp;&amp; x != 2){ return false; } for(j = 3; j &lt;= Math.sqrt(x); j+=2){ if(x % j == 0 &amp;&amp; x != j){ return false; } } return true; } </code></pre> <pre><code>function euler(){ const t = 600851475143; let maxPrimeDiv = 0; for(let j = 3; j &lt;= t; j++){ if(isPrime(j) &amp;&amp; t % j == 0){ maxPrimeDiv = j; }else{ continue; } } return maxPrimeDiv; } </code></pre> <pre><code>console.log(euler()); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T01:16:56.127", "Id": "534603", "Score": "0", "body": "You don't need to test for primality. If you start with 2 and proceed in sequence 2, 3,4,5, ... then when you find a factor it is *guaranteed* to be prime. Another optimization is, after trying 2 or 3 every prime is of the form 6*k + 1 or 6*k - 1 for k an integer. Finally, once you reach sqrt(n) without finding a factor you know that n is prime. You can combine these to drastically speed up your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T15:41:59.020", "Id": "534621", "Score": "0", "body": "Check these https://codereview.stackexchange.com/search?q=%22largest+prime+factor%22+%5Bjavascript%5D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T01:31:15.727", "Id": "534644", "Score": "0", "body": "@PresidentJamesK.Polk Every factor is *not* guaranteed to be prime. If one progresses through the sequence 2, 3, 4, 5, … testing which of these divides the number 12, then, amongst others, 4 and 6 will be (correctly) identified as factors, neither of which are prime. The OP‘s algorithm doesn’t perform any divisions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T01:32:55.600", "Id": "534645", "Score": "0", "body": "Well of course you have to divide out the prime factors as you find them. The comment is a hint, not a complete algorithm." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T00:40:17.863", "Id": "270636", "Score": "0", "Tags": [ "javascript", "programming-challenge" ], "Title": "Euler Project Problem #3 Optimization Needed" }
270636
<p>I want to print the below pattern</p> <pre><code>* * * * * * * * * * * * * * * </code></pre> <p><strong>My logic written</strong></p> <pre><code>for row in range(1,6): for col in range(1,6): if row is col: print(row * '* ') </code></pre> <p>Can someone review the code and suggest any improvements needed</p> <p>The code which i have written is it a right approach ?</p>
[]
[ { "body": "<p>Welcome to Code Review.</p>\n<p>Your code is literally 4 lines. So there isn't much to review.</p>\n<ul>\n<li><p>Do not use the <code>is</code> operator to compare the integers. See <a href=\"https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is\">difference between <code>is</code> and <code>==</code></a></p>\n</li>\n<li><p>You can save the nested loop: you are already ensuring <code>col == row</code> so you can instead write:</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>for row in range(1,6):\n print(&quot;* &quot; * row)\n</code></pre>\n<ul>\n<li>If we want to get technical, the code you have written has a time complexity of <strong>O(n^3)</strong>, but the problem can be solved in <strong>O(n^2)</strong>. You can read more on this topic <a href=\"https://www.google.com/amp/s/www.mygreatlearning.com/blog/why-is-time-complexity-essential/%3famp\" rel=\"nofollow noreferrer\">here</a>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T05:01:41.520", "Id": "270640", "ParentId": "270639", "Score": "4" } }, { "body": "<p>Welcome to codereview. Well, as you said your code works but it can be improved.</p>\n<h2>Reviewing time complexity</h2>\n<pre class=\"lang-py prettyprint-override\"><code># tends to -&gt; n-1 where n = 6 in this case\nfor row in range(1,6):\n # tends to -&gt; n-1\n for col in range(1,6):\n # compares two ints which is O(1) time\n if row is col:\n # internally concatenates row times the character '* '\n print(row * '* ')\n</code></pre>\n<p>This could be some what in the <span class=\"math-container\">\\$\\mathcal{O}(n^3)\\$</span> order. It is to say. If your pattern prints on the last row 10 asterisks, it will take approximately 10⁵ instructions to complete it (quite a lot).</p>\n<h2>Decrementing the algorithm complexity</h2>\n<p>In this case you need to notice that the number of asterisks is increasing from <code>1 to n</code>, and that each line there's one more <code>*</code>.</p>\n<p>How to represent it? Using a range, a range from <code>1 to n+1</code> because as you know the upper limit in a range is excluded.</p>\n<p>Now, look at the <code>print(row * '* ')</code> statement, you could actually use the value of the variable iterating the <code>range from 1 to n+1</code> in the form of <code>print(x * '* ')</code> and so your code would be:</p>\n<pre class=\"lang-py prettyprint-override\"><code>n = 5 # number asterisks in the final row\n\nfor asterisks in range(1,n+1):\n print(asterisks * '* ')\n</code></pre>\n<p>another way could be</p>\n<pre class=\"lang-py prettyprint-override\"><code>n = 5 # number asterisks in the final row\n\nfor asterisks in range(1,n+1):\n for _ in range(1,asterisks+1):\n print('* ')\n</code></pre>\n<p>but the previous one is more &quot;pythonic&quot;</p>\n<h2>How could you get better at coding</h2>\n<ul>\n<li>Thinking in the most simplistic way to solve a problem is the right approach</li>\n<li>Understanding that simplicity isn't mediocrity is the second step (a good solution is simple but isn't lacking)</li>\n<li>Practicing is like bread and butter, you will get better with practice and peer review.</li>\n</ul>\n<p>Why I'm saying all this? Because I spent my first 2 or so years doing spaghetti code and I don't want anyone to lose precious time wasting effort in the wrong thing. <strong>Well, I hope this helps you :)</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T18:53:10.110", "Id": "534627", "Score": "0", "body": "`# compares two ranges which is O(n²) time` -> actually I think it's comparing row and col (two ints) for reference equality which is constant time O(1), so the other answer with O(n³) is correct, not O(n⁵)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T07:19:32.750", "Id": "534651", "Score": "0", "body": "If you try the second suggested approach, it doesn't work. You need to use the `end` kwarg in `print` in the inner loop (`print(\"*\", end=\" \")`), and then print a `\\n` (call `print()`) on the outter loop" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T05:17:45.753", "Id": "270642", "ParentId": "270639", "Score": "0" } } ]
{ "AcceptedAnswerId": "270640", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T04:21:23.580", "Id": "270639", "Score": "3", "Tags": [ "python", "design-patterns" ], "Title": "Design a pattern using python" }
270639
<p>I have different format of address in an array, those format looks like this</p> <p><code>lastname/firstname/_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/phone</code></p> <p><code>lastname</code> =&gt; a part of the address (noted <code>AddressPart</code>) <code>/</code> =&gt; a separation <code>_</code> =&gt; a line break</p> <p>the above entire would do</p> <pre><code>lastname firstname country postalCode regionId city addressFirst addressSecond phone </code></pre> <p>now, I have a method, where I basically want to pass a parameter what part I am interested in, and get the resulting format:</p> <p>f.e</p> <pre><code> input : [&quot;country&quot;, &quot;postalCode&quot;] return &quot;country/postalCode input : [&quot;lastname&quot;, &quot;firstname&quot;, &quot;regionId&quot;] return &quot;lastname/firstname/_/regionId&quot; input : [&quot;firstname&quot;, &quot;country&quot;, &quot;regionId&quot;, &quot;city&quot;] return &quot;firstname/_/country/_/regionId/city&quot; input : [&quot;country&quot;, &quot;regionId&quot;, &quot;phone&quot;] return &quot;country/_/regionId/_/phone&quot; </code></pre> <p>Here is the method :</p> <pre><code> type AddressPart = &quot;firstname&quot; | &quot;lastname&quot; | ... | &quot;phone&quot;; const allAddressParts = [&quot;firstname&quot;, &quot;lastname&quot;, ... ,&quot;phone&quot;]; static getLocaleAddress( parts: AddressPart[] ) { let addressFormat = `lastname/firstname/_/country/postalCode/_/regionId/city/addressFirst/addressSecond/_/phone`; // (1) const toRemove = allAddressParts.filter((part) =&gt; !parts.includes(part)); // (2) toRemove.forEach((part) =&gt; { addressFormat = addressFormat .replace(`_/${part}/_`, '_') .replace(new RegExp(part + '/?'), '') .replace(/^(_\/)+/, '') .replace(/\/(_\/)*$/, ''); }); return addressFormat.split('/'); } </code></pre> <p>What I don't like in what I did is :</p> <ol> <li>I replace items, so I need to filter from the list of parts the one I want, to keep the one I want to remove</li> <li>it is 4 replaces operations, and I was wondering if it was improvable.</li> </ol> <p>Thanks for the tips :x</p>
[]
[ { "body": "<blockquote>\n<p>What I don't like in what I did is :</p>\n<ol>\n<li><p>I replace items, so I need to filter from the list of parts the one I want, to keep the one I want to remove</p>\n</li>\n<li><p>it is 4 replaces operations, and I was wondering if it was improvable.</p>\n</li>\n</ol>\n</blockquote>\n<hr />\n<p>It is possible to avoid replacing items. For example,</p>\n<pre><code>'use strict';\n\nfunction getLocaleAddress(parts) {\n // field and line separators\n const fieldSep = &quot;/&quot;;\n const lineBreak = &quot;_&quot;;\n\n // address parts plus lineBreak as set\n parts = new Set(parts).add(lineBreak);\n\n // format template as array\n const format = (\n &quot;lastname/firstname/_/&quot; +\n &quot;country/postalCode/_/&quot; +\n &quot;regionId/city/addressFirst/addressSecond/_/&quot; +\n &quot;phone&quot; \n )\n .split(fieldSep)\n ;\n\n // selected address parts as array\n let selected = [];\n let inLine = false;\n for (const field of format) {\n if (parts.has(field)) {\n if (field !== lineBreak) {\n inLine = true;\n }\n if (inLine) {\n selected.push(field);\n }\n }\n if (field === lineBreak) {\n inLine = false;\n }\n }\n const end = selected.length - 1;\n if (end &gt;= 0 &amp;&amp; selected[end] === lineBreak) {\n selected.pop();\n }\n return selected;\n}\n</code></pre>\n<hr />\n<pre><code>function test(input) {\n const fieldSep = &quot;/&quot;;\n console.log(\n &quot;\\n&quot;, input, \n &quot;\\n&quot;, getLocaleAddress(input).join(fieldSep)\n );\n}\n\ntest([&quot;country&quot;, &quot;postalCode&quot;]);\ntest([&quot;lastname&quot;, &quot;firstname&quot;, &quot;regionId&quot;]);\ntest([&quot;firstname&quot;, &quot;country&quot;, &quot;regionId&quot;, &quot;city&quot;]);\ntest([&quot;country&quot;, &quot;regionId&quot;, &quot;phone&quot;]);\n</code></pre>\n<hr />\n<pre><code>$ node cr.address.js\n\n [ 'country', 'postalCode' ] \n country/postalCode\n\n [ 'lastname', 'firstname', 'regionId' ] \n lastname/firstname/_/regionId\n\n [ 'firstname', 'country', 'regionId', 'city' ] \n firstname/_/country/_/regionId/city\n\n [ 'country', 'regionId', 'phone' ] \n country/_/regionId/_/phone\n\n$ \n</code></pre>\n<hr />\n<p>I used <a href=\"https://jsbench.me/\" rel=\"nofollow noreferrer\">JSBench.me</a> and your test cases to compare my code to your code. My code was fastest. Your code was 70.3% slower.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T21:14:20.737", "Id": "270685", "ParentId": "270644", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T08:38:45.840", "Id": "270644", "Score": "1", "Tags": [ "javascript", "strings", "typescript" ], "Title": "get address parts based on requested parts" }
270644
<p>Heart rate or blink generator. Clocked from the system frequency, but calculated from a constant of 120MHz. Has a prescaler with values 2, 3, 5, 6, for even heart beat / blinking. The IS_DEBUG parameter is required for debugging for easy control over the rhythm, this parameter reduces 120MHz to 120Hz. IS_BLINK selects between blink and heart beat.</p> <p>heart_beat.sv</p> <pre><code>`timescale 1ns / 10ps module heart_beat # ( parameter integer SPEED_GRADE = 2, parameter IS_DEBUG = &quot;false&quot;, parameter IS_BLINK = &quot;false&quot; ) ( input logic i_clk, input logic i_s_rst_n, output logic o_heart_beat ); localparam integer RATE = (IS_DEBUG == &quot;true&quot;) ? 120 : 120_000_000; localparam integer MAX_COUNTER_VAL = RATE / (((SPEED_GRADE != 2 ) &amp;&amp; (SPEED_GRADE != 3 ) &amp;&amp; (SPEED_GRADE != 5 ) &amp;&amp; (SPEED_GRADE != 6 )) ? 2 : SPEED_GRADE); localparam integer COUNTER_WIDTH = $clog2(MAX_COUNTER_VAL); localparam [COUNTER_WIDTH - 1: 0] CMP_COUNTER_VAL = MAX_COUNTER_VAL - 1'h1; logic heart_beat; logic mask; logic [COUNTER_WIDTH - 1: 0] counter; assign o_heart_beat = heart_beat &amp; ((IS_BLINK == &quot;true&quot;) ? '1 : mask); always_ff @ (posedge i_clk) begin if (i_s_rst_n == '0) begin counter &lt;= '0; heart_beat &lt;= '0; end else begin if (counter == CMP_COUNTER_VAL) begin heart_beat &lt;= !heart_beat; counter &lt;= '0; end else begin counter++; end end end generate if (IS_BLINK == &quot;false&quot;) begin localparam integer MASK_COUNTER_PRE = 4; localparam integer MASK_MAX_COUNTER_VAL = (MAX_COUNTER_VAL / MASK_COUNTER_PRE); localparam integer MASK_COUNTER_WIDTH = $clog2(MASK_MAX_COUNTER_VAL); localparam [COUNTER_WIDTH - 1: 0] MASK_CMP_COUNTER_VAL = MASK_MAX_COUNTER_VAL - 1'h1; logic [MASK_COUNTER_WIDTH - 1: 0] mask_counter; always_ff @ (posedge i_clk) begin if (i_s_rst_n == '0) begin mask &lt;= '0; mask_counter &lt;= '0; end else begin if (mask_counter == MASK_CMP_COUNTER_VAL) begin mask &lt;= !mask; mask_counter &lt;= '0; end else begin mask_counter++; end end end end endgenerate endmodule </code></pre> <p>heart_beat_tb.sv</p> <pre><code>`timescale 1ns / 1ps module heart_beat_tb; //-------------------------------------------------- setup localparam integer SPEED_GRADE = 2; localparam IS_DEBUG = &quot;true&quot;; localparam IS_BLINK = &quot;true&quot;; localparam integer ITERATION = 1000; //-------------------------------------------------- end setup localparam integer CLOCK_PERIOD = 120; localparam integer MAX_COUNTER_VAL = CLOCK_PERIOD - 1; localparam integer TEST_ITERATION = ITERATION * MAX_COUNTER_VAL; bit clk = '0; bit s_rst_n = '1; bit heart_beat = '0; integer counter = 0; heart_beat # ( .SPEED_GRADE (SPEED_GRADE ), .IS_DEBUG (IS_DEBUG ), .IS_BLINK (IS_BLINK ) ) heart_beat_dut ( .i_clk (clk ), .i_s_rst_n (s_rst_n ), .o_heart_beat (heart_beat) ); always begin #(CLOCK_PERIOD / 2) clk = !clk; end initial begin s_rst_n &lt;= '0; @(posedge clk); s_rst_n &lt;= '1; @(posedge clk); repeat(TEST_ITERATION) begin if (counter == MAX_COUNTER_VAL) begin counter = 0; end else begin counter++; end @(posedge clk); end $stop(); end endmodule </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T14:18:04.590", "Id": "270647", "Score": "1", "Tags": [ "verilog", "fpga", "systemverilog", "rtl" ], "Title": "Heart beat RTL module" }
270647
<p>Develop a program to maintain a list of homework assignments. When an assignment is assigned, add it to the list, and when it is completed, remove it. You should keep track of the due date. Your program should provide the following services:</p> <ol> <li>Add a new assignment.</li> <li>Remove an assignment.</li> <li>Provide a list of the assignments in the order they were assigned.</li> <li>Find the assignment(s) with the earliest due date.</li> </ol> <p>Just want to make sure I am doing this correctly. Should these methods in the Main class be happening in the Assignments class or is it fine as it is? Here is my code for both classes:</p> <p>Assignments Class:</p> <pre><code>import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class Assignments { private String assignmentName; private LocalDate date; public Assignments() { } public Assignments(String assignmentName, LocalDate date) { this.assignmentName = assignmentName; this.date = date; } public String getAssignmentName() { return assignmentName; } public void setAssignmentName(String assignmentName) { this.assignmentName = assignmentName; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } @Override public String toString() { return &quot;Assignment: &quot; + assignmentName + &quot;\nDue Date: &quot; + date; } } </code></pre> <p>Main Class:</p> <pre><code>import java.time.LocalDate; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Assignments assignment = new Assignments(); Scanner indata = new Scanner(System.in); //Creating an ArrayList of assignments List&lt;Assignments&gt; assignmentList = new ArrayList&lt;&gt;(); assignmentList.add(new Assignments(&quot;Assignment1&quot;, LocalDate.of(2021, 12, 10))); assignmentList.add(new Assignments(&quot;Assignment2&quot;, LocalDate.of(2021, 12, 14))); assignmentList.add(new Assignments(&quot;Assignment3&quot;, LocalDate.of(2021, 12, 9))); assignmentList.add(new Assignments(&quot;Assignment4&quot;, LocalDate.of(2021, 12, 7))); assignmentList.add(new Assignments(&quot;Assignment5&quot;, LocalDate.of(2021, 12, 13))); assignmentList.add(new Assignments(&quot;Assignment6&quot;, LocalDate.of(2021, 12, 7))); menu(assignment, indata, assignmentList); } private static void getEarliestDate(List&lt;Assignments&gt; assignmentList) { selectionSort(assignmentList); System.out.println(); int j = 0; for(int i = 0; i &lt; assignmentList.size(); i++) { if(assignmentList.get(i).getDate().isEqual(assignmentList.get(j).getDate())) { System.out.println(assignmentList.get(i)); } } } private static void printSortedList(List&lt;Assignments&gt; assignmentList) { selectionSort(assignmentList); for(int i = 0; i &lt; assignmentList.size(); i++) { System.out.println(assignmentList.get(i)); } } //Using the selection sort algorithm to sort list from earliest due date to latest due date private static void selectionSort(List&lt;Assignments&gt; assignmentList) { for(int i = 0; i &lt; assignmentList.size(); i++) { int pos = i; for(int j = i; j &lt; assignmentList.size(); j++) { if(assignmentList.get(j).getDate().isBefore(assignmentList.get(pos).getDate())) { pos = j; } } Assignments min = assignmentList.get(pos); assignmentList.set(pos, assignmentList.get(i)); assignmentList.set(i, min); } } //Method that gives menu options private static void menu(Assignments assignment, Scanner indata, List&lt;Assignments&gt; assignmentList) { int userInput = 1; while(userInput != 0) { System.out.println(&quot;Enter 1 to add an assignment&quot;); System.out.println(&quot;Enter 2 to remove an assignment&quot;); System.out.println(&quot;Enter 3 to get ordered list of assignments&quot;); System.out.println(&quot;Enter 4 to find earliest due date&quot;); userInput = indata.nextInt(); switch(userInput) { case 1: addAssignment(assignment, indata, assignmentList); System.out.println(); break; case 2: removeAssignment(indata, assignmentList, assignment); System.out.println(); break; case 3: printSortedList(assignmentList); System.out.println(); break; case 4: getEarliestDate(assignmentList); System.out.println(); break; default: userInput = 0; break; } } } private static void removeAssignment(Scanner indata, List&lt;Assignments&gt; assignmentList, Assignments assignment) { String assignmentInput; System.out.print(&quot;Remove an assignment: &quot;); assignmentInput = indata.next(); for(int i = 0; i &lt; assignmentList.size(); i++) { if(assignmentList.get(i).getAssignmentName().equals(assignmentInput)) { assignmentList.remove(i); } } } private static void addAssignment(Assignments assignment, Scanner indata, List&lt;Assignments&gt; assignmentList) { String assignmentInput; String dateInput; System.out.print(&quot;Assignment: &quot;); assignmentInput = indata.next(); assignment.setAssignmentName(assignmentInput); System.out.println(); System.out.print(&quot;Due date: (YYYY-MM-DD)&quot;); dateInput = indata.next(); assignment.setDate(LocalDate.parse(dateInput)); assignmentList.add(assignment); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T23:20:17.500", "Id": "534637", "Score": "0", "body": "Hey, can you please provide the actual text of the assignment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T23:32:47.210", "Id": "534639", "Score": "1", "body": "That is, the problem statement you're trying to solve." } ]
[ { "body": "<ul>\n<li><p>Right names.</p>\n<p>The class should be called <code>Assignment</code> singular, and instead of <code>assignmentName</code> one can drop <code>assignment</code>, maybe call it <code>topic</code> as <code>name</code> is too generic, misleading.</p>\n</li>\n<li><p>Your question: where what methods.</p>\n<p>You could create a class <code>Assignments</code> holding a <code>List&lt;Assignment&gt;</code> and providing operations on the list, scheduling, no conflicts, listing by date etcetera. This is defining an abstraction, a small algebra of operations that can be done on assigments: how many assignments there are and so on.</p>\n<p>The usage could then be done high level in the <code>Main</code> class; using <code>System.out</code> there.</p>\n</li>\n<li><p>Test Driven Development using unit tests, needs some learning; is worth it.</p>\n<p>There is also a solution I use: make a unit test, and test all functionality in a unit test:</p>\n<pre><code>@Test\npublic void testAdd() {\n Assignments assignments = new Assignments();\n assignments.add(...);\n assertEquals(1, assignments.size());\n}\n</code></pre>\n<p>This is Test Driven Development, and you rapidly develop the functionality\nand has a nice overview, sample code.</p>\n<p>In this case this would probably overkill. Main suffices.</p>\n</li>\n<li><p>Remove this irritating comment:</p>\n<pre><code> // TODO Auto-generated method stub\n</code></pre>\n</li>\n<li><p>A utility function <code>Collections.addAll</code>:</p>\n<pre><code>List&lt;Assignment&gt; assignmentList = new ArrayList&lt;&gt;();\nCollections.addAll(assignmentList,\n new Assignment(&quot;Assignment1&quot;, LocalDate.of(2021, 12, 10)),\n new Assignment(&quot;Assignment2&quot;, LocalDate.of(2021, 12, 14)),\n new Assignment(&quot;Assignment3&quot;, LocalDate.of(2021, 12, 9)),\n new Assignment(&quot;Assignment4&quot;, LocalDate.of(2021, 12, 7)),\n new Assignment(&quot;Assignment5&quot;, LocalDate.of(2021, 12, 13)),\n new Assignment(&quot;Assignment6&quot;, LocalDate.of(2021, 12, 7)));\n</code></pre>\n<p>There exists also <code>List.of(...)</code>.</p>\n</li>\n<li><p>There are some variations on for-like loops:</p>\n<pre><code>for (int i = 0; i &lt; assignmentList.size(); i++) {\n System.out.println(assignmentList.get(i));\n}\n\nfor (Assigment assignment: assignmentList.size()) {\n System.out.println(assignment);\n}\n\nassignmentList.forEach(a -&gt; System.out.println(a));\n</code></pre>\n</li>\n<li><p>In international software <code>ZonedDateTime</code> is more appriopriate and in the database a UTC time (Zero Zone). I just mention it, as LocalDate is fine here, but a future internationalized product should make that transition.</p>\n</li>\n<li><p>Your own <em>sort</em> is wasted effort.</p>\n<pre><code>assignmentList.sort(Comparator.comparing(Assignment::getDate)\n .thenComparing(Assigment::getAssignmentName));\n\nList&lt;Assignment&gt; sorted = assignmentList().stream()\n .sorted(Comparator.comparing(Assignment::getDate))\n .collect(Collectors.toList());\n</code></pre>\n<p>This might be a bit much for a beginner (some new complex concepts), but has quite some expressive power.</p>\n</li>\n<li><p>The operations you want to provide determine data structures too.</p>\n<p>A <code>List</code> is quite unstructured. If you want to to have a list by date, or search for a specific assignment. For a first version you can start with a List, and hide such implementation details inside a class Assignments (plural).</p>\n<p>First compose a list of operations you want to provide. This is the API, Application Programming Interface, the class.</p>\n</li>\n<li><p>The usage in Main:</p>\n<pre><code>System.out.println(&quot;Enter 1 to add an assignment&quot;);\n</code></pre>\n<p>Could simply be:</p>\n<pre><code>System.out.println(&quot;1. Add an assignment&quot;);\n...\nSystem.out.println(&quot;Enter a choice (1-4)&quot;);\nint userInput = indata.nextInt();\n</code></pre>\n<p>Declare variables at their first point of use.\nThe above has one problem: validation. One would need to do:</p>\n<pre><code>int userInput;\nif (indata.hasNextInt()) {\n userInput = indata.nextInt();\n} else {\n indate.next(); // Discard non-numeric input.\n userInput = 0;\n}\n...\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T17:38:20.763", "Id": "534664", "Score": "0", "body": "This answer seems well above the level of the OP and annoyed. It's tossing out a ton of information is clearly going to be new and take time to process." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T20:53:29.970", "Id": "534688", "Score": "0", "body": "@Xtros I appreciate your feedback. Though the OP's code was meager, and the level beginner, but not totally, I wanted to show the landscape of programming. Java has become so complex, that not mentioning unintroduced features seems no longer pedagogical. But right: I should not write on my own favorite topics, TDD was too much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T21:03:04.710", "Id": "534689", "Score": "1", "body": "But still... why call it meager? They're a beginner.\n\n@John S Despite my gripes, this answer has lot of concepts that are worth considering. Declaring variable at the first point of use is a key concept to understand and as is validating input. Don't ignore what's said here, but also don't be upset if any part of it doesn't make sense yet." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T01:24:07.370", "Id": "270656", "ParentId": "270650", "Score": "1" } }, { "body": "<p>@Joop Eggen has covered some good points. Another few other things to think about...</p>\n<ul>\n<li>Blank lines can help to break up logical sections of code. However it can be quite distracting to read code that uses too much, or inconsistent blank lines. Typically your IDE can be configured to help you maintain consistency for some of this type of spacing. (blank lines after <code>for</code> statements, at start of functions etc). It's very unusual to see 2, or 3 blank lines in the middle of a function/class.</li>\n</ul>\n<blockquote>\n<pre><code>for(int i = 0; i &lt; assignmentList.size(); i++) {\n \n int pos = i;\n for(int j = i; j &lt; assignmentList.size(); j++) {\n if(\n</code></pre>\n</blockquote>\n<ul>\n<li><p>&quot;Provide a list of the assignments in the order they were assigned.&quot; I seem to have interpreted this differently to you. To me this says, I should if I assign tasks &quot;1,2,3,4&quot; in that order, then I should be able to get them back in that order even if they're due to be completed &quot;4,3,2,1&quot;. All of your methods return the list ordered by due date.</p>\n</li>\n<li><p>None of your methods give any feedback if they don't do anything. Typically you'd expect something like &quot;No Assignments&quot;, &quot;That assignment doesn't exist&quot; etc.</p>\n</li>\n<li><p>Your menu's default interpretation is exit. Consider adding a specific option to exit, or checking if the user really wants to exit. It's quite frustrating if you hit the wrong key by accident and the application just exits and throws away the in memory database. Consider also how you might handle invalid input. For example what happens if the user types &quot;Important Assignment&quot; in response to:</p>\n</li>\n</ul>\n<blockquote>\n<pre><code>System.out.print(&quot;Due date: (YYYY-MM-DD)&quot;);\ndateInput = indata.next();\nassignment.setDate(LocalDate.parse(dateInput));\n</code></pre>\n</blockquote>\n<ul>\n<li>There's no validation to ensure that assignments don't have the same name. Is this a valid scenario? I might put call all my Maths assignments the same thing for example.</li>\n</ul>\n<p>If so, consider how your remove function would behave in various combinations. If not, consider if you might could stop looking after you find the first occurence of the assignment name...</p>\n<blockquote>\n<pre><code>for(int i = 0; i &lt; assignmentList.size(); i++) \n{ \n if(assignmentList.get(i).getAssignmentName().equals(assignmentInput)) \n { \n assignmentList.remove(i);\n</code></pre>\n</blockquote>\n<ul>\n<li><code>get</code> is usually used to prefix property getters. It sets an expectation that the method will return something. You <code>getEarliestDate</code> doesn't return anything. This feels like the code encouraging you to refactor the printing out of the method...</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T15:58:45.233", "Id": "270669", "ParentId": "270650", "Score": "2" } }, { "body": "<p>I'm going to borrow some from other answers but present it differently.</p>\n<p><strong>Assignment Class</strong></p>\n<ul>\n<li>As @Joop Eggen said, the right names are important and pluralization of classes often trips developers up. It's pretty rare that a class should be pluralized, though there are some cases. <code>Assignment</code> is a better name. It looks like the class used to be a list of assignments and then you changed it to be a single assignment.</li>\n<li>Within that, <code>assignmentName</code> is redundant. You already know that the name belongs to an assignment. Further, <code>date</code> is ambiguous. Is it the date that it was assigned or due? Your requirements suggest that both are needed, so let's keep track of both.</li>\n<li>You need the assigned date time in order to display the assignments in the order that they were assigned rather than just the date, so that field should be a <code>LocalDateTime</code>.</li>\n<li>That gives us <code>name</code>, <code>assignedDateTime</code>, and <code>dueDate</code>.</li>\n<li>These fields in the Assignment class do not need to change (according to your requirements), so you can remove the setter methods and mark those fields as final. These denote the fields as <strong>immutable</strong>, which is often valued as it can make a class easier to work with. If you make this change right away, it's going to break something that you do that I talk about later one. (Because I'm suggesting that you remove the setter methods.)</li>\n<li>I marked the Assignment class as final too, because you're not intending to create a subclass for it. If you haven't heard of inheritance yet, don't worry about this.</li>\n<li>I also removed the default constructor (the one with no parameters) because that enforces all users of this class to use the other constructor.</li>\n<li>In a professional environment, each parameter should be validated to ensure that it has good date. For example, making sure that the <code>name</code> is not null or an empty string. I'm leaving this out for now, but adding argument validation can make development easier (despite having more code).</li>\n<li>If you can use Java 15, then a record is exactly what you want.</li>\n</ul>\n<p>Pre-Java 15:</p>\n<pre><code>import java.time.LocalDate;\n\npublic final class Assignment {\n private final String name;\n private final LocalDate assignedDate;\n private final LocalDate dueDate;\n\n public Assignment(String name, LocalDate assignedDate, LocalDate dueDate) {\n this.assignmentName = assignmentName;\n this.assignedDate = assignedDate;\n this.dueDate = dueDate;\n }\n\n public String getName() {\n return name;\n }\n\n public LocalDate getAssignedDate() {\n return assignedDate;\n }\n\n public LocalDate getDueDate() {\n return dueDate;\n }\n\n @Override\n public String toString() {\n return &quot;Assignment: &quot; + name + &quot;\\nAssigned Date: &quot; + assignedDate + &quot;\\nDue Date: &quot; + dueDate;\n }\n}\n</code></pre>\n<p>Java 15+</p>\n<pre><code>public record Assignment(String name, LocalDate assignedDate, LocalDate dueDate)\n{ }\n</code></pre>\n<p><strong>HomeworkList Class</strong></p>\n<ul>\n<li>I do actually like the idea of having a class that represents the list of assignments, though I'd suggest a different name to help provide clarity. <code>HomeworkList</code>. <code>Assignments</code> just looks too similar to <code>Assignment</code>.</li>\n<li>See if you can come up with the contents of <code>HomeworkList</code>. What fields does it need? Are those immutable? (This is a bit tricky because you want the contents of the list to change, but not the list itself. Ask me if this doesn't make sense.)</li>\n<li>This HomeworkList should know absolutely nothing about Scanners or System.out. It's just holding data.</li>\n<li>It should be able to have an assignment added to it or removed.</li>\n<li>You currently load up the assignmentList inside your main method. You'll want to remove that before you submit your program, but it's helpful to have while you are testing it.</li>\n<li>The HomeworkList should be about to sort the assignments by assignedDate.</li>\n<li>The HomeworkList should be able to return the one or more assignments that have the earliest due date.</li>\n</ul>\n<p><strong>Main Class</strong></p>\n<ul>\n<li>What's left is a Main class that handles just the menu portion. How would you rewrite it to work with a HomeworkList?</li>\n<li>Something that might be tripping you up now, you create an Assignment in the main method, but why? Let's walk through what's really happening in your addAssignment method.</li>\n</ul>\n<ol>\n<li>You create a box to hold some data in the main method</li>\n<li>Then that box is passed to addAssignment</li>\n<li>In that box you place a name and a date taken from user input. Let's say &quot;Quiz&quot; due &quot;2021-12-06&quot;</li>\n<li>Then you place that box at the end of the list</li>\n<li>When you later print the list you see at the end</li>\n</ol>\n<blockquote>\n<p>&quot;Quiz due 2021-12-06&quot;</p>\n</blockquote>\n<p>So far that doesn't seem too far off. But let's add another assignment.</p>\n<ol start=\"6\">\n<li>That same box is passed to addAssignment</li>\n<li>You <strong>replace</strong> the name and date with new user input. &quot;Test&quot; due &quot;2021-12-10&quot;</li>\n<li>When you look at the list now, you see at the end</li>\n</ol>\n<blockquote>\n<p>&quot;Test due 2021-12-10&quot;</p>\n<p>&quot;Test due 2021-12-10&quot;</p>\n</blockquote>\n<p>?!?! What happened to the previous assignment? Why wasn't a new assignment created?</p>\n<p>Hopefully this all gets you going in the right direction. There are a bunch of handy little things that can be done to make your program more and more simple, but get the basics down first.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T19:10:04.017", "Id": "534683", "Score": "0", "body": "@John S if you make these changes and want further feedback, don't edit this question, but you can create a new question with the updated code. Provided it still works" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T18:28:29.603", "Id": "270674", "ParentId": "270650", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T20:08:12.490", "Id": "270650", "Score": "4", "Tags": [ "java" ], "Title": "Create a list of assignments" }
270650
<p>Everything currently works exactly as requested by the instructor, I've included as much possible commented documentation as I can think of to make it easier for people to see what the required criteria is for the project! Let me know what you guys think, I would really appreciated it!</p> <p>The program is disjointed as it is a culmination of almost everything we've learned this semester.</p> <p>The program is going to define a main function with at least 3 other embedded functions(any other functions will be extra credit). It must create a list of usernames, using a while loop to gather info from the user until they decide to stop, include a random number between the user's age and 99 (inclusively), add all the generated names to a list and display the names in lower case. It will then allow the user to test if a name is contained within the list, until they decide to stop. Write the user names to an empty text file titled 'username.txt'. Then it must calculate an average based on entered number of test scores and classify the average to a letter grade.</p> <pre><code>import random uNameList = [] def start(): #create the greeting function &quot;&quot;&quot;Present user with a greeting and program introduction&quot;&quot;&quot; print(&quot;&quot;&quot;======================================================================= Welcome to my Username generator and test-score-average-classifier. This program will allow you to create a set of user names by entering a user's first name, last name, and their age. You will then be able to check to see if a Username that you enter is currently in use. Finally, you will be able to enter in a number of test scores, get the average and return an equivalent letter grade. ======================================================================\n\n&quot;&quot;&quot;) def end(): #create the farewell function &quot;&quot;&quot;Offers farewell and thanks to the user&quot;&quot;&quot; print(&quot;&quot;&quot;\n\n====================================================================== You have reached the end of the Username generator and the test-score-average-classifier. Your Usernames will appear in a text file after you close out the program. Thank you for your time and have a wonderful day! Goodbye! ======================================================================&quot;&quot;&quot;) #my attempt at an extra credit function def lWriter(listName): &quot;&quot;&quot;This should be a simple call to create the text file&quot;&quot;&quot; f = open(&quot;username.txt&quot;, 'w') for names in listName: f.write(names+&quot;\n&quot;) f.close() def grader(tAverage): &quot;&quot;&quot;A function to classify they test averages into a letter grade&quot;&quot;&quot; if tAverage &gt;= 90: return &quot;A&quot; elif tAverage &gt;= 80 and tAverage &lt; 90: return &quot;B&quot; elif tAverage &gt;= 70 and tAverage &lt; 80: return &quot;C&quot; elif tAverage &gt;= 60 and tAverage &lt; 70: return &quot;D&quot; else: return &quot;F&quot; #create the averaging function def average(scoreTotal, tests): &quot;&quot;&quot;Returns an average based on number of tests ,and total score&quot;&quot;&quot; return scoreTotal/tests #create the main function def main(): start() #call the start function &quot;&quot;&quot;The main function will contain all additional functions&quot;&quot;&quot; print(&quot;Why don't we generate some Usernames first?\n&quot;) #time to gather user info and compile names into a list fname = input(&quot;What is the user's first name? &quot;) while fname != &quot;&quot;: lname = input(&quot;What is the user's last name? &quot;) age = int(input(&quot;What is the user's age? &quot;)) rNum = random.randint(age,100) uName = fname[-1]+lname[0:4]+str(rNum) uName = uName.lower() uNameList.append(uName) #give the user a chance to continue, or exit and move onto the next task fname = input(&quot;&quot;&quot;\nIf there is another user, please enter their first name. If not, simply press &lt;Enter&gt; to continue: &quot;&quot;&quot;) print (&quot;\nYour available Username choices are displayed below:&quot;) print() print (uNameList) print() #the user enters a new loop to test whether or not certain names are contained in the list uNameChoice = input(&quot;Enter a Username to check if it is contained in the list: &quot;) while uNameChoice != &quot;&quot;: if uNameChoice in uNameList: print (&quot;Yes, that user name is contained in the list.&quot;) print() else: print (&quot;No that user name is not contained in the list.&quot;) print() uNameChoice = input(&quot;&quot;&quot;Would you like to check another user name? If not, simply press &lt;Enter&gt; to continue: &quot;&quot;&quot;) print() #time to generate a test score average for the user print(&quot;Now we can move on to calculating the average of your tests!&quot;) print() tests = int(input(&quot;How many test grades would you like to enter?&quot;)) #I'm turning this into a loop as well, in case the user wants to check multiple sets of grades while tests != 0: scoreTotal = 0 for scores in range(tests): score = int(input(&quot;Please enter one of the grades: &quot;)) scoreTotal += score print() tAverage = average(scoreTotal,tests) print(&quot;The test score average is&quot;,round(tAverage,2),&quot;and the letter grade is:&quot;,grader(tAverage),end=&quot;.&quot;) print(&quot;\n\n&quot;) tests = int(input(&quot;&quot;&quot;If you'd like to check a new set of tests, please tell me how many there are. If not, then please simply type a '0' to end the program. &quot;&quot;&quot;)) lWriter(uNameList) #write all the usernames to the textfile before the program closes out print() end() #make sure to call main at the end of the program to ensure it will start automatically if __name__==&quot;__main__&quot;: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T21:15:37.733", "Id": "534631", "Score": "3", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T21:16:08.247", "Id": "534632", "Score": "2", "body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226). What are the exact requirements for this program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T21:42:49.697", "Id": "534633", "Score": "0", "body": "Sorry, I included what the program was supposed to do in the actual docstring in the coding. Let me reword my program setup" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T21:50:53.490", "Id": "534634", "Score": "0", "body": "I'm still really new to the site, so I appreciate the help getting things posted correctly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T10:03:16.470", "Id": "534654", "Score": "1", "body": "For what Python version did you write this?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T20:53:15.957", "Id": "270651", "Score": "1", "Tags": [ "python", "beginner", "homework" ], "Title": "Generate and display usernames" }
270651
<p>This is a working solution to <a href="https://adventofcode.com/2021/day/3" rel="nofollow noreferrer">today's Advent of Code puzzle</a>, written in Haskell. However, I feel like this solution is not optimal.</p> <pre class="lang-hs prettyprint-override"><code>module BinaryDiagnostic (parseInput, part1, part2) where import Control.Monad (liftM2) import Data.List (group, maximumBy, sort, transpose) import Data.Ord (comparing) bin2dec :: String -&gt; Integer bin2dec = foldl (\acc x -&gt; acc * 2 + read [x]) 0 mostCommonElems :: (Ord a) =&gt; [[a]] -&gt; [a] mostCommonElems = map (head . maximumBy (comparing length) . group . sort) . transpose bitNot :: String -&gt; String bitNot = map (\bit -&gt; if bit == '0' then '1' else '0') iterateMatch :: Eq a =&gt; ([[a]] -&gt; [a]) -&gt; [[a]] -&gt; [a] iterateMatch criterion = head . snd . until ((== 1) . length . snd) iterator . (,) 0 where iterator (n, xs) = (n + 1, filter ((criterion xs !! n ==) . (!! n)) xs) part1 :: [String] -&gt; String part1 = show . liftM2 (*) bin2dec (bin2dec . bitNot) . mostCommonElems part2 :: [String] -&gt; String part2 xs = show $ bin2dec (iterateMatch mostCommonElems xs) * bin2dec (iterateMatch (bitNot . mostCommonElems) xs) parseInput :: String -&gt; [String] parseInput = lines </code></pre> <p>You can test this solution by running</p> <pre class="lang-hs prettyprint-override"><code>part1 $ parseInput &quot;00100\n11110\n10110\n10111\n10101\n01111\n00111\n11100\n10000\n11001\n00010\n01010&quot; -- should return &quot;198&quot; part2 $ parseInput &quot;00100\n11110\n10110\n10111\n10101\n01111\n00111\n11100\n10000\n11001\n00010\n01010&quot; -- should return &quot;230&quot; </code></pre> <p>I am particularly looking for improvement suggestions regarding the following:</p> <ul> <li>How can I make the code more readable in general? (especially the <code>iterateMatch</code> function looks a bit hard to understand)</li> <li>Can I use existing functions from common packages to simplify some operations?</li> <li>How can I remove the redundancy in the <code>part2</code> function (and can it be pointfree)? Both operands of <code>*</code> do a very similar thing.</li> <li>Are there any parts that could be significantly optimized in terms of runtime performance?</li> </ul> <hr /> <p>Just very briefly, below is the task. The complete puzzle is linked above.</p> <p>The input is a line-separated list of binary numbers of fixed width, e. g.</p> <pre><code>00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010 </code></pre> <p>For <strong>part 1</strong>, for each bit position (0 to 4), we need to find the most common bit (either <code>0</code> or <code>1</code>). The most common bit for each of the 5 positions give us a new binary number γ. We do the same thing for the least common bits and get a binary number ε. For the example above, γ is <code>10110</code> and ε ist <code>01001</code>. Their product (in decimal) is the solution for part 1, in this case <code>10110</code> (22) times <code>01001</code> (9) is <strong>198</strong>.</p> <p>For <strong>part 2</strong>, we again find the most common bit for each position. However, after every step, we eliminate the binary numbers that have the opposite bit at that position. We repeat that process until only one binary number is left (<code>10111</code> in the example). The same thing for the least common bits give us another binary number (<code>01010</code> in the example). Again, their product is the solution for part 2, in this case <code>10111</code> (23) times <code>01010</code> (10) is <strong>230</strong>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T22:11:09.387", "Id": "270654", "Score": "2", "Tags": [ "performance", "programming-challenge", "haskell", "functional-programming" ], "Title": "Advent of Code 2021, Day 3 in Haskell" }
270654
<p><a href="https://i.stack.imgur.com/YfzVp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YfzVp.png" alt="screenshhot" /></a></p> <pre><code>def shuffle(): global deck positions = [i for i in range(52)] deck = [i for i in range(52)] cards = [A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K] for c in cards: for r in range(4): ind = random.randint(0, (len(positions) - 1)) deck[ind] = c del positions[ind] </code></pre> <p>this function is the only thing that modifies the deck, how is that even possible</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T23:27:27.743", "Id": "534638", "Score": "1", "body": "Welcome to Code Review! Please confirm: is the code working as expected?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T00:09:06.347", "Id": "534641", "Score": "1", "body": "no, the hands on the right should only contain elements of the list \"cards\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T00:36:36.653", "Id": "534642", "Score": "1", "body": "Thank you for your response. Unfortunately this question is _off-topic_ because this site is for reviewing **working** code. Please [take the tour](https://codereview.stackexchange.com/tour) and read up at our [help center](https://codereview.stackexchange.com/help/on-topic). When the code works then feel free to [edit] the post to include it for a review." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T23:15:48.783", "Id": "270655", "Score": "-4", "Tags": [ "beginner", "python-3.x" ], "Title": "tried to make blackjack in python, deck that should only contain standard cards somehow has 52s in it" }
270655
<p><a href="https://i.stack.imgur.com/Adpkq.jpg" rel="nofollow noreferrer">Here is what it should look like</a> I am having trouble aligning the first day of the month with the right weekday. The calendar is going to be for this year so January first will be on Friday but I cant seem to get any of firsts of each month off of the left side. I tried to change the setw but its not working for some reason. <a href="https://i.stack.imgur.com/w1Fas.jpg" rel="nofollow noreferrer">Here is what mine looks like now</a></p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;iomanip&gt; using namespace std; void month(int days, int day) { int i; string weekDays[7] = { &quot; Sun &quot;, &quot; Mon &quot;, &quot; Tue &quot;, &quot; Wed &quot;, &quot; Thu &quot;, &quot; Fri &quot;, &quot; Sat &quot; }; cout &lt;&lt; endl &lt;&lt; &quot; &quot; &lt;&lt; endl; for (i = 0; i &lt; 7; i++) { cout &lt;&lt; left &lt;&lt; setw(1) &lt;&lt; &quot; &quot; &lt;&lt; weekDays[i]; } cout &lt;&lt; endl &lt;&lt; &quot; &quot; &lt;&lt; endl; int firstDay = day - 1; for (int i = 1; i &lt;= days; i++) { cout &lt;&lt; setw(5) &lt;&lt; &quot; &quot; &lt;&lt; setw(2) &lt;&lt; i; if ((i + firstDay - 1) % 7 == 0) { cout &lt;&lt; endl; } } } int main(){ int i, day = 1; int yearly[12][2] = { {1,31},{2,28},{3,31},{4,30},{5,31},{6,30},{7,31},{8,31},{9,30},{10,31},{11,30},{12,31} }; string months[] = { &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; }; for (i = 0; i &lt; 12; i++) { cout &lt;&lt; endl &lt;&lt; &quot; -------------------- &quot;&lt;&lt;months[i] &lt;&lt; &quot; -------------------- &quot;&lt;&lt; endl; month(yearly[i][1], day); if (day == 7) { day = 1; } else { day = day + 1; } cout &lt;&lt; endl; } return 0; </code></pre> <p>}</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T06:42:10.617", "Id": "534649", "Score": "0", "body": "Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T06:43:14.177", "Id": "534650", "Score": "0", "body": "I wonder why this is tagged with [object-oriented]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T07:52:00.793", "Id": "534652", "Score": "0", "body": "(The easiest way to drop blocks of code in a \"markdown post\" is to \"fence it in\" lines containing just `~~~` before&after.)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T03:54:30.490", "Id": "270657", "Score": "-1", "Tags": [ "c++" ], "Title": "C++ Calendar Alignment" }
270657
<p>I created a BaseRoute class route handling.</p> <p>The BaseRoute class takes the following parameters:</p> <pre><code> 1. prefix - the name of the endpoint such as posts 2. service - the service it has to call such as post_service 3. response_model:Pydantic Model - the response it will return 4. create_schema: Pydantic Model - the object type for creae 5. create_tag :Boolean - Whether itll create a tag for docs 6. update_schema: Pydantic Model - the object type for updating </code></pre> <p><strong>Immediately after creating it calls the initialize_routes methods to register the endpoints</strong></p> <p>Below is my code:</p> <pre><code>from fastapi import Depends, APIRouter from utils.service_result import handle_result from services.main import DBSessionMixin from routers.abstract_base import ABSRouter from services.base import BaseService from pydantic import BaseModel from typing import List from sqlalchemy.ext.asyncio import AsyncSession class BaseRoute(ABSRouter): def __init__( self, prefix: str, service: BaseService, response_model: BaseModel, create_schema: BaseModel, create_tag: bool = False, update_schema: BaseModel = None, ): if create_tag: self.router = APIRouter(prefix=&quot;/&quot; + prefix, tags=[&quot; &quot;.join(prefix.split(&quot;/&quot;)).title()]) else: self.router = APIRouter(prefix=&quot;/&quot; + prefix) self.service = service self.response_model = response_model self.create_schema = create_schema self.update_schema = update_schema self.initialize_routes() def initialize_routes(self): self.get() self.post() self.get_one() self.put() self.delete() def get(self): @self.router.get(&quot;&quot;, response_model=List[self.response_model], status_code=200) async def get(search: str = None, page_size: int = 10, page: int = 1, db=Depends(DBSessionMixin.get_session)): result = await self.service.get_many(db, search=search, page_size=page_size, page=page) print(result) return handle_result(result) def post(self): @self.router.post(&quot;&quot;, response_model=self.response_model, status_code=201) async def post(data_in: self.create_schema, db: AsyncSession = Depends(DBSessionMixin.get_session)): result = await self.service.create(db, data_in) return handle_result(result) def get_one(self): @self.router.get(&quot;/{id}&quot;, response_model=self.response_model, status_code=200) async def get_one(id: int, db: AsyncSession = Depends(DBSessionMixin.get_session)): result = await self.service.get_one(db, id) return handle_result(result) def put(self): @self.router.put(&quot;/{id}&quot;, response_model=self.response_model, status_code=200) async def update(id: int, data_in: self.update_schema, db: AsyncSession = Depends(DBSessionMixin.get_session)): result = await self.service.update(db, id, data_in) return handle_result(result) def delete(self): @self.router.delete(&quot;/{id}&quot;, status_code=200) async def delete(id: int, db: AsyncSession = Depends(DBSessionMixin.get_session)): result = await self.service.remove(db, id) return handle_result(result) </code></pre> <p><strong>Problems with the current BaseRoute:</strong></p> <ol> <li>Need to rewrite the <strong>initialize_routes</strong> method if I add any extra routes.</li> <li>Authentication, need to <strong>override</strong> method if I want to add authentication.</li> </ol> <p>My question is <em><strong>Is this a good decision ? If this is, then how can I improve my code ? If this isn't, can someone please explain why it isn't</strong></em></p> <p><em><strong>Why we don't use OOP in case of routing ? Why we kind of repeat the same six lines over and over again ? I do understand that a lot of routes might require multiple service calls an etc.</strong></em></p> <p><a href="https://gist.github.com/anotherChowdhury/3b85f0191a1f7656528ea00ed259ff10" rel="nofollow noreferrer">Here's the link for the gist of my base route,base service and base repo</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T07:59:04.873", "Id": "270659", "Score": "0", "Tags": [ "python", "object-oriented", "design-patterns" ], "Title": "Object Oriented Routing using Python's FastAPI" }
270659
<p>Given a list of integers a 2D graph has to be plotted taking 1st, 3rd, 5th, ... numbers as upward slope and 2nd, 4th, ... numbers as downward slope.</p> <p>I have used a Python list to do it. Is there any further optimization possible with Python?</p> <h2>Sample input:</h2> <blockquote> <p>3, 1, 2, 3, 6, 2, 3, 6, 2, 3, 6, 3, 2, 3, 6, 2, 3, 4, 3, 2, 5, 4, 2, 1, 2, 1, 2, 3, 1, 2, 6, 2, 3, 6, 2, 3, 6, 3, 2, 3, 1, 5, 3, 2, 1, 2, 4, 2, 1, 8, 1, 2</p> </blockquote> <h2>My code:</h2> <pre><code>data = [3, 1, 2, 3, 6, 2, 3, 6, 2, 3, 6, 3, 2, 3, 6, 2, 3, 4, 3, 2, 5, 4, 2, 1, 2, 1, 2, 3, 1, 2, 6, 2, 3, 6, 2, 3, 6, 3, 2, 3, 1, 5, 3, 2, 1, 2, 4, 2, 1, 8, 1, 2] length = sum(data) print_list=[] def populate_list(): top = -1 #to keep track of max x-axis of list x=0 y=0 for i in range(0,len(data)): if i % 2==0: for _ in range(0,data[i]): if x&gt;top: print_list.append([]) top=x for _ in range(0,length): #to initialize a new top list print_list[x].append(&quot; &quot;) print_list[x][y]=&quot;/&quot; x+=1 y+=1 else: for _ in range(0,data[i]): x-=1 print_list[x][y]=&quot;\\&quot; y+=1 populate_list() for i in range(len(print_list)-1,-1,-1): #printing from bottom up since generated graph is inverted print(''.join(map(str,print_list[i]))) </code></pre> <h2>OUTPUT:</h2> <pre class="lang-none prettyprint-override"><code> /\ /\ / \ /\ / \/ \ / \ /\ /\ /\ / \ / \/ \ / \ /\/ \ / \ /\ / \/\ /\ / \ /\/ \/\ / \/ \ / \ /\ /\ / \ /\ / \/ \/ \/ \ /\ / \/\ /\ / \/ \ / \/ \ / \/\ / \ /\ / \ /\ / \/ \/ \/ \ / \/ \ / \ /\ / \ / \ / \/ \ / \ /\ / \ /\ / \/ \ /\/ \ / \/ \ / \ / \/ \/ \/\ / \ </code></pre>
[]
[ { "body": "<p><strong>Some simple things:</strong></p>\n<p>check out</p>\n<p><code>top</code> and <code>length</code> could probably have better names (Top of what? Length of what?), maybe <code>max_x</code>, <code>max_y</code>? And <code>print_list</code> could be better as e.g. <code>graph</code> and <code>populate_list</code> as <code>create_graph</code>?</p>\n<p>also <code>print_list</code> should probably be a local variable inside <code>populate_list()</code>, which can then return the list for you to print. Might also be better for it to take data as an argument.</p>\n<p><strong>Simplification</strong></p>\n<p>Instead of this:</p>\n<pre><code>if x&gt;top:\n print_list.append([])\n top=x\n for _ in range(0,length): #to initialize a new top list\n print_list[x].append(&quot; &quot;)\n</code></pre>\n<p>you could do:</p>\n<pre><code>if x+1 &gt; len(graph):\n graph.append([&quot; &quot;] * length)\n</code></pre>\n<p>(top is only used once so <code>len(graph)</code> works just as well, but we need to +1 to x because 0-indexed lists!)</p>\n<p>Your final print could be simplified a lot (using 'range' to then iterate over a list is a good sign you could do something with iterators):</p>\n<pre><code>for i in print_list[::-1]: #printing from bottom up since generated graph is inverted\n print(&quot;&quot;.join(i))\n</code></pre>\n<p>You can also see your main for loop could do something similar, but because we need to track the iterator as well as the value we can use <code>enumerate</code> to get both:</p>\n<pre><code>for i, n in enumerate(data):\n if i % 2==0:\n for _ in range(n):\n</code></pre>\n<p>and while I'm looking at that loop, I see that your two 'for _` loops are basically identical except one goes up, and one goes down. So with some refactoring we can combine them into one.</p>\n<p><strong>Putting it all together we get</strong></p>\n<pre><code>def populate_graph(data):\n graph = []\n max_y = sum(data)\n x,y = 0,0\n \n for i, n in enumerate(data):\n for _ in range(data[i]):\n if i%2 == 0:\n if x+1 &gt; len(graph):\n graph.append([&quot; &quot;] * max_y)\n \n graph[x][y]=&quot;/&quot;\n x += 1\n \n else: \n x -= 1\n graph[x][y]=&quot;\\\\&quot; \n \n y+=1\n \n return graph[::-1] #polite to prove a right-way-up-graph\n\nif __name__ == &quot;__main__&quot;:\n \n data = [3, 1, 2, 3, 6, 2, 3, 6, 2, 3, 6, 3, 2, 3, 6, 2, 3, 4, 3, 2]\n \n for row in populate_graph(data): \n print(&quot;&quot;.join(row))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T11:54:11.747", "Id": "270664", "ParentId": "270660", "Score": "4" } }, { "body": "<p><strong>Global variables rarely needed</strong>. You have written most of the algorithm inside of a function, which is good;\nhowever, you are not really taking full advantage of what functions offer. In\nparticular, they take arguments and return data. You aren't doing that;\ninstead, your function operates on global variables, which is bad in nearly all\ncases.</p>\n<p><strong>Don't make the caller work too hard</strong>. I would describe the algorithm in your function as only partially implemented,\nbecause it forces the caller to engage in further machinations in order to\nprint it. If the purpose of the function is to generate data that can easily be\nprinted as an ASCII line graph, then the printing itself should be trivially\neasy.</p>\n<p><strong>Avoid tight algorithmic coupling with printing, when feasible</strong>.The algorithm is also tightly coupled to printing. On the one hand, that makes\nsense: we are solving a made-up programming challenge, so we should focus on the\nconcrete challenge at hand. However, one can often develop better programming\nhabits by broadening one's perspective. Instead of writing an algorithm that is\nnarrowly targeted to printing, one can approach the problem like this: (1)\nconvert the raw input data into some other type of data that contains the same\ninformation but in a more useful form; (2) convert the generally-more-useful\ndata into what we need specifically for printing.</p>\n<p><strong>Test algorithms with a wider range of inputs</strong>. Finally, your algorithm is a bit fragile. It has some special case logic to add\na new row to <code>print_list</code> whenever the line slopes upward. But what about when\nthe line slopes downward? For example, consider a very simple case where the\ninput data is <code>[3, 7]</code>. The code will add 3 rows on the upward direction, but\nthen the big downward movement of 7 will require that we add rows on the lower\nportion of the graph. Your code blows up with an <code>IndexError</code>.</p>\n<p><strong>My thought process</strong>. In the rest of this reply, I'll describe the thought process I used in solving\nthe problem. We begin with a solid program structure that uses functions, not\nglobal variables, and that will place no excessive burdens on the caller of our\nfunction when it comes time to print:</p>\n<pre><code>def main():\n input_data = [3, 1, ...]\n for row in ascii_line_graph(input_data):\n # Printing will be easy: no algorithmic logic required.\n print(row)\n\ndef ascii_line_graph(input_data):\n rows = []\n ...\n return rows\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>I decided first to convert the idiosyncratic input data into a more generally\nuseful format: a list of <code>Point</code> objects, where each point knows its x-y\ncoordinates and its marker style (up or down). This data conversion doesn't\nsolve the real problem yet, but my intuition is that this generally useful way\nof storing the data will be amenable to further conversions that are needed for\nthe ultimate printing.</p>\n<pre><code>from dataclasses import dataclass\n\ndef main():\n input_data = [3, 1, 2]\n for row in ascii_line_graph(input_data):\n print(row)\n\ndef ascii_line_graph(input_data):\n # Not fully implemented yet.\n # So far, we're just creating Point instances.\n for p in get_points(input_data):\n yield p\n\ndef get_points(input_data):\n x, y = (-1, 0)\n for i, nsteps in enumerate(input_data):\n slope = -1 if i % 2 else 1\n for _ in range(nsteps):\n x += 1\n y += slope\n yield Point(x, y, slope)\n y += slope\n\n@dataclass(frozen = True)\nclass Point:\n x: int\n y: int\n slope: int\n\n @property\n def marker(self):\n return '/' if slope == 1 else '\\\\'\n</code></pre>\n<p>The only remaining step is to convert the list of Point instances into a row-oriented\nASCII graph. That requires some sorting and grouping.</p>\n<pre><code>from operator import attrgetter\nfrom itertools import groupby\n\ndef ascii_line_graph(input_data):\n # Sort the Points by their y values, in descending order.\n y_key = attrgetter('y')\n points = sorted(get_points(input_data), key = y_key, reverse = True)\n\n # Get the stop value for chart width.\n x_stop = 1 + max(p.x for p in points)\n\n # Process the points in groups, based on their y values.\n for y, group in groupby(points, y_key):\n # A dict of the marked points for the current row.\n markers = {p.x : p.marker for p in group}\n\n # Yield the full row.\n row = ''.join(markers.get(x, ' ') for x in range(x_stop))\n yield row.rstrip()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T19:14:10.790", "Id": "270679", "ParentId": "270660", "Score": "2" } }, { "body": "<ul>\n<li>Move your <code>data</code>, etc. out of the global namespace into functions</li>\n<li>Rather than doing an even/odd check on an index, consider doing the slightly more Pythonic thing of a slice <code>[::2]</code> and <code>zip</code></li>\n<li>Consider making a generator function that converts deltas to height values</li>\n<li>Separate your rendering code that uses <code>/\\</code> from your logical code that calculates heights</li>\n<li>Avoid your <code>for i in range</code>; changing iteration methods on an iterable is more Pythonic than manipulating indices</li>\n<li>Use PEP484 type hints</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from typing import Collection, Iterator, List, Tuple, Iterable\n\n\ndef heights_with_end(start: int, n: int, direction: int) -&gt; Tuple[range, int]:\n end = start + direction*n\n return range(start, end, direction), end - direction\n\n\ndef data_to_heights(data: Collection[int]) -&gt; Iterator[Tuple[bool, range]]:\n ups = data[::2]\n downs = data[1::2]\n height = 0\n for up, down in zip(ups, downs):\n segment, height = heights_with_end(height, up, 1)\n yield True, segment\n segment, height = heights_with_end(height, down, -1)\n yield False, segment\n\n\ndef make_grid(deltas: Collection[int]) -&gt; List[List[str]]:\n segments = tuple(data_to_heights(deltas))\n width = sum(deltas)\n flat = [y for is_up, segment in segments for y in segment]\n bottom = min(flat)\n height = max(flat) - bottom\n grid = [\n [' ']*width\n for _ in range(1 + height)\n ]\n\n x = 0\n for is_up, segment in segments:\n for y in segment:\n grid[height + bottom - y][x] = '/' if is_up else '\\\\'\n x += 1\n\n return grid\n\n\ndef print_grid(grid: Iterable[Iterable[str]]) -&gt; None:\n print(\n '\\n'.join(\n ''.join(line) for line in grid\n )\n )\n\n\ndef test() -&gt; None:\n data = (\n 3, 1, 2, 3, 6, 2, 3, 6, 2, 3, 6, 3, 2, 3, 6, 2, 3, 4, 3, 2, 5, 4, 2, 1,\n 2, 1, 2, 3, 1, 2, 6, 2, 3, 6, 2, 3, 6, 3, 2, 3, 1, 5, 3, 2, 1, 2, 4, 2,\n 1, 8, 1, 2,\n )\n grid = make_grid(data)\n print_grid(grid)\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T21:15:39.810", "Id": "534690", "Score": "0", "body": "Plenty of good advice here, and in the useful answer from @JeffUK, but I think both fail in the same way the OP's code fails, with an IndexError if the line crosses below the initial point. (But it's possible I missed a detail outlawing such inputs.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T22:10:11.577", "Id": "534694", "Score": "0", "body": "@FMc You're right. Works for sample input but not for the scenario you describe. Will edit later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T23:23:38.670", "Id": "534697", "Score": "1", "body": "@FMc Should be fixed" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T19:55:48.793", "Id": "270680", "ParentId": "270660", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T08:26:01.810", "Id": "270660", "Score": "7", "Tags": [ "python", "graph", "data-visualization", "ascii-art" ], "Title": "Draw a 2d graph using slashes" }
270660
<p>My favourite 3rd party library isn't getting maintained so now I need to make my own library for interfacing with Riot Games' API. Epic.</p> <p>Problem is that there are <em>rules</em>, such as:</p> <ul> <li>100 requests in 2 minutes</li> <li>20 requests in 1 second</li> </ul> <p>So I made an API request scheduler.</p> <pre class="lang-py prettyprint-override"><code>import asyncio import time from collections import deque from typing import Deque import httpx class SingleRegionCoordinator: WAIT_LENIENCY = 2 def __init__(self, subdomain: str) -&gt; None: self.subdomain = subdomain self.calls: Deque[float] = deque() self.base_url = f&quot;https://{subdomain}.api.riotgames.com&quot; self.force_wait = 0 def _schedule_call(self) -&gt; float: &quot;&quot;&quot; Schedule an API call. This call must be atomic (call finishes before being called by another coroutine). Returns: float: The time in seconds to wait to make the API call &quot;&quot;&quot; now = time.time() # Remove all calls older than 2 minutes while self.calls and self.calls[0] &lt; now - 120: self.calls.popleft() # Figure out how long to wait before there will be less than 100 calls # in the last 2 minutes worth of requests rate_1s_time, rate_2m_time = 0, 0 if len(self.calls) &gt;= 100: rate_2m_time = ( self.calls[-100] + 120 + SingleRegionCoordinator.WAIT_LENIENCY ) # Figure out how long to wait before there will be less than 20 calls # in the last second worth of requests if len(self.calls) &gt;= 20: rate_1s_time = ( self.calls[-20] + 1 + SingleRegionCoordinator.WAIT_LENIENCY ) scheduled_time = max(self.force_wait, rate_2m_time, rate_1s_time, now) self.calls.append(scheduled_time) return scheduled_time - now async def _api_call( self, method: str, path: str, params: dict = None ) -&gt; dict: &quot;&quot;&quot; Make an API call Args: method: The HTTP method to use path: The path to the API endpoint params: The parameters to pass to the API endpoint Returns: dict: The API response &quot;&quot;&quot; # Schedule the call wait_time = self._schedule_call() await asyncio.sleep(wait_time) url = f&quot;{self.base_url}{path}&quot; headers = {&quot;X-Riot-Token&quot;: &quot;code edited for codereview&quot;} response = await httpx.request( method, url, headers=headers, params=params ) res = response.json() # Check if we got a rate limit error if res[&quot;status&quot;][&quot;status_code&quot;] == 429: # Let the scheduler know that we are in trouble self.force_wait = ( time.time() + 120 + SingleRegionCoordinator.WAIT_LENIENCY ) return await self._api_call(method, path, params) return res </code></pre> <p>We can see it in action (sort of) with some quick test code to see what it tries to achieve:</p> <pre class="lang-py prettyprint-override"><code># Not recommended in practice but makes this example clearer SingleRegionCoordinator.WAIT_LENIENCY = 0 src = SingleRegionCoordinator(&quot;&quot;) for _ in range(120): src._schedule_call() arr = np.array(src.calls) # arr is now the time to wait that the function tells all of the API calls arr -= arr.min() print(arr) </code></pre> <p>Output:</p> <pre><code>[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 4. 120. 120. 120. 120. 120. 120. 120. 120. 120. 120. 120. 120. 120. 120. 120. 120. 120. 120. 120. 120.] </code></pre> <p>Works as intended. It greedily schedules API calls as soon as possible, but respects the rules.</p> <p>I know that:</p> <ul> <li>This solution won't horizontally scale.</li> <li>If the application closed/reopened it's going to run into a little trouble (though it can resolve by itself).</li> <li>Exponential backoff is the typical go-to solution for error handling with APIs. However, I find it to be no good with rate limit scenarios, as batching, say, 1000 requests would eventually lead you to be waiting way more time than you need. This is supposed to be the optimal scheduler.</li> <li>There are additional techniques such as caching requests.</li> </ul> <p>My main questions are:</p> <ul> <li>What are the general best practices when it comes to dealing with API rate limiting? This solution works in my mind but I have little idea how it's actually going to behave in the wild.</li> <li>Code style is fine? I now use the Black autoformatter with line length 79 plus import ordering (builtin, external, internal, alphabetical). Is 79 line length a thing of the past yet or is that not important? I like short line lengths because it means I can put multiple scripts side-by-side easily.</li> <li>Is <code>-&gt; dict</code> OK? I really like Typescript's <code>interface</code>, where I could do something like:</li> </ul> <pre><code>interface SomethingDTO { id: string data: Array&lt;SomethingElseDTO&gt; } </code></pre> <p>Instead now I have to write classes and... you know. A lot of work and honestly, hardly worth the effort either. Or am I delusional? Even this <a href="https://stackoverflow.com/a/48255117/5524761">suggested alternative</a> is not that good since it doesn't deal with nested objects. Some <a href="https://developer.riotgames.com/apis#match-v5/GET_getMatch" rel="nofollow noreferrer">API responses are also just a straight PITA</a> to typehint.</p>
[]
[ { "body": "<p>Don't use <code>time.time</code>; use <code>time.monotonic</code> - otherwise, certain OS time changes are going to deliver a nasty surprise.</p>\n<p>Make a constant for your 120 seconds.</p>\n<p>You ask:</p>\n<blockquote>\n<p>Is <code>-&gt; dict</code> OK?</p>\n</blockquote>\n<p>Not really. This:</p>\n<pre><code>params: dict = None\n</code></pre>\n<p>is first of all incorrect since it would need to be <code>Optional[dict]</code>, which is basically <code>Optional[Dict[Any, Any]]</code>. Setting aside the outer <code>Optional</code>, in decreasing order of type strength, your options are roughly:</p>\n<ul>\n<li><a href=\"https://docs.python.org/3/library/typing.html#typing.TypedDict\" rel=\"nofollow noreferrer\"><code>TypedDict</code></a></li>\n<li><code>Dict[str, str]</code> if all of your values are strings but you don't enforce key names</li>\n<li><code>Dict[str, Union[...]]</code> if you know of a value type set and don't enforce key names</li>\n<li><code>Dict[str, Any]</code> if you have no idea what the values are</li>\n</ul>\n<p>That's all assuming that you're stuck using a dictionary. Keep in mind that all of the above hinting is hinting only, and is not enforced in runtime. If you want meaningful runtime type enforcement (which, really, you should) then move to <code>@dataclass</code>es. They're really not a PITA; they're basically the lightest-weight class definition mechanism and have a convenience <a href=\"https://docs.python.org/3/library/dataclasses.html?highlight=dataclass#dataclasses.asdict\" rel=\"nofollow noreferrer\">asdict</a> which makes API integration a breeze. This is effort worth investing if you at all care about program correctness.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-05T00:13:47.167", "Id": "270689", "ParentId": "270661", "Score": "1" } } ]
{ "AcceptedAnswerId": "270689", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T10:05:02.937", "Id": "270661", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "API call scheduler for Python" }
270661
<p>I'm learning regex for c++, and tried to make a simple function. It is very small but I'm satisfied, because this is the first time I managed to pass function as argument. This is a replace function. Please give me tips on how to improve:</p> <pre><code>std::string Replace(std::string text, std::regex reg, std::function&lt;std::string(std::smatch)&gt; func){ std::smatch matcher; std::string result = &quot;&quot;; while (std::regex_search(text, matcher, reg)) { result += matcher.prefix().str(); result += func(matcher); text = matcher.suffix().str(); } result += text; return result; } </code></pre> <p>Now here is a test, I pass a javascript like formatted string, with regex <code>\\$\\{\\s*([a-zA-Z0-9]*?)\\s*\\}</code> and I put my name and age into a variable.</p> <pre><code>int main(){ std::string name = &quot;Ihsan&quot;; std::string age = &quot;13&quot;; std::string text = &quot;hello my name is ${name}, and im ${age} years old.&quot;; std::regex pattern(&quot;\\$\\{\\s*([a-zA-Z0-9]*?)\\s*\\}&quot;); std::cout &lt;&lt; Replace(text, pattern, [name, age](auto matcher) -&gt; std::string{ std::string str1 = matcher.str(1); if(str1 == &quot;name&quot;){ return name; } if(str1 == &quot;age&quot;){ return age; } }); } </code></pre> <p>Output is:</p> <pre><code>hello my name is Ihsan, and im 13 years old. </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T10:29:11.783", "Id": "270662", "Score": "1", "Tags": [ "c++", "regex" ], "Title": "Replace function for C++" }
270662
<p>I am trying to solve the following exercise:</p> <p>&quot;Consider a function ​ removePrimes() be a C function that takes as input an array of integers, removes all numbers that are prime, and returns the compacted version of the array. Create an array of 200 integers, with random values between 7 and 13, and call ​ removePrimes()​ on the just filled array.&quot;</p> <p>I used the following code in order to solve the task</p> <pre><code> #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void print_ar(int* ar, int len){ for (int i = 0; i &lt; len; i++){ printf(&quot;%d &quot;, ar[i]); } printf(&quot;\n&quot;); } int is_prime(int n ){ if (n==1){ return 1; } if (n == 2){ return 1; } for (int i=2; i&lt;n;i++){ if (n % i == 0){ return 0; } } return 1; } int* removePrimes(int* ar, int len, int* new_len){ int k = 0; int* temp = calloc(0, sizeof(int)); for (int i =0;i &lt; len; i++){ if ( is_prime(ar[i]) == 1) { continue; } else{ k=k+1; temp = realloc(temp, sizeof(int) * k); temp[k-1] = ar[i]; } } free(ar); // is this the correct use of free()? // *new_len = k; return temp; } int main() { int n=0; while (n&lt;200){ printf(&quot;Insert an integer greater than 200: &quot;); scanf(&quot;%d&quot;, &amp;n); } int* arr = malloc( n * sizeof(int)); for (int i =0;i&lt;n;i++){ int k =rand()%7 +7; arr[i] = k; } int new_len = 0; print_ar(arr,n); printf(&quot;\n&quot;); arr = removePrimes(arr, n, &amp;new_len); print_ar(arr,new_len); } </code></pre> <p>I am not sure about the usage of the free() function on the previous array. Is the free function used correctly, inside the removePrimes() function? Or should I call the free() outside, inside the main?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T18:36:03.980", "Id": "534671", "Score": "0", "body": "user252524: `if (n==1){ return 1; }` --> Usually 1 is not considered a _prime_." } ]
[ { "body": "<p>Given that all the values are between 7 and 13, we can implement <code>is_prime()</code> much more efficiently:</p>\n<pre><code>bool is_prime(int n)\n{\n switch(n) {\n case 7: case 11: case 13: return true;\n default: return false;\n }\n}\n</code></pre>\n<hr />\n<p>In <code>removePrimes()</code>, we allocate and reallocate memory without checking for failure. <strong>Always</strong> test the return value from allocation functions is non-null before using it.</p>\n<p>This is especially bad:</p>\n<pre><code> temp = realloc(temp, sizeof(int) * k);\n</code></pre>\n<p>If <code>realloc()</code> returns a null pointer, then we have overwritten our only pointer to the memory that was allocated, so we can never free it - that's a memory leak.</p>\n<p>According to the problem specification, I don't think we need to allocate any new memory - we could return values in the passed-in memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T21:48:27.013", "Id": "534693", "Score": "0", "body": "Thanks for the advice. So it would be sufficient to add an if condition that check if temp is not NULL, am I right? Secondly, if I wanted to keep the solution as it is, the free() called on 'ar' inside the removePrimes() function is working correctly?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T18:50:43.360", "Id": "270676", "ParentId": "270663", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T10:54:19.323", "Id": "270663", "Score": "1", "Tags": [ "c", "array" ], "Title": "Given an array of integers randomly selected from 7 to 13 (included), build a function that remove the primes in the array" }
270663
<p>I am trying to find all the &quot;missing&quot; devices in our database. Therefore I filter for the existing device ids and then prepare the data to be presentable and usable. The question I have is if there is any way to speed this up. Especially in the beginning <code>existing_device_ids</code> can even be empty and so the entire collection has to be grouped. I have an index on the internal_id, but in the group stage MongoDB doesn't use any indexes.</p> <pre><code>mongo_col.aggregate([ {&quot;$match&quot;: {&quot;internal_id&quot;: {'$nin': existing_device_ids}}}, { &quot;$group&quot;: { &quot;_id&quot;: &quot;$internal_id&quot;, &quot;protocol&quot;: {&quot;$first&quot;: &quot;$protocol&quot;}, &quot;configs&quot;: {&quot;$addToSet&quot;: &quot;$config&quot;}, &quot;document_count&quot;: {&quot;$sum&quot;: 1}, &quot;last_ts&quot;: {&quot;$last&quot;: &quot;$data.timestamp&quot;} } }] </code></pre> <p>Is there any better way to do exactly this? Or is it somehow possible to speed up this process?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T12:07:53.903", "Id": "270665", "Score": "0", "Tags": [ "mongodb", "pymongo" ], "Title": "Is there a way to speed up the group stage of the MongoDB aggregation pipeline?" }
270665
<p>I have two rest application say a1 and a2 which is running on different containers. From a1 application i am calling the service exposed by a2 application for some processing. I am using okhttp to call the rest end point exposed by a2 and i am providing a callback url in request body. Once the request is received on a2 , it will start processing and once done , it will send the result back to a1 using the callback url shared in body. On a1 , i am sending post call something like below</p> <pre><code> CompletableFuture future = new CompletableFuture&lt;&gt;(); client.newCall(request).enqueue(new callback{ @Override public void onFailure(Call call, IOException e) { future.completeExceptionally(e); } @Override public void onResponse(Call call, Response response) throws IOException { future.complete(response); } }); </code></pre> <p>Now i am stuck here, how should i make the call to wait here and once a2 call the callback url, this call should resume and send back the data to the caller without breaking the async behavior. Any input highly appreciated.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T15:41:19.760", "Id": "270668", "Score": "0", "Tags": [ "java", "rest", "callback" ], "Title": "Callback Url example with Okhtp" }
270668
<p>I implemented this carousel component in react:</p> <pre><code>import React from &quot;react&quot;; import { AiOutlineArrowLeft, AiOutlineArrowRight } from &quot;react-icons/ai&quot;; import { useResizeDetector } from &quot;react-resize-detector&quot;; let arrowStyle = { background: &quot;white&quot;, border: &quot;1px solid lightgray&quot;, borderRadius: &quot;20%&quot;, cursor: &quot;pointer&quot;, display: &quot;flex&quot;, justifyContent: &quot;center&quot;, alignItems: &quot;center&quot;, height: 30, width: 30, boxShadow: &quot;rgba(0, 0, 0, 0.24) 0px 3px 8px&quot;, }; export default function Carousel(props) { let [count, setCount] = React.useState(0); let innerContainer = React.useRef(); // We use these coordinates to know if we should show left/right arrows or not let [relativeCords, setRelativeCords] = React.useState({}); // We use this variable because during transition if user clicks multiple times the arrow buttons, coordinates are not computed correctly anymore let [transitionBlock, setTransitionBlock] = React.useState(false); let innerContainerRelativeCordsToParent = () =&gt; { let relativeLeft = innerContainer.current.getBoundingClientRect().left - ref.current.getBoundingClientRect().left; let relativeRight = ref.current.getBoundingClientRect().right - innerContainer.current.getBoundingClientRect().right; setRelativeCords({ relativeLeft, relativeRight }); }; const onResize = React.useCallback(() =&gt; { // When main container is resized we want to update relative coordinates innerContainerRelativeCordsToParent(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const { ref } = useResizeDetector({ onResize }); React.useEffect(() =&gt; { innerContainerRelativeCordsToParent(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); React.useEffect(() =&gt; { // We need to run this also when transition ends to get fresh coordinates innerContainer.current.addEventListener(&quot;transitionend&quot;, () =&gt; { innerContainerRelativeCordsToParent(); setTransitionBlock(false); }); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( &lt;div className=&quot;carousel&quot; style={{ padding: 50 }}&gt; &lt;div style={{ paddingLeft: 50, position: &quot;relative&quot;, paddingRight: 50, }} &gt; &lt;div ref={ref} style={{ overflow: &quot;hidden&quot;, }} &gt; {/* If you have height issues with below div, see this: https://stackoverflow.com/questions/27536428/inline-block-element-height-issue */} &lt;div ref={innerContainer} style={{ display: &quot;inline-block&quot;, whiteSpace: &quot;nowrap&quot;, transition: &quot;transform 0.4s linear&quot;, transform: `translateX(${-count * 100}px)`, }} &gt; {props.items.map((x) =&gt; { return ( &lt;div key={x.id} style={{ padding: 5, display: &quot;inline-block&quot;, width: 150, height: 150, marginLeft: 5, marginRight: 5, border: &quot;1px solid lightgray&quot;, borderRadius: 10, overflow: &quot;auto&quot;, whiteSpace: &quot;normal&quot;, }} &gt; &lt;h1&gt;{x.title}&lt;/h1&gt; &lt;p&gt;{x.body}&lt;/p&gt; &lt;/div&gt; ); })} &lt;/div&gt; &lt;/div&gt; &lt;button style={{ ...arrowStyle, position: &quot;absolute&quot;, left: 0, top: &quot;50%&quot;, transform: &quot;translateY(-50%)&quot;, }} disabled={relativeCords.relativeLeft &gt;= 0} onClick={() =&gt; { if (transitionBlock) return; setCount(count - 1); setTransitionBlock(true); }} &gt; &lt;AiOutlineArrowLeft /&gt; &lt;/button&gt; &lt;button style={{ ...arrowStyle, position: &quot;absolute&quot;, right: 0, top: &quot;50%&quot;, transform: &quot;translateY(-50%)&quot;, }} disabled={relativeCords.relativeRight &gt;= 0} onClick={() =&gt; { if (transitionBlock) return; setCount(count + 1); setTransitionBlock(true); }} &gt; &lt;AiOutlineArrowRight /&gt; &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; ); } </code></pre> <p>Any feedback welcome. Here is demo: <a href="https://stackblitz.com/edit/react-vu1aqp?file=src%2Findex.js" rel="nofollow noreferrer">https://stackblitz.com/edit/react-vu1aqp?file=src%2Findex.js</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T16:10:14.610", "Id": "270670", "Score": "2", "Tags": [ "css", "image", "react.js", "jsx" ], "Title": "Carousel in react" }
270670
<p>I think I programmed a bottom-up merge sort, but I'm a little sceptical that it will work under any data set. By now, I've tested it with many random arrays of massive lengths, and it seems to work; the only thing making me doubt my function is that whenever I look online for a non-recursive one, all of the algorithms by other people are much longer than mine (in terms of the number of lines of code). This makes me suspect I have missed out something important form my function. Here is my work:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function mergeSort(list) { list = list.map(n =&gt; [n]); while(list.length &gt; 1) { list.push(merge(list[0], list[1])); list.splice(0, 2); } return list[0]; }</code></pre> </div> </div> </p> <h2>the <code>merge</code> function is here:</h2> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function merge(lista, listb) { let newList = new Array(); while(lista.length &amp;&amp; listb.length) { const listToProcess = lista[0] &lt; listb[0] ? lista : listb; newList.push(listToProcess[0]); listToProcess.shift(); } const listWithRemainingElmnts = lista.length ? lista : listb; newList = newList.concat(listWithRemainingElmnts); return newList; }</code></pre> </div> </div> </p> <p>Why are all of the online examples of bottom-up MergeSort so large compared to mine?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T16:29:14.657", "Id": "270671", "Score": "1", "Tags": [ "javascript", "algorithm", "array", "mergesort" ], "Title": "Bottom-up merge sort" }
270671
<p>I have just started learning Java last month and started the java snake game program. I need to write a java snake game where the snake grows when it eats an apple, and dies when it touches itself. The goal of Snake is to create a snake as long as possible. When the snake reaches the end of the screen, it will re-emerge at the other end, so it isn't game over. There are no walls in this game.</p> <p>I have written most methods for this program, but I don't understand why the snake isn't moving although its method is called in processAlarm, which is called in the while loop under processEvent. This is the code related to how the snake moves in my program:</p> <p><strong>SnakeBody class</strong></p> <pre><code>public class SnakeBody { static final int MAX_NO_OF_Coordinates = 9999999; int bodyLength; Coordinate[] position; int numberOfElements; SnakeBody() { position = new Coordinate[MAX_NO_OF_Coordinates]; numberOfElements = 0; } public int growSnakeBody(Coordinate coordinate) { position[numberOfElements] = coordinate; numberOfElements++; return bodyLength = numberOfElements; } void moveSnake(Coordinate coordinate) { for (int i = numberOfElements; i &gt;= 1; i--) { position[i] = position[i - 1]; } position[0] = coordinate; } </code></pre> <p>}</p> <p><strong>Snake (main) class</strong></p> <pre><code>import ui.Event; import ui.SnakeUserInterface; import ui.UserInterfaceFactory; import ui.properties.GridScreen; import ui.UIAuxiliaryMethods; import Snake.SnakeBody; public class Snake { SnakeUserInterface ui; static final int WIDTH = 32; static final int HEIGHT = 24; static int EMPTY; public static int FOOD; Coordinate APPLE; String direction; SnakeBody snake; int bodyLength; Snake() { ui = UserInterfaceFactory.getSnakeUI(WIDTH, HEIGHT); snake = new SnakeBody(); direction = &quot;RIGHT&quot;; } void proccessEvent(Event event) { if (event.name.equals(&quot;arrow&quot;)) { processArrow(event.data); } else if (event.name.equals(&quot;alarm&quot;)) { processAlarm(); } } void processAlarm() { Coordinate newHead = changeDirection(direction); snake.growSnakeBody(newHead); // check for eat apple // if it ate apple --&gt; grow // if not, don't grow snake.moveSnake(newHead); // gameOver(); // checksIfAppleIsEaten(newHead); ui.showChanges(); } void start() { ui.setFramesPerSecond(1); initialSnakePosition(); while (true) { Event event = ui.getEvent(); ui.printf(&quot;%s - %s \n&quot;, event.name, event.data); foodPosition(); proccessEvent(event); } } // void checksIfAppleIsEaten(Coordinate coordinate) { // // if(currentPosition() = foodPosition() ){ // Coordinate snakeBody() = new growSnakeBody(); // } // } void processArrow(String data) { if (data.equals(&quot;U&quot;) &amp;&amp; !direction.equals(&quot;DOWN&quot;)) { direction = &quot;UP&quot;; } else if (data.equals(&quot;L&quot;) &amp;&amp; !direction.equals(&quot;RIGHT&quot;)) { direction = &quot;LEFT&quot;; } else if (data.equals(&quot;R&quot;) &amp;&amp; !direction.equals(&quot;LEFT&quot;)) { direction = &quot;RIGHT&quot;; } else if (data.equals(&quot;D&quot;) &amp;&amp; !direction.equals(&quot;UP&quot;)) { direction = &quot;DOWN&quot;; } changeDirection(direction); } void initialSnakePosition() { ui.place(0, 0, ui.SNAKE); ui.place(0, 1, ui.SNAKE); Coordinate snakeTail = new Coordinate(0, 0); Coordinate snakeHead = new Coordinate(0, 1); snake.growSnakeBody(snakeHead); snake.growSnakeBody(snakeTail); //foodPosition(); ui.showChanges(); // SnakeBody.moveSnake(snakeHead); } // void currentPosition(Coordinate coordinate) { // // } // void foodPosition() { int appleX = UIAuxiliaryMethods.getRandom(0, 32); int appleY = UIAuxiliaryMethods.getRandom(0, 24); APPLE = new Coordinate(appleX, appleY); ui.place(APPLE.x, APPLE.y, FOOD); ui.showChanges(); } Coordinate changeDirection(String direction) { Coordinate oldHead = snake.position[0]; Coordinate newHead = new Coordinate(oldHead.x, oldHead.y); if (direction.equals(&quot;LEFT&quot;)) { newHead.x -= 1; } else if (direction.equals(&quot;DOWN&quot;)) { newHead.y += 1; } else if (direction.equals(&quot;RIGHT&quot;)) { newHead.x += 1; } else if (direction.equals(&quot;UP&quot;)) { newHead.y -= 1; } snake.moveSnake(newHead); newHead = placeTranslucent(newHead); return newHead; } Coordinate placeTranslucent(Coordinate newHead) { if (direction.equals(&quot;RIGHT&quot;) &amp;&amp; newHead.x &gt; WIDTH) { newHead = new Coordinate(0, newHead.y); } else if (direction.equals(&quot;LEFT&quot;) &amp;&amp; newHead.x &lt; 0) { newHead = new Coordinate(WIDTH, newHead.y); } else if (direction.equals(&quot;UP&quot;) &amp;&amp; newHead.y &lt; 0) { newHead = new Coordinate(newHead.x, HEIGHT); } else if (direction.equals(&quot;DOWN&quot;) &amp;&amp; newHead.y &gt; HEIGHT) { newHead = new Coordinate(newHead.x, 0); } return newHead; } void continueDirection(Coordinate newHead) { // if it reaches end of screen, it returns to the beginning of the same row // if(processEvent(event) != processArrow(event.data)) { placeTranslucent(newHead); // snakeHead.x = 0; // snakeHead = new Coordinate(snakeHead.x , snakeHead.y); } boolean checkForCollision(SnakeBody snake) { for (int i = 0; i &lt; bodyLength; i++) { if ((snake.position[0] == snake.position[i])) { return true; } } return false; } void gameOver(SnakeBody snake) { // stops game when snake touches its tail if (checkForCollision(snake) == true) { ui.clear(); ui.printf(&quot;GAME OVER&quot;); initialSnakePosition(); } } public static void main(String[] args) { new Snake().start(); } } <span class="math-container">````</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T17:24:25.793", "Id": "534663", "Score": "0", "body": "You also took out some code. In SnakeBody there's a bodyLength that's used but not defined. And in Snake, there's a foodPosition method that was removed.\nYou would need to post all of the code, rather than taking out some parts. If that is all of the code, then I wouldn't expect it to compile." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T17:57:58.230", "Id": "534667", "Score": "0", "body": "@Xtros I have asked a question before about this, and they downvoted it because I gave all my code, while they only wanted the relevant code. So I took their advice and only wrote relevant code. But if I'm allowed to write all of my code I will do so. I will edit it with everything I've done up till now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T18:33:55.233", "Id": "534669", "Score": "0", "body": "Does ui.getEvent() block and wait until the user enters a key?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T18:40:13.850", "Id": "534673", "Score": "0", "body": "@Xtros, thank you so much. No, when i comment everything inside the processAlarm method, ( so I only have `void processAlarm() { }`, it still refreshes every second" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T18:45:58.950", "Id": "534678", "Score": "2", "body": "@Nancy To be clear [MCVE](https://stackoverflow.com/help/minimal-reproducible-example) is not a rule on Code Review. Your question is off-topic here (Code Review) because the code doesn't work as intended. We don't review such questions, only ones which work correctly. Once you figure out how to make the snake move (since \"Snake doesn't move\") we'd be happy to review your code. I'd also suggest posting all your code (unlike on Stack Overflow) for the reason Xtros outlined." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T19:04:23.067", "Id": "534681", "Score": "0", "body": "@Peilonrayz I have edited my code and added everything I did up till now. I know my code isn't working well but that's because I first need to at least figure out why it isn't moving. That's my main question, but wherever I ask why it isn't moving my question gets closed. After I make it move I can know exactly how to improve my code and what goes wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T20:10:49.157", "Id": "534686", "Score": "1", "body": "I think you could possibly get the question to be on-topic on Stack Overflow. However, doing so would require quite a bit of knowledge and skill working with the MCVE rule. Since you've asked twice on SO I'd recommended not trying to post on Stack Overflow again. As such, I don't think your question is a good fit for the Stack Exchange network. Code Review is for improving the quality of code, which is not what you want. We (Code Review) don't provide the service you want." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T20:22:55.673", "Id": "534687", "Score": "0", "body": "@Peilonrayz I understand, thank you very much for your reply" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T16:55:25.367", "Id": "270672", "Score": "-2", "Tags": [ "java", "eclipse" ], "Title": "Snake doesn't move in Java snake game" }
270672
<p>I have implemented the bulls and cows game in C++. The code:</p> <pre><code>#include &lt;cstdio&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; struct DigitMatches { int matches_in_right_positions; int matches_in_wrong_positions; }; void CountNumberDigits(int (&amp;counts)[10], int n) { while (n &gt; 0) { counts[n % 10]++; n /= 10; } } class DigitsMatchChecker { public: DigitMatches CheckMatchedDigits(int generated_number, int guess_number) { CountNumberDigits(this-&gt;generated_number_left_digits_, generated_number); CountNumberDigits(this-&gt;guess_number_left_digits_, guess_number); DigitMatches matches; matches.matches_in_right_positions = this-&gt;CountMatchesInRightPositions(generated_number, guess_number); matches.matches_in_wrong_positions = this-&gt;CountMatchesInWrongPositions(guess_number); return matches; } private: int CountMatchesInRightPositions(int generated_number, int guess_number) { int matches = 0; while (generated_number &gt; 0 &amp;&amp; guess_number &gt; 0) { const int generated_number_digit = generated_number % 10; const int guess_number_digit = guess_number % 10; if (generated_number_digit == guess_number_digit) { matches++; this-&gt;guess_number_left_digits_[generated_number_digit]--; this-&gt;generated_number_left_digits_[generated_number_digit]--; } generated_number /= 10; guess_number /= 10; } return matches; } int CountMatchesInWrongPositions(int guess_number) { int matches = 0; while (guess_number &gt; 0) { const int guess_number_digit = guess_number % 10; int &amp;generated_number_left_digits = this-&gt;generated_number_left_digits_[guess_number_digit]; int &amp;guess_number_left_digits = this-&gt;guess_number_left_digits_[guess_number_digit]; if (generated_number_left_digits &gt; 0 &amp;&amp; guess_number_left_digits &gt; 0) { matches++; generated_number_left_digits--; guess_number_left_digits--; } guess_number /= 10; } return matches; } private: int generated_number_left_digits_[10] = {}; int guess_number_left_digits_[10] = {}; }; void InitializeRandomNumberGenerator() { srand(time(nullptr)); } int GenerateNumber(int min, int max) { return min + (rand() % (max - min + 1)); } int InputNumber() { int n; scanf(&quot;%d&quot;, &amp;n); return n; } int main() { InitializeRandomNumberGenerator(); const int kTotalNumberOfDigits = 4; const int generated_number = GenerateNumber(1000, 9999); int attempts = 0; while (true) { const int guess_number = InputNumber(); if (guess_number &lt; 1000 || guess_number &gt; 9999) { printf(&quot;Invalid number. Must be between 1000 and 9999.\n&quot;); continue; } const DigitMatches matches = DigitsMatchChecker().CheckMatchedDigits(generated_number, guess_number); printf(&quot;%d cows, %d bulls\n&quot;, matches.matches_in_right_positions, matches.matches_in_wrong_positions); attempts++; if (matches.matches_in_right_positions == kTotalNumberOfDigits) break; } printf(&quot;You won! Attempts: %d\n&quot;, attempts); return 0; } </code></pre> <p>I would like to hear objective criticism and comments on my code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T18:40:14.560", "Id": "534674", "Score": "0", "body": "Can you provide a bit more introduction for those of us who have never heard of \"the bulls and cows game\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T18:59:08.580", "Id": "534679", "Score": "0", "body": "@TobySpeight, https://en.wikipedia.org/wiki/Bulls_and_Cows. In my case, cows is guessed digits in right positions, bulls is guessed digits in wrong positions. It is a popular programming problem, you can find other descriptions of this game on google." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T19:06:27.813", "Id": "534682", "Score": "0", "body": "Briefly, computer generates a number. User need to guess the number. After each guess the system returns a number of cows and bulls. Cows means the number of guessed digits in right positions. Bulls is the number of guessed digitis in wrong positions. If there is no such digit in generated number, then no cows and bulls added. User wins when guessed all digits in right positions (guessed whole number)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T23:52:06.550", "Id": "534700", "Score": "0", "body": "Please add the necessary info to your question. Comments are ephemeral and subject to deletion." } ]
[ { "body": "<p>Thoughts:</p>\n<ol>\n<li>The names are descriptive.</li>\n<li>This is supposed to be C++ but all of the libraries are from C -- my compiler complains about scanf (changed to scanf_s) as unsafe.</li>\n<li>Ask yourself &quot;Why did I make a class?&quot; A class is a container for data and code - it defined an object; a &quot;thing&quot; in memory that gets instantiated - and hopefully used. You have created a class that is basically a container for a function. It falls short of being a functor because it does not really maintain its state. Creating a class that held the <code>generated_number</code> as a private variable (or just its digits) and exposed a function to check guesses might be a more logical direction.</li>\n<li>Did you really need to declare those local variables as 'const'? Const correctness <em>is important</em> and it certainly didn't hurt but that usually refers to arguments to functions and return values etc. i.e. it is used to communicate to others reading/using your code and the compiler when something should be const. With temporary locals, it is not important (but does not hurt anything). -- maybe I have something to learn here. I will think on it more.</li>\n<li>Reusing the name <code>matches</code> with different types is a bit confusing. Again not BAD but a bit confusing - when a variable graduates to having its own name (as opposed to just i, or x, count, etc.) it is generally is unique within a class or used in a consistent manner (i.e. several functions may have a <code>matches</code> but they would all be of the same type and used in a similar way).</li>\n<li><code>generated_number_left_digits</code> should really just be <code>generated_number_left_digit</code> should it not? -- You are referencing just the one element from a similarly named array. Honestly, just a name like <code>generated_digit</code> would be fine. Self-documenting code is wonderful -- but brevity is also to be desired.</li>\n<li>Why is <code>CountNumberDigits</code> not a member function? Do you really expect to need that function elsewhere?</li>\n</ol>\n<p>Ask yourself -- what are the likely upgrade paths? Like if users like your game what might they ask for next? More digits perhaps? Using letters and numbers together? etc. How hard would it be to modify this code to work and 8 character hexidecimal strings rather than 4 digit decimal?</p>\n<p>We want to strive towards generality/abstractness in our code - without sacrificing too much on readability and simplicity. C++ proper, as opposed to the kind of C + &quot;a class&quot; code you have here, offers a lot of features for making things more general.</p>\n<p>My advice would be to try to do this again in a more C++ way and less C-ish. You can keep the <code>rand()</code> and <code>srand()</code> -- but try to work in some of the C++ standard libraries. I don't just mean cout/cin but C++ data structures/enumerators/algorithms. <code>CountNumberOfDigits</code> just seems to scream re-write with enumerators to me...</p>\n<p>Also, try to think about how to automate testing. Since your code uses stdin/stdout is actually IS pretty easy to feed it a script but that tests the &quot;whole thing&quot;. Maybe try to make sure it is easy to write test cases...</p>\n<p>I don't know your level of programming but I would say this was pretty good code. It seemed to work, I found it pretty readable and logical to follow. It is not Object Oriented programming but one does not need to view everything in C++ as OOP. Your code was rearranging a bunch of C functions to fit into a class - this is from the school of &quot;C with classes&quot; programming and falls short of C++ programming.</p>\n<p>Keep it up.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-05T00:45:37.770", "Id": "270690", "ParentId": "270673", "Score": "0" } } ]
{ "AcceptedAnswerId": "270690", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T18:02:45.850", "Id": "270673", "Score": "0", "Tags": [ "c++", "object-oriented" ], "Title": "The bulls and cows game" }
270673
<p>I'm learning rust and doing an exercise where to parse a particular SGML document. Each line in a document can be either an opening tag &quot;&quot; , a closing tag &quot;&quot; or a scalar: &quot; Val&quot;. I'm using a regex with named capture groups to detect and extract, and would like to return an enum afterwards.</p> <p>I came up with the following code, but it feels overly verbose and un-idiomatic, so I'm seeking feedback, particularly on the <em>extract_tag_from_line_match</em> function</p> <pre class="lang-rust prettyprint-override"><code> use regex::Captures; use regex::Regex; struct LineParseError; enum Tag { Open(String), Close(String), Scalar(String, String), } fn extract_line_tag(line: &amp;str) -&gt; Result&lt;Tag, LineParseError&gt; { let reg: Regex = Regex::new(r&quot;&lt;((?P&lt;close&gt;/))|((?P&lt;open&gt;.+)&gt;(?P&lt;value&gt;.+)?)&quot;).unwrap(); let capture = reg.captures(line); match capture { None =&gt; Err(LineParseError), Some(cap) =&gt; Ok(extract_tag_from_line_match(cap)), } } fn extract_tag_from_line_match(capture: Captures) -&gt; Tag { let close = capture.name(&quot;close&quot;); let open = capture.name(&quot;open&quot;); let value = capture.name(&quot;value&quot;); let scalar = open.zip(value); if (scalar.is_some()) { let (o, v) = scalar.unwrap(); return Tag::Scalar(String::from(o.as_str()), String::from(v.as_str())); } else if close.is_some() { let c = close.unwrap(); return Tag::Close(String::from(c.as_str())); } else { let v = open.unwrap(); return Tag::Open(String::from(v.as_str())); } } </code></pre>
[]
[ { "body": "<p>Hello and welcome to the Rust community.</p>\n<h2>Correctness</h2>\n<p>Are you sure the code is correct? The regex looks odd, but ok. It seems that <code>Tag::Close</code> does not carry any meaningful info, even though it contains a String.</p>\n<h2>Manual</h2>\n<p>Be sure to read up on <code>if let</code> statements. They are useful for concise and idiomatic code. Here, catch some reading material:</p>\n<ul>\n<li><a href=\"https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html\" rel=\"nofollow noreferrer\">https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html</a></li>\n<li><a href=\"https://www.geeksforgeeks.org/rust-if-let-operator/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/rust-if-let-operator/</a></li>\n<li><a href=\"https://doc.rust-lang.org/book/ch06-03-if-let.html\" rel=\"nofollow noreferrer\">https://doc.rust-lang.org/book/ch06-03-if-let.html</a></li>\n</ul>\n<h2>Nitpicks</h2>\n<ul>\n<li>I changed <code>String::from</code> to <code>.to_string()</code>.</li>\n<li>I believe you confused <code>v</code> with <code>o</code> in the last branch.</li>\n<li>Don't use single letter variable names too often. (I didn't change this below.)</li>\n</ul>\n<h2>Code</h2>\n<pre class=\"lang-rust prettyprint-override\"><code>use regex::Captures;\nuse regex::Regex;\n\n#[derive(Debug)]\nstruct LineParseError;\n#[derive(Debug)]\nenum Tag {\n Open(String),\n Close(String),\n Scalar(String, String),\n}\nfn extract_line_tag(line: &amp;str) -&gt; Result&lt;Tag, LineParseError&gt; {\n let reg: Regex = Regex::new(r&quot;&lt;((?P&lt;close&gt;/))|((?P&lt;open&gt;.+)&gt;(?P&lt;value&gt;.+)?)&quot;).unwrap();\n\n let capture = reg.captures(line);\n match capture {\n None =&gt; Err(LineParseError),\n Some(cap) =&gt; Ok(extract_tag_from_line_match(cap)),\n }\n}\n\nfn extract_tag_from_line_match(capture: Captures) -&gt; Tag {\n let close = capture.name(&quot;close&quot;);\n let open = capture.name(&quot;open&quot;);\n let value = capture.name(&quot;value&quot;);\n\n let scalar = open.zip(value);\n if let Some((o, v)) = scalar {\n return Tag::Scalar(o.as_str().to_string(), v.as_str().to_string());\n } else if let Some(c) = close {\n return Tag::Close(c.as_str().to_string());\n } else if let Some(o) = open {\n return Tag::Open(o.as_str().to_string());\n } else {\n unreachable!();\n }\n}\n\nfn main() {\n println!(&quot;{:?}&quot;, extract_line_tag(&quot;&lt;val&gt;&quot;));\n println!(&quot;{:?}&quot;, extract_line_tag(&quot;&lt;/val&gt;&quot;));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T19:27:17.540", "Id": "534685", "Score": "0", "body": "Thanks! And double thanks for the super fast help.\nI have a question about to_string() . \n\nBeing lazy, would it be idiomatic to add a trait to the regex::Match to_string() so that I wouldn't have to write out to_str().to_string() ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T19:11:55.443", "Id": "270678", "ParentId": "270675", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T18:46:58.743", "Id": "270675", "Score": "2", "Tags": [ "beginner", "rust" ], "Title": "Idiomatic way to extract matches from rust Regex?" }
270675
<p>In one of my homework projects, I have to parse a matrix definition into a matrix data structure in C. The elements of the matrix will be given in a list of double. I need a simple tokenizer and parser for the task naturally, but I have not much experience in parsing. I implemented the tokenizer and parser. The tokenizer produces a few types of tokens. The list of token types includes <code>tokEot</code> (ie. End of tokens), <code>tokId</code>, <code>tokNumber</code>, <code>tokOparen</code>, <code>tokCparen</code>, <code>tokComma</code>, <code>tokAssign</code>. The matrix definition will be in the form of <code>identifier(Integer, Integer) = ( Real Number, Real Number, ... , Real Number)</code>. The input can have more than one matrix definition. The name of the data structure for the tokenizer is <code>scanner</code>. I have no data structure for the parser, implemented it in a single function(<code>parse_matrix</code>). I need also error checking in the parsing stage, so if the order in the definition of a matrix is not be followed, then I must report an error and exit the program. You can look at the supplementary code for more details. The program works without any problems. However, since I need a code review specifically for the function <code>parse_matrix</code> and it might be redundant, I don't want to include the source code of the tokenizer (maybe in another question). Here is the code with the all necessary parts.</p> <pre><code>typedef struct matrix { char* name; // The name of the matrix, the parsed identifiers will be stored here. int m; // The number of rows int n; // The number of cols double* elements; // A chunk of doubles }matrix; // The enum for the token types typedef enum token_type { tokEot, // End of tokens tokId, // Identifier tokNumber, // Either int or double tokOparen, // ( tokCparen, // ) tokComma, // , tokAssign, // = tokCount }token_type; typedef struct token_t { token_type type; union { double data_double; char* data_string; int data_int; }; }token_t; typedef struct scanner { token_t current_token; // Last generated token char* input_string; // Input string that contains matrix definitions char* current_char; // Current character to be processed. }scanner; token_t next_token(scanner* pthis); matrix* parse_matrix(scanner* pscanner); void handle_error(const char* error_text); matrix* new_matrix(char* name, int m, int n); int main() { char* input = &quot;mat1(3, 3) = ( 1.0, -3.0, 5.0, &quot; &quot;2.0, -1.0, 5.0, &quot; &quot;1.0, -3.0, 5.0 )&quot;; scanner* float_scanner = new_scanner(input); matrix* mat1 = parse_matrix(float_scanner); system(&quot;pause&quot;); } matrix* new_matrix(char* name, int m, int n) { matrix* mat = malloc(sizeof(matrix)); mat-&gt;m = m; mat-&gt;n = n; mat-&gt;name = name; mat-&gt;elements = malloc(sizeof(double) * m * n); return mat; } // tokId --&gt; ( --&gt; Int --&gt; , --&gt; Int --&gt; ) --&gt; = --&gt; ( --&gt; Double --&gt; , --&gt; Double ... --&gt; ) matrix* parse_matrix(scanner* pthis) { matrix* mat; int count = 0; char* id_name = NULL; int m = 0; int n = 0; token_t pre_token; token_t token; do { token = next_token(pthis); //If token type is a identifier, then we will try to parse a matrix declaration. if (token.type == tokId) { // Duplicate the token data id_name = strdup(token.data_string); token = next_token(pthis); // I must have an open parenthesis after an identifier if (token.type == tokOparen) { token = next_token(pthis); // Parsing the dimensions of the matrix if (token.type == tokNumber) { m = token.data_int; token = next_token(pthis); // There is a comma between the dimensions of matrix if (token.type == tokComma) { token = next_token(pthis); // A number must follow the comma if (token.type == tokNumber) { n = token.data_int; token = next_token(pthis); if (token.type == tokCparen) { // Allocate the matrix with the specified dimensions. mat = new_matrix(id_name, m, n); token = next_token(pthis); if (token.type == tokAssign) { token = next_token(pthis); if (token.type == tokOparen) { token = next_token(pthis); // Finally, parse the elements. if (token.type == tokNumber) *(mat-&gt;elements + count++) = token.data_double; else handle_error(&quot;Expected a number after open paranthesis.&quot;); do { token = next_token(pthis); if (token.type == tokCparen) break; if (token.type == tokComma) { token = next_token(pthis); if (token.type == tokNumber) *(mat-&gt;elements + count++) = token.data_double; else handle_error(&quot;Expected a number after a comma.&quot;); } else handle_error(&quot;Expected a comma after a number.&quot;); } while (token.type != tokCparen); // If the user didn't specificy enough elements, we should // fill the rest with zero. if (count &lt; m * n) for (int i = count; i &lt; m * n; i++) *(mat-&gt;elements + i) = 0.0; return mat; } else handle_error(&quot;Expected an open parenthesis after an assignment.&quot;); } else handle_error(&quot;Expected an assigment.&quot;); } else handle_error(&quot;Expected a close parenthesis.&quot;); } else handle_error(&quot;Expected a integer number.&quot;); } else handle_error(&quot;Expected a comma.&quot;); } else handle_error(&quot;Expected a integer number.&quot;); } else handle_error(&quot;Expected an open parenthesis.&quot;); } } while (token.type != tokEot); } void handle_error(const char* error_text) { perror(error_text); exit(-1); } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Code looks pretty good. I prefer some other <a href=\"https://www.doc.ic.ac.uk/lab/cplus/cstyle.html\" rel=\"nofollow noreferrer\">style guide</a>, but this looks consistent, and consistency is important too.</p>\n<h3>Indentation</h3>\n<p>Arbitrarily, you can spell the string constant like this:</p>\n<pre><code>char* input = \n &quot;mat1(3, 3) = &quot;\n &quot;( 1.0, -3.0, 5.0, &quot;\n &quot;2.0, -1.0, 5.0, &quot;\n &quot;1.0, -3.0, 5.0 )&quot;;\n</code></pre>\n<p>Placing the similar tokens directly one under another can find errors in those tokens in a moment.</p>\n<h3>Unit tests</h3>\n<p>You should test your code. There are literally dozens of <a href=\"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C\" rel=\"nofollow noreferrer\">unit test frameworks for C</a>; and using unit tests will make you immediately find if new changes would break something later. Just do it. Besides, you're <em>already</em> testing the code, but in a much less efficient way - this code has one test in a <code>main()</code> function.</p>\n<h3>Mixing model and presentation</h3>\n<p>Data transformations should be some inner job, usually called model, while reporting errors to user is for presentation. The parser would be much more portable and reusable if it wouldn't rely on a specific output system, maybe returning NULL on errors.</p>\n<h3><code>system(&quot;pause&quot;);</code></h3>\n<p>The worst thing in this code. It relies on specific OS and calls a far more complex program than this one for just one discarded input. Your IDE probably has some tools to capture the output after the program exit, just <a href=\"https://stackoverflow.com/questions/1107705/systempause-why-is-it-wrong\">look for it</a>.</p>\n<h3><code>if-else</code> staircase</h3>\n<p>I think this is why you've posted the code here. Well, it may be a good habit to put more likely option into the <code>if</code> branch and less likely into the <code>else</code>; but here the execution stops on <code>handle_error</code>, so it can be rewritten in a much more linear way:</p>\n<pre><code>token = next_token(pthis); \nif (token.type != tokOparen)\n handle_error(&quot;Expected an open parenthesis.&quot;);\n\ntoken = next_token(pthis);\nif (token.type != tokNumber)\n handle_error(&quot;Expected a integer number.&quot;);\n</code></pre>\n<p>etc. This will make the code not so structured (though it isn't structured now), but much more readable - except for one detail. It's not clear for readers that <code>handle_error</code> breaks the execution. So, maybe, it should be something like</p>\n<pre><code>token = next_token(pthis); \nif (token.type != tokOparen)\n return handle_error(&quot;Expected an open parenthesis.&quot;);\n\ntoken = next_token(pthis);\nif (token.type != tokNumber)\n return handle_error(&quot;Expected a integer number.&quot;);\n</code></pre>\n<p>This looks much better. Of course, <code>handle_error</code> now should <code>return NULL</code> after <code>exit(-1)</code>. Maybe commented out to avoid compiler warnings.</p>\n<p>One other option for such situations is a <code>do-while(false);</code> construction:</p>\n<pre><code>do { //while(false) - you should always comment this\n do_some_work();\n if(something_wrong())\n break;\n\n do_some_more_work();\n if(one thing more wrong)\n break;\n\n do_even_more_work();\n if(still wrong)\n break;\n\n do_final_work();\n} while(false);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T21:01:08.977", "Id": "270683", "ParentId": "270677", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T19:09:56.540", "Id": "270677", "Score": "1", "Tags": [ "c", "parsing" ], "Title": "Parsing A Simple Matrix Definition In C" }
270677
<p>My code is working but it is extremely long. So, I guess there is a way to make it shorter/more efficient.</p> <p>The problem solved here is from Advent of Code 2021, Day 3, Part 1: <a href="https://adventofcode.com/2021/day/3" rel="nofollow noreferrer">https://adventofcode.com/2021/day/3</a></p> <pre><code>binary_list = open(&quot;data.txt&quot;).read().split(&quot;\n&quot;) counter_1st_bit_0 = 0 counter_1st_bit_1 = 0 counter_2nd_bit_0 = 0 counter_2nd_bit_1 = 0 counter_3rd_bit_0 = 0 counter_3rd_bit_1 = 0 counter_4th_bit_0 = 0 counter_4th_bit_1 = 0 counter_5th_bit_0 = 0 counter_5th_bit_1 = 0 counter_6th_bit_0 = 0 counter_6th_bit_1 = 0 counter_7th_bit_0 = 0 counter_7th_bit_1 = 0 counter_8th_bit_0 = 0 counter_8th_bit_1 = 0 counter_9th_bit_0 = 0 counter_9th_bit_1 = 0 counter_10th_bit_0 = 0 counter_10th_bit_1 = 0 counter_11th_bit_0 = 0 counter_11th_bit_1 = 0 counter_12th_bit_0 = 0 counter_12th_bit_1 = 0 gamma_rate_queue = [] epsilon_rate_queue = [] for i in range(0, len(binary_list), 1): for j in range(0, len(binary_list[i]), 1): if binary_list[i][0] == &quot;0&quot;: counter_1st_bit_0 += 1 elif binary_list[i][0] == &quot;1&quot;: counter_1st_bit_1 += 1 if binary_list[i][1] == &quot;0&quot;: counter_2nd_bit_0 += 1 elif binary_list[i][1] == &quot;1&quot;: counter_2nd_bit_1 += 1 if binary_list[i][2] == &quot;0&quot;: counter_3rd_bit_0 += 1 elif binary_list[i][2] == &quot;1&quot;: counter_3rd_bit_1 += 1 if binary_list[i][3] == &quot;0&quot;: counter_4th_bit_0 += 1 elif binary_list[i][3] == &quot;1&quot;: counter_4th_bit_1 += 1 if binary_list[i][4] == &quot;0&quot;: counter_5th_bit_0 += 1 elif binary_list[i][4] == &quot;1&quot;: counter_5th_bit_1 += 1 if binary_list[i][5] == &quot;0&quot;: counter_6th_bit_0 += 1 elif binary_list[i][5] == &quot;1&quot;: counter_6th_bit_1 += 1 if binary_list[i][6] == &quot;0&quot;: counter_7th_bit_0 += 1 elif binary_list[i][6] == &quot;1&quot;: counter_7th_bit_1 += 1 if binary_list[i][7] == &quot;0&quot;: counter_8th_bit_0 += 1 elif binary_list[i][7] == &quot;1&quot;: counter_8th_bit_1 += 1 if binary_list[i][8] == &quot;0&quot;: counter_9th_bit_0 += 1 elif binary_list[i][8] == &quot;1&quot;: counter_9th_bit_1 += 1 if binary_list[i][9] == &quot;0&quot;: counter_10th_bit_0 += 1 elif binary_list[i][9] == &quot;1&quot;: counter_10th_bit_1 += 1 if binary_list[i][10] == &quot;0&quot;: counter_11th_bit_0 += 1 elif binary_list[i][10] == &quot;1&quot;: counter_11th_bit_1 += 1 if binary_list[i][11] == &quot;0&quot;: counter_12th_bit_0 += 1 elif binary_list[i][11] == &quot;1&quot;: counter_12th_bit_1 += 1 def gamma_rate_finder(): if counter_1st_bit_0 &gt; counter_1st_bit_1: gamma_rate_queue.append('0') elif counter_1st_bit_0 &lt; counter_1st_bit_1: gamma_rate_queue.append('1') if counter_2nd_bit_0 &gt; counter_2nd_bit_1: gamma_rate_queue.append('0') elif counter_2nd_bit_0 &lt; counter_2nd_bit_1: gamma_rate_queue.append('1') if counter_3rd_bit_0 &gt; counter_3rd_bit_1: gamma_rate_queue.append('0') elif counter_3rd_bit_0 &lt; counter_3rd_bit_1: gamma_rate_queue.append('1') if counter_4th_bit_0 &gt; counter_4th_bit_1: gamma_rate_queue.append('0') elif counter_4th_bit_0 &lt; counter_4th_bit_1: gamma_rate_queue.append('1') if counter_5th_bit_0 &gt; counter_5th_bit_1: gamma_rate_queue.append('0') elif counter_5th_bit_0 &lt; counter_5th_bit_1: gamma_rate_queue.append('1') if counter_6th_bit_0 &gt; counter_6th_bit_1: gamma_rate_queue.append('0') elif counter_6th_bit_0 &lt; counter_6th_bit_1: gamma_rate_queue.append('1') if counter_7th_bit_0 &gt; counter_7th_bit_1: gamma_rate_queue.append('0') elif counter_7th_bit_0 &lt; counter_7th_bit_1: gamma_rate_queue.append('1') if counter_8th_bit_0 &gt; counter_8th_bit_1: gamma_rate_queue.append('0') elif counter_8th_bit_0 &lt; counter_8th_bit_1: gamma_rate_queue.append('1') if counter_9th_bit_0 &gt; counter_9th_bit_1: gamma_rate_queue.append('0') elif counter_9th_bit_0 &lt; counter_9th_bit_1: gamma_rate_queue.append('1') if counter_10th_bit_0 &gt; counter_10th_bit_1: gamma_rate_queue.append('0') elif counter_10th_bit_0 &lt; counter_10th_bit_1: gamma_rate_queue.append('1') if counter_11th_bit_0 &gt; counter_11th_bit_1: gamma_rate_queue.append('0') elif counter_11th_bit_0 &lt; counter_11th_bit_1: gamma_rate_queue.append('1') if counter_12th_bit_0 &gt; counter_12th_bit_1: gamma_rate_queue.append('0') elif counter_12th_bit_0 &lt; counter_12th_bit_1: gamma_rate_queue.append('1') gamma_rate = ''.join(gamma_rate_queue) return gamma_rate def epsilon_rate_finder(): if counter_1st_bit_0 &lt; counter_1st_bit_1: epsilon_rate_queue.append('0') elif counter_1st_bit_0 &gt; counter_1st_bit_1: epsilon_rate_queue.append('1') if counter_2nd_bit_0 &lt; counter_2nd_bit_1: epsilon_rate_queue.append('0') elif counter_2nd_bit_0 &gt; counter_2nd_bit_1: epsilon_rate_queue.append('1') if counter_3rd_bit_0 &lt; counter_3rd_bit_1: epsilon_rate_queue.append('0') elif counter_3rd_bit_0 &gt; counter_3rd_bit_1: epsilon_rate_queue.append('1') if counter_4th_bit_0 &lt; counter_4th_bit_1: epsilon_rate_queue.append('0') elif counter_4th_bit_0 &gt; counter_4th_bit_1: epsilon_rate_queue.append('1') if counter_5th_bit_0 &lt; counter_5th_bit_1: epsilon_rate_queue.append('0') elif counter_5th_bit_0 &gt; counter_5th_bit_1: epsilon_rate_queue.append('1') if counter_6th_bit_0 &lt; counter_6th_bit_1: epsilon_rate_queue.append('0') elif counter_6th_bit_0 &gt; counter_6th_bit_1: epsilon_rate_queue.append('1') if counter_7th_bit_0 &lt; counter_7th_bit_1: epsilon_rate_queue.append('0') elif counter_7th_bit_0 &gt; counter_7th_bit_1: epsilon_rate_queue.append('1') if counter_8th_bit_0 &lt; counter_8th_bit_1: epsilon_rate_queue.append('0') elif counter_8th_bit_0 &gt; counter_8th_bit_1: epsilon_rate_queue.append('1') if counter_9th_bit_0 &lt; counter_9th_bit_1: epsilon_rate_queue.append('0') elif counter_9th_bit_0 &gt; counter_9th_bit_1: epsilon_rate_queue.append('1') if counter_10th_bit_0 &lt; counter_10th_bit_1: epsilon_rate_queue.append('0') elif counter_10th_bit_0 &gt; counter_10th_bit_1: epsilon_rate_queue.append('1') if counter_11th_bit_0 &lt; counter_11th_bit_1: epsilon_rate_queue.append('0') elif counter_11th_bit_0 &gt; counter_11th_bit_1: epsilon_rate_queue.append('1') if counter_12th_bit_0 &lt; counter_12th_bit_1: epsilon_rate_queue.append('0') elif counter_12th_bit_0 &gt; counter_12th_bit_1: epsilon_rate_queue.append('1') epsilon_rate = ''.join(epsilon_rate_queue) return epsilon_rate binary_gamma_rate = gamma_rate_finder() binary_epsilon_rate = epsilon_rate_finder() def Binary_to_DecimalValue(n): b_num = list(n) value = 0 for i in range(len(b_num)): digit = b_num.pop() if digit == '1': value = value + pow(2, i) return value gamma_rate = Binary_to_DecimalValue(binary_gamma_rate) epsilon_rate = Binary_to_DecimalValue(binary_epsilon_rate) PowerConsumption = gamma_rate * epsilon_rate print(&quot;Gamma rate is: {} | {}&quot;.format(gamma_rate, binary_gamma_rate) + &quot;\n&quot; + &quot;Epsilon rate is: {} | {}&quot;.format(epsilon_rate, binary_epsilon_rate) + &quot;\n&quot; + &quot;The Power Consumption is: {}&quot;.format(PowerConsumption)) </code></pre> <p>Any advice about my code would be helpful, I guess there is a way to replace lists here and to make the loops and functions more efficient.</p> <p>Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T21:47:55.830", "Id": "534692", "Score": "0", "body": "This seems like a very hardcoded way to go about things. For starters, I see a lot of `if` that should've been `elif`. What version of Python did you write this for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T22:28:24.773", "Id": "534695", "Score": "1", "body": "Why do you stop on _12th_ bit?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T23:09:18.033", "Id": "534696", "Score": "0", "body": "@vnp is appears that the sample given only has twelve lines of input. But it's not guaranteed for the puzzle input that I can see. @zаѓатhᵾѕтѓа Generally speaking, if you have variable names like `...5th...`, you need to step back and think if you should be using a list instead. And `for i in range(len(somelist))` is almost always the wrong approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-05T00:03:49.190", "Id": "534701", "Score": "0", "body": "@vnp For context, the input to this problem is randomized per user but the format of that input is constant: a list of 1,000 12-digit binary numbers. Which does justify hard-coding `12` here since the input will never contain a binary number that is not 12 digits long." } ]
[ { "body": "<p>I'm just going to make one suggestion, which you should be able to apply across a lot of your code.</p>\n<ol>\n<li>Use <a href=\"https://docs.python.org/3/tutorial/datastructures.html?highlight=list\" rel=\"nofollow noreferrer\"><code>list</code></a> structures, which are analogous to <em>arrays</em> in other languages.</li>\n</ol>\n<p>That's it. Lists.</p>\n<h2>Use lists for counting values</h2>\n<p>Your first use should be to replace the 0/1 variables in counting code:</p>\n<pre><code>counter_1st_bit_0 = 0\ncounter_1st_bit_1 = 0\n</code></pre>\n<p>Let's make those two variables into a single list with two elements:</p>\n<pre><code>counter_1st_bit = [0, 0]\n</code></pre>\n<p>(<em><strong>Note:</strong></em> the <code>[0, 0]</code> syntax is a list literal. These things are so common that Python supports typing them directly into the code.)</p>\n<p>Now you can access <code>counter_1st_bit[0]</code> and <code>counter_1st_bit[1]</code> as two separate values (which they are!) and update them based on your input:</p>\n<pre><code>if binary_list[i][0] == &quot;0&quot;:\n counter_1st_bit[0] += 1\nelif binary_list[i][0] == &quot;1&quot;:\n counter_1st_bit[1] += 1\n</code></pre>\n<p>Once you make that change, you can go one step farther and convert the string value to an integer value:</p>\n<pre><code>bit = int(binary_list[i][0])\nif bit == 0:\n counter_1st_bit[0] += 1\nelif bit == 1:\n counter_1st_bit[1] += 1\n</code></pre>\n<p>Then you realize that the bit value can <em>only</em> be either 0 or 1, so it's not <code>if</code> / <code>elif</code> but rather <code>if</code> / <code>else</code>:</p>\n<pre><code>bit = int(binary_list[i][0])\nif bit == 0:\n counter_1st_bit[0] += 1\nelse:\n counter_1st_bit[1] += 1\n</code></pre>\n<p>And <em>then</em> you realize that the 0 and 1 are the values of <code>bit</code>:</p>\n<pre><code>bit = int(binary_list[i][0])\nif bit == 0:\n counter_1st_bit[bit] += 1\nelse:\n counter_1st_bit[bit] += 1\n</code></pre>\n<p>And <em>then</em> you realize that the statements are the same, so you don't need the <code>if</code> and <code>else</code>:</p>\n<pre><code>bit = int(binary_list[i][0])\ncounter_1st_bit[bit] += 1\n</code></pre>\n<p>Now you're cooking with gas! Because you're only using the <code>bit</code> value one time, in one place, you can get rid of that variable:</p>\n<pre><code>counter_1st_bit[int(binary_list[i][0])] += 1\n</code></pre>\n<p>And you can make the same change across all the counter variables:</p>\n<pre><code>counter_1st_bit[int(binary_list[i][0])] += 1\ncounter_2nd_bit[int(binary_list[i][1])] += 1\ncounter_3rd_bit[int(binary_list[i][2])] += 1\ncounter_4th_bit[int(binary_list[i][3])] += 1\n:\ncounter_12th_bit[int(binary_list[i][11])] += 1\n</code></pre>\n<p>And <em>then</em> you realize that your <code>counter_xxx_bit</code> variables could be replaced by a <code>list</code> of 12 lists!</p>\n<pre><code># at start:\ncounter = [[0,0] for _ in range(12)]\n\n# in loop:\nfor j in range(0, len(binary_list[i]), 1):\n counter[j][int(binary_list[i][j])] += 1\n</code></pre>\n<p>(<em><strong>Note:</strong></em> The <code>[... for ... in ...]</code> syntax is called a <a href=\"https://docs.python.org/3/glossary.html#term-list-comprehension\" rel=\"nofollow noreferrer\"><strong>list comprehension</strong></a>. It's a shorthand that allows specifying the contents of a list as a single <em>expression.</em> This is super-valuable in places where statements are not permitted, like argument defaults and <em>lambda functions</em>. And initializing list variables...)</p>\n<p>You can probably see how to make similar changes to your <code>gamma</code> and <code>epsilon</code> computation functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-05T00:32:41.813", "Id": "534702", "Score": "0", "body": "Good answer, especially for its tight focus on using collections (lists, in this case) rather than a proliferation of individual variables." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T23:55:04.297", "Id": "270688", "ParentId": "270682", "Score": "3" } } ]
{ "AcceptedAnswerId": "270688", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T20:36:38.737", "Id": "270682", "Score": "3", "Tags": [ "python" ], "Title": "Inefficient Solution - Advent of Code 2021, Day 3, Part 1" }
270682